(()=>{const stack=new Error().stack;stack&&(globalThis._sentryDebugIds=globalThis._sentryDebugIds||{},globalThis._sentryDebugIds[stack]="6bf0235a-185b-5358-ab58-68c522e5a481",globalThis._sentryDebugIdIdentifier="sentry-dbid-6bf0235a-185b-5358-ab58-68c522e5a481");})();

/*---------------------------------------------------------------------------------------------
 *  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 __clipboardRequire = __fs.existsSync(__clipboardEntrypoint)
    ? __module.createRequire(__clipboardEntrypoint)
    : __rootRequire;
const __foundryRequire = __fs.existsSync(__foundryEntrypoint)
    ? __module.createRequire(__foundryEntrypoint)
    : __rootRequire;
const __pvRecorderRequire = __fs.existsSync(__pvRecorderEntrypoint)
    ? __module.createRequire(__pvRecorderEntrypoint)
    : __rootRequire;
const __isVendoredNativeModule = (module) =>
    typeof module === "string" &&
    (module.startsWith("@teddyzhu/") || module === "foundry-local-sdk" || module === "@picovoice/pvrecorder-node");
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 (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 ms=Object.create;var Vr=Object.defineProperty;var ys=Object.getOwnPropertyDescriptor;var vs=Object.getOwnPropertyNames;var Es=Object.getPrototypeOf,bs=Object.prototype.hasOwnProperty;var ce=(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 D=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Ss=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vs(e))!bs.call(t,i)&&i!==n&&Vr(t,i,{get:()=>e[i],enumerable:!(r=ys(e,i))||r.enumerable});return t};var rt=(t,e,n)=>(n=t!=null?ms(Es(t)):{},Ss(e||!t||!t.__esModule?Vr(n,"default",{value:t,enumerable:!0}):n,t));var Ur=D((wd,qr)=>{"use strict";var jr=()=>process.platform==="linux",it=null,ws=()=>{if(!it)if(jr()&&process.report){let t=process.report.excludeNetwork;process.report.excludeNetwork=!0,it=process.report.getReport(),process.report.excludeNetwork=t}else it={};return it};qr.exports={isLinux:jr,getReport:ws}});var Wr=D((Id,Hr)=>{"use strict";var Oe=ce("fs"),Is="/usr/bin/ldd",Rs="/proc/self/exe",ot=2048,_s=t=>{let e=Oe.openSync(t,"r"),n=Buffer.alloc(ot),r=Oe.readSync(e,n,0,ot,0);return Oe.close(e,()=>{}),n.subarray(0,r)},ks=t=>new Promise((e,n)=>{Oe.open(t,"r",(r,i)=>{if(r)n(r);else{let o=Buffer.alloc(ot);Oe.read(i,o,0,ot,0,(a,l)=>{e(o.subarray(0,l)),Oe.close(i,()=>{})})}})});Hr.exports={LDD_PATH:Is,SELF_PATH:Rs,readFileSync:_s,readFile:ks}});var Gr=D((Rd,Br)=>{"use strict";var Ps=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};Br.exports={interpreterPath:Ps}});var ui=D((_d,li)=>{"use strict";var Jr=ce("child_process"),{isLinux:Me,getReport:Kr}=Ur(),{LDD_PATH:st,SELF_PATH:Yr,readFile:Zt,readFileSync:en}=Wr(),{interpreterPath:Qr}=Gr(),oe,se,ae,Xr="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",ge="",Zr=()=>ge||new Promise(t=>{Jr.exec(Xr,(e,n)=>{ge=e?" ":n,t(ge)})}),ei=()=>{if(!ge)try{ge=Jr.execSync(Xr,{encoding:"utf8"})}catch{ge=" "}return ge},de="glibc",ti=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,we="musl",Ts=t=>t.includes("libc.musl-")||t.includes("ld-musl-"),ni=()=>{let t=Kr();return t.header&&t.header.glibcVersionRuntime?de:Array.isArray(t.sharedObjects)&&t.sharedObjects.some(Ts)?we:null},ri=t=>{let[e,n]=t.split(/[\r\n]+/);return e&&e.includes(de)?de:n&&n.includes(we)?we:null},ii=t=>{if(t){if(t.includes("/ld-musl-"))return we;if(t.includes("/ld-linux-"))return de}return null},oi=t=>(t=t.toString(),t.includes("musl")?we:t.includes("GNU C Library")?de:null),Cs=async()=>{if(se!==void 0)return se;se=null;try{let t=await Zt(st);se=oi(t)}catch{}return se},Os=()=>{if(se!==void 0)return se;se=null;try{let t=en(st);se=oi(t)}catch{}return se},Ms=async()=>{if(oe!==void 0)return oe;oe=null;try{let t=await Zt(Yr),e=Qr(t);oe=ii(e)}catch{}return oe},xs=()=>{if(oe!==void 0)return oe;oe=null;try{let t=en(Yr),e=Qr(t);oe=ii(e)}catch{}return oe},si=async()=>{let t=null;if(Me()&&(t=await Ms(),!t&&(t=await Cs(),t||(t=ni()),!t))){let e=await Zr();t=ri(e)}return t},ai=()=>{let t=null;if(Me()&&(t=xs(),!t&&(t=Os(),t||(t=ni()),!t))){let e=ei();t=ri(e)}return t},Ls=async()=>Me()&&await si()!==de,Ns=()=>Me()&&ai()!==de,As=async()=>{if(ae!==void 0)return ae;ae=null;try{let e=(await Zt(st)).match(ti);e&&(ae=e[1])}catch{}return ae},Fs=()=>{if(ae!==void 0)return ae;ae=null;try{let e=en(st).match(ti);e&&(ae=e[1])}catch{}return ae},ci=()=>{let t=Kr();return t.header&&t.header.glibcVersionRuntime?t.header.glibcVersionRuntime:null},zr=t=>t.trim().split(/\s+/)[1],di=t=>{let[e,n,r]=t.split(/[\r\n]+/);return e&&e.includes(de)?zr(e):n&&r&&n.includes(we)?zr(r):null},Ds=async()=>{let t=null;if(Me()&&(t=await As(),t||(t=ci()),!t)){let e=await Zr();t=di(e)}return t},$s=()=>{let t=null;if(Me()&&(t=Fs(),t||(t=ci()),!t)){let e=ei();t=di(e)}return t};li.exports={GLIBC:de,MUSL:we,family:si,familySync:ai,isNonGlibcLinux:Ls,isNonGlibcLinuxSync:Ns,version:Ds,versionSync:$s}});var xe=D(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.stringArray=U.array=U.func=U.error=U.number=U.string=U.boolean=void 0;function la(t){return t===!0||t===!1}U.boolean=la;function Ti(t){return typeof t=="string"||t instanceof String}U.string=Ti;function ua(t){return typeof t=="number"||t instanceof Number}U.number=ua;function pa(t){return t instanceof Error}U.error=pa;function fa(t){return typeof t=="function"}U.func=fa;function Ci(t){return Array.isArray(t)}U.array=Ci;function ga(t){return Ci(t)&&t.every(e=>Ti(e))}U.stringArray=ga});var On=D(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.Message=m.NotificationType9=m.NotificationType8=m.NotificationType7=m.NotificationType6=m.NotificationType5=m.NotificationType4=m.NotificationType3=m.NotificationType2=m.NotificationType1=m.NotificationType0=m.NotificationType=m.RequestType9=m.RequestType8=m.RequestType7=m.RequestType6=m.RequestType5=m.RequestType4=m.RequestType3=m.RequestType2=m.RequestType1=m.RequestType=m.RequestType0=m.AbstractMessageSignature=m.ParameterStructures=m.ResponseError=m.ErrorCodes=void 0;var Re=xe(),sn;(function(t){t.ParseError=-32700,t.InvalidRequest=-32600,t.MethodNotFound=-32601,t.InvalidParams=-32602,t.InternalError=-32603,t.jsonrpcReservedErrorRangeStart=-32099,t.serverErrorStart=-32099,t.MessageWriteError=-32099,t.MessageReadError=-32098,t.PendingResponseRejected=-32097,t.ConnectionInactive=-32096,t.ServerNotInitialized=-32002,t.UnknownErrorCode=-32001,t.jsonrpcReservedErrorRangeEnd=-32e3,t.serverErrorEnd=-32e3})(sn||(m.ErrorCodes=sn={}));var an=class t extends Error{constructor(e,n,r){super(n),this.code=Re.number(e)?e:sn.UnknownErrorCode,this.data=r,Object.setPrototypeOf(this,t.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};m.ResponseError=an;var K=class t{constructor(e){this.kind=e}static is(e){return e===t.auto||e===t.byName||e===t.byPosition}toString(){return this.kind}};m.ParameterStructures=K;K.auto=new K("auto");K.byPosition=new K("byPosition");K.byName=new K("byName");var x=class{constructor(e,n){this.method=e,this.numberOfParams=n}get parameterStructures(){return K.auto}};m.AbstractMessageSignature=x;var cn=class extends x{constructor(e){super(e,0)}};m.RequestType0=cn;var dn=class extends x{constructor(e,n=K.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};m.RequestType=dn;var ln=class extends x{constructor(e,n=K.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};m.RequestType1=ln;var un=class extends x{constructor(e){super(e,2)}};m.RequestType2=un;var pn=class extends x{constructor(e){super(e,3)}};m.RequestType3=pn;var fn=class extends x{constructor(e){super(e,4)}};m.RequestType4=fn;var gn=class extends x{constructor(e){super(e,5)}};m.RequestType5=gn;var hn=class extends x{constructor(e){super(e,6)}};m.RequestType6=hn;var mn=class extends x{constructor(e){super(e,7)}};m.RequestType7=mn;var yn=class extends x{constructor(e){super(e,8)}};m.RequestType8=yn;var vn=class extends x{constructor(e){super(e,9)}};m.RequestType9=vn;var En=class extends x{constructor(e,n=K.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};m.NotificationType=En;var bn=class extends x{constructor(e){super(e,0)}};m.NotificationType0=bn;var Sn=class extends x{constructor(e,n=K.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};m.NotificationType1=Sn;var wn=class extends x{constructor(e){super(e,2)}};m.NotificationType2=wn;var In=class extends x{constructor(e){super(e,3)}};m.NotificationType3=In;var Rn=class extends x{constructor(e){super(e,4)}};m.NotificationType4=Rn;var _n=class extends x{constructor(e){super(e,5)}};m.NotificationType5=_n;var kn=class extends x{constructor(e){super(e,6)}};m.NotificationType6=kn;var Pn=class extends x{constructor(e){super(e,7)}};m.NotificationType7=Pn;var Tn=class extends x{constructor(e){super(e,8)}};m.NotificationType8=Tn;var Cn=class extends x{constructor(e){super(e,9)}};m.NotificationType9=Cn;var Oi;(function(t){function e(i){let o=i;return o&&Re.string(o.method)&&(Re.string(o.id)||Re.number(o.id))}t.isRequest=e;function n(i){let o=i;return o&&Re.string(o.method)&&i.id===void 0}t.isNotification=n;function r(i){let o=i;return o&&(o.result!==void 0||!!o.error)&&(Re.string(o.id)||Re.number(o.id)||o.id===null)}t.isResponse=r})(Oi||(m.Message=Oi={}))});var xn=D(me=>{"use strict";var Mi;Object.defineProperty(me,"__esModule",{value:!0});me.LRUCache=me.LinkedMap=me.Touch=void 0;var H;(function(t){t.None=0,t.First=1,t.AsOld=t.First,t.Last=2,t.AsNew=t.Last})(H||(me.Touch=H={}));var gt=class{constructor(){this[Mi]="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=H.None){let r=this._map.get(e);if(r)return n!==H.None&&this.touch(r,n),r.value}set(e,n,r=H.None){let i=this._map.get(e);if(i)i.value=n,r!==H.None&&this.touch(i,r);else{switch(i={key:e,value:n,next:void 0,previous:void 0},r){case H.None:this.addItemLast(i);break;case H.First:this.addItemFirst(i);break;case H.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}[(Mi=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!==H.First&&n!==H.Last)){if(n===H.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===H.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=gt;var Mn=class extends gt{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=H.AsNew){return super.get(e,n)}peek(e){return super.get(e,H.None)}set(e,n){return super.set(e,n,H.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};me.LRUCache=Mn});var Li=D(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.Disposable=void 0;var xi;(function(t){function e(n){return{dispose:n}}t.create=e})(xi||(ht.Disposable=xi={}))});var ye=D(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});var Ln;function Nn(){if(Ln===void 0)throw new Error("No runtime abstraction layer installed");return Ln}(function(t){function e(n){if(n===void 0)throw new Error("No runtime abstraction layer provided");Ln=n}t.install=e})(Nn||(Nn={}));An.default=Nn});var Ne=D(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Emitter=Le.Event=void 0;var ha=ye(),Ni;(function(t){let e={dispose(){}};t.None=function(){return e}})(Ni||(Le.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,ha.default)().console.error(l)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},mt=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)}};Le.Emitter=mt;mt._noop=function(){}});var Et=D(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CancellationTokenSource=Ae.CancellationToken=void 0;var ma=ye(),ya=xe(),Dn=Ne(),yt;(function(t){t.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Dn.Event.None}),t.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Dn.Event.None});function e(n){let r=n;return r&&(r===t.None||r===t.Cancelled||ya.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}t.is=e})(yt||(Ae.CancellationToken=yt={}));var va=Object.freeze(function(t,e){let n=(0,ma.default)().timer.setTimeout(t.bind(e),0);return{dispose(){n.dispose()}}}),vt=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?va:(this._emitter||(this._emitter=new Dn.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},$n=class{get token(){return this._token||(this._token=new vt),this._token}cancel(){this._token?this._token.cancel():this._token=yt.Cancelled}dispose(){this._token?this._token instanceof vt&&this._token.dispose():this._token=yt.None}};Ae.CancellationTokenSource=$n});var Ai=D(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.SharedArrayReceiverStrategy=Fe.SharedArraySenderStrategy=void 0;var Ea=Et(),ze;(function(t){t.Continue=0,t.Cancelled=1})(ze||(ze={}));var Vn=class{constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let n=new SharedArrayBuffer(4),r=new Int32Array(n,0,1);r[0]=ze.Continue,this.buffers.set(e.id,n),e.$cancellationData=n}async sendCancellation(e,n){let r=this.buffers.get(n);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,ze.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};Fe.SharedArraySenderStrategy=Vn;var jn=class{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===ze.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}},qn=class{constructor(e){this.token=new jn(e)}cancel(){}dispose(){}},Un=class{constructor(){this.kind="request"}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new Ea.CancellationTokenSource:new qn(n)}};Fe.SharedArrayReceiverStrategy=Un});var Wn=D(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.Semaphore=void 0;var ba=ye(),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,ba.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 Di=D(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.ReadableStreamMessageReader=ve.AbstractMessageReader=ve.MessageReader=void 0;var Gn=ye(),De=xe(),Bn=Ne(),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||(ve.MessageReader=Fi={}));var St=class{constructor(){this.errorEmitter=new Bn.Emitter,this.closeEmitter=new Bn.Emitter,this.partialMessageEmitter=new Bn.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${De.string(e.message)?e.message:"unknown"}`)}};ve.AbstractMessageReader=St;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 y of n.contentDecoders)a.set(y.name,y);if(n.contentTypeDecoder!==void 0&&(l=n.contentTypeDecoder,u.set(l.name,l)),n.contentTypeDecoders!==void 0)for(let y of n.contentTypeDecoders)u.set(y.name,y)}return l===void 0&&(l=(0,Gn.default)().applicationJson.decoder,u.set(l.name,l)),{charset:r,contentDecoder:o,contentDecoders:a,contentTypeDecoder:l,contentTypeDecoders:u}}t.fromOptions=e})(zn||(zn={}));var Jn=class extends St{constructor(e,n){super(),this.readable=e,this.options=zn.fromOptions(n),this.buffer=(0,Gn.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,Gn.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))}};ve.ReadableStreamMessageReader=Jn});var Ui=D(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.WriteableStreamMessageWriter=Ee.AbstractMessageWriter=Ee.MessageWriter=void 0;var $i=ye(),Je=xe(),wa=Wn(),Vi=Ne(),Ia="Content-Length: ",ji=`\r
`,qi;(function(t){function e(n){let r=n;return r&&Je.func(r.dispose)&&Je.func(r.onClose)&&Je.func(r.onError)&&Je.func(r.write)}t.is=e})(qi||(Ee.MessageWriter=qi={}));var wt=class{constructor(){this.errorEmitter=new Vi.Emitter,this.closeEmitter=new Vi.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: ${Je.string(e.message)?e.message:"unknown"}`)}};Ee.AbstractMessageWriter=wt;var Kn;(function(t){function e(n){return n===void 0||typeof n=="string"?{charset:n??"utf-8",contentTypeEncoder:(0,$i.default)().applicationJson.encoder}:{charset:n.charset??"utf-8",contentEncoder:n.contentEncoder,contentTypeEncoder:n.contentTypeEncoder??(0,$i.default)().applicationJson.encoder}}t.fromOptions=e})(Kn||(Kn={}));var Yn=class extends wt{constructor(e,n){super(),this.writable=e,this.options=Kn.fromOptions(n),this.errorCount=0,this.writeSemaphore=new wa.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(Ia,r.byteLength.toString(),ji),i.push(ji),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=Yn});var Hi=D(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.AbstractMessageBuffer=void 0;var Ra=13,_a=10,ka=`\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 y=this._chunks[r];for(i=0;i<y.length;){switch(y[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+=y.byteLength,r++}if(n!==4)return;let a=this._read(o+i),l=new Map,u=this.toString(a,"ascii").split(ka);if(u.length<2)return l;for(let y=0;y<u.length-2;y++){let R=u[y],T=R.indexOf(":");if(T===-1)throw new Error(`Message header must separate key and value using ':'
${R}`);let j=R.substr(0,T),W=R.substr(T+1).trim();l.set(e?j.toLowerCase():j,W)}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}};It.AbstractMessageBuffer=Qn});var Ji=D(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.createMessageConnection=E.ConnectionOptions=E.MessageStrategy=E.CancellationStrategy=E.CancellationSenderStrategy=E.CancellationReceiverStrategy=E.RequestCancellationReceiverStrategy=E.IdCancellationReceiverStrategy=E.ConnectionStrategy=E.ConnectionError=E.ConnectionErrors=E.LogTraceNotification=E.SetTraceNotification=E.TraceFormat=E.TraceValues=E.Trace=E.NullLogger=E.ProgressType=E.ProgressToken=void 0;var Wi=ye(),N=xe(),v=On(),Bi=xn(),Ke=Ne(),Xn=Et(),Xe;(function(t){t.type=new v.NotificationType("$/cancelRequest")})(Xe||(Xe={}));var Zn;(function(t){function e(n){return typeof n=="string"||typeof n=="number"}t.is=e})(Zn||(E.ProgressToken=Zn={}));var Ye;(function(t){t.type=new v.NotificationType("$/progress")})(Ye||(Ye={}));var er=class{constructor(){}};E.ProgressType=er;var tr;(function(t){function e(n){return N.func(n)}t.is=e})(tr||(tr={}));E.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||(E.Trace=I={}));var Gi;(function(t){t.Off="off",t.Messages="messages",t.Compact="compact",t.Verbose="verbose"})(Gi||(E.TraceValues=Gi={}));(function(t){function e(r){if(!N.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||(E.Trace=I={}));var Q;(function(t){t.Text="text",t.JSON="json"})(Q||(E.TraceFormat=Q={}));(function(t){function e(n){return N.string(n)?(n=n.toLowerCase(),n==="json"?t.JSON:t.Text):t.Text}t.fromString=e})(Q||(E.TraceFormat=Q={}));var nr;(function(t){t.type=new v.NotificationType("$/setTrace")})(nr||(E.SetTraceNotification=nr={}));var Rt;(function(t){t.type=new v.NotificationType("$/logTrace")})(Rt||(E.LogTraceNotification=Rt={}));var Qe;(function(t){t[t.Closed=1]="Closed",t[t.Disposed=2]="Disposed",t[t.AlreadyListening=3]="AlreadyListening"})(Qe||(E.ConnectionErrors=Qe={}));var $e=class t extends Error{constructor(e,n){super(n),this.code=e,Object.setPrototypeOf(this,t.prototype)}};E.ConnectionError=$e;var rr;(function(t){function e(n){let r=n;return r&&N.func(r.cancelUndispatched)}t.is=e})(rr||(E.ConnectionStrategy=rr={}));var _t;(function(t){function e(n){let r=n;return r&&(r.kind===void 0||r.kind==="id")&&N.func(r.createCancellationTokenSource)&&(r.dispose===void 0||N.func(r.dispose))}t.is=e})(_t||(E.IdCancellationReceiverStrategy=_t={}));var ir;(function(t){function e(n){let r=n;return r&&r.kind==="request"&&N.func(r.createCancellationTokenSource)&&(r.dispose===void 0||N.func(r.dispose))}t.is=e})(ir||(E.RequestCancellationReceiverStrategy=ir={}));var kt;(function(t){t.Message=Object.freeze({createCancellationTokenSource(n){return new Xn.CancellationTokenSource}});function e(n){return _t.is(n)||ir.is(n)}t.is=e})(kt||(E.CancellationReceiverStrategy=kt={}));var Pt;(function(t){t.Message=Object.freeze({sendCancellation(n,r){return n.sendNotification(Xe.type,{id:r})},cleanup(n){}});function e(n){let r=n;return r&&N.func(r.sendCancellation)&&N.func(r.cleanup)}t.is=e})(Pt||(E.CancellationSenderStrategy=Pt={}));var Tt;(function(t){t.Message=Object.freeze({receiver:kt.Message,sender:Pt.Message});function e(n){let r=n;return r&&kt.is(r.receiver)&&Pt.is(r.sender)}t.is=e})(Tt||(E.CancellationStrategy=Tt={}));var Ct;(function(t){function e(n){let r=n;return r&&N.func(r.handleMessage)}t.is=e})(Ct||(E.MessageStrategy=Ct={}));var zi;(function(t){function e(n){let r=n;return r&&(Tt.is(r.cancellationStrategy)||rr.is(r.connectionStrategy)||Ct.is(r.messageStrategy))}t.is=e})(zi||(E.ConnectionOptions=zi={}));var te;(function(t){t[t.New=1]="New",t[t.Listening=2]="Listening",t[t.Closed=3]="Closed",t[t.Disposed=4]="Disposed"})(te||(te={}));function Pa(t,e,n,r){let i=n!==void 0?n:E.NullLogger,o=0,a=0,l=0,u="2.0",y,R=new Map,T,j=new Map,W=new Map,C,G=new Bi.LinkedMap,z=new Map,He=new Set,Y=new Map,k=I.Off,Se=Q.Text,$,ue=te.New,Yt=new Ke.Emitter,kr=new Ke.Emitter,Pr=new Ke.Emitter,Tr=new Ke.Emitter,Cr=new Ke.Emitter,pe=r&&r.cancellationStrategy?r.cancellationStrategy:Tt.Message;function Or(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 Xo(){return"not-"+(++a).toString()}function Zo(s,d){v.Message.isRequest(d)?s.set(Or(d.id),d):v.Message.isResponse(d)?s.set(Qo(d.id),d):s.set(Xo(),d)}function es(s){}function Mr(){return ue===te.Listening}function xr(){return ue===te.Closed}function Pe(){return ue===te.Disposed}function Lr(){(ue===te.New||ue===te.Listening)&&(ue=te.Closed,kr.fire(void 0))}function ts(s){Yt.fire([s,void 0,void 0])}function ns(s){Yt.fire(s)}t.onClose(Lr),t.onError(ts),e.onClose(Lr),e.onError(ns);function Nr(){C||G.size===0||(C=(0,Wi.default)().timer.setImmediate(()=>{C=void 0,rs()}))}function Ar(s){v.Message.isRequest(s)?os(s):v.Message.isNotification(s)?as(s):v.Message.isResponse(s)?ss(s):cs(s)}function rs(){if(G.size===0)return;let s=G.shift();try{let d=r?.messageStrategy;Ct.is(d)?d.handleMessage(s,Ar):Ar(s)}finally{Nr()}}let is=s=>{try{if(v.Message.isNotification(s)&&s.method===Xe.type.method){let d=s.params.id,p=Or(d),g=G.get(p);if(v.Message.isRequest(g)){let P=r?.connectionStrategy,A=P&&P.cancelUndispatched?P.cancelUndispatched(g,es):void 0;if(A&&(A.error!==void 0||A.result!==void 0)){G.delete(p),Y.delete(d),A.id=g.id,nt(A,s.method,Date.now()),e.write(A).catch(()=>i.error("Sending response for canceled message failed."));return}}let M=Y.get(d);if(M!==void 0){M.cancel(),Qt(s);return}else He.add(d)}Zo(G,s)}finally{Nr()}};function os(s){if(Pe())return;function d(w,L,_){let V={jsonrpc:u,id:s.id};w instanceof v.ResponseError?V.error=w.toJson():V.result=w===void 0?null:w,nt(V,L,_),e.write(V).catch(()=>i.error("Sending response failed."))}function p(w,L,_){let V={jsonrpc:u,id:s.id,error:w.toJson()};nt(V,L,_),e.write(V).catch(()=>i.error("Sending response failed."))}function g(w,L,_){w===void 0&&(w=null);let V={jsonrpc:u,id:s.id,result:w};nt(V,L,_),e.write(V).catch(()=>i.error("Sending response failed."))}us(s);let M=R.get(s.method),P,A;M&&(P=M.type,A=M.handler);let F=Date.now();if(A||y){let w=s.id??String(Date.now()),L=_t.is(pe.receiver)?pe.receiver.createCancellationTokenSource(w):pe.receiver.createCancellationTokenSource(s);s.id!==null&&He.has(s.id)&&L.cancel(),s.id!==null&&Y.set(w,L);try{let _;if(A)if(s.params===void 0){if(P!==void 0&&P.numberOfParams!==0){p(new v.ResponseError(v.ErrorCodes.InvalidParams,`Request ${s.method} defines ${P.numberOfParams} params but received none.`),s.method,F);return}_=A(L.token)}else if(Array.isArray(s.params)){if(P!==void 0&&P.parameterStructures===v.ParameterStructures.byName){p(new v.ResponseError(v.ErrorCodes.InvalidParams,`Request ${s.method} defines parameters by name but received parameters by position`),s.method,F);return}_=A(...s.params,L.token)}else{if(P!==void 0&&P.parameterStructures===v.ParameterStructures.byPosition){p(new v.ResponseError(v.ErrorCodes.InvalidParams,`Request ${s.method} defines parameters by position but received parameters by name`),s.method,F);return}_=A(s.params,L.token)}else y&&(_=y(s.method,s.params,L.token));let V=_;_?V.then?V.then(B=>{Y.delete(w),d(B,s.method,F)},B=>{Y.delete(w),B instanceof v.ResponseError?p(B,s.method,F):B&&N.string(B.message)?p(new v.ResponseError(v.ErrorCodes.InternalError,`Request ${s.method} failed with message: ${B.message}`),s.method,F):p(new v.ResponseError(v.ErrorCodes.InternalError,`Request ${s.method} failed unexpectedly without providing any details.`),s.method,F)}):(Y.delete(w),d(_,s.method,F)):(Y.delete(w),g(_,s.method,F))}catch(_){Y.delete(w),_ instanceof v.ResponseError?d(_,s.method,F):_&&N.string(_.message)?p(new v.ResponseError(v.ErrorCodes.InternalError,`Request ${s.method} failed with message: ${_.message}`),s.method,F):p(new v.ResponseError(v.ErrorCodes.InternalError,`Request ${s.method} failed unexpectedly without providing any details.`),s.method,F)}}else p(new v.ResponseError(v.ErrorCodes.MethodNotFound,`Unhandled method ${s.method}`),s.method,F)}function ss(s){if(!Pe())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=z.get(d);if(ps(s,p),p!==void 0){z.delete(d);try{if(s.error){let g=s.error;p.reject(new v.ResponseError(g.code,g.message,g.data))}else if(s.result!==void 0)p.resolve(s.result);else throw new Error("Should never happen.")}catch(g){g.message?i.error(`Response handler '${p.method}' failed with message: ${g.message}`):i.error(`Response handler '${p.method}' failed unexpectedly.`)}}}}function as(s){if(Pe())return;let d,p;if(s.method===Xe.type.method){let g=s.params.id;He.delete(g),Qt(s);return}else{let g=j.get(s.method);g&&(p=g.handler,d=g.type)}if(p||T)try{if(Qt(s),p)if(s.params===void 0)d!==void 0&&d.numberOfParams!==0&&d.parameterStructures!==v.ParameterStructures.byName&&i.error(`Notification ${s.method} defines ${d.numberOfParams} params but received none.`),p();else if(Array.isArray(s.params)){let g=s.params;s.method===Ye.type.method&&g.length===2&&Zn.is(g[0])?p({token:g[0],value:g[1]}):(d!==void 0&&(d.parameterStructures===v.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 ${g.length} arguments`)),p(...g))}else d!==void 0&&d.parameterStructures===v.ParameterStructures.byPosition&&i.error(`Notification ${s.method} defines parameters by position but received parameters by name`),p(s.params);else T&&T(s.method,s.params)}catch(g){g.message?i.error(`Notification handler '${s.method}' failed with message: ${g.message}`):i.error(`Notification handler '${s.method}' failed unexpectedly.`)}else Pr.fire(s)}function cs(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(N.string(d.id)||N.number(d.id)){let p=d.id,g=z.get(p);g&&g.reject(new Error("The received response has neither a result nor an error property."))}}function fe(s){if(s!=null)switch(k){case I.Verbose:return JSON.stringify(s,null,4);case I.Compact:return JSON.stringify(s);default:return}}function ds(s){if(!(k===I.Off||!$))if(Se===Q.Text){let d;(k===I.Verbose||k===I.Compact)&&s.params&&(d=`Params: ${fe(s.params)}

`),$.log(`Sending request '${s.method} - (${s.id})'.`,d)}else Te("send-request",s)}function ls(s){if(!(k===I.Off||!$))if(Se===Q.Text){let d;(k===I.Verbose||k===I.Compact)&&(s.params?d=`Params: ${fe(s.params)}

`:d=`No parameters provided.

`),$.log(`Sending notification '${s.method}'.`,d)}else Te("send-notification",s)}function nt(s,d,p){if(!(k===I.Off||!$))if(Se===Q.Text){let g;(k===I.Verbose||k===I.Compact)&&(s.error&&s.error.data?g=`Error data: ${fe(s.error.data)}

`:s.result?g=`Result: ${fe(s.result)}

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

`)),$.log(`Sending response '${d} - (${s.id})'. Processing request took ${Date.now()-p}ms`,g)}else Te("send-response",s)}function us(s){if(!(k===I.Off||!$))if(Se===Q.Text){let d;(k===I.Verbose||k===I.Compact)&&s.params&&(d=`Params: ${fe(s.params)}

`),$.log(`Received request '${s.method} - (${s.id})'.`,d)}else Te("receive-request",s)}function Qt(s){if(!(k===I.Off||!$||s.method===Rt.type.method))if(Se===Q.Text){let d;(k===I.Verbose||k===I.Compact)&&(s.params?d=`Params: ${fe(s.params)}

`:d=`No parameters provided.

`),$.log(`Received notification '${s.method}'.`,d)}else Te("receive-notification",s)}function ps(s,d){if(!(k===I.Off||!$))if(Se===Q.Text){let p;if((k===I.Verbose||k===I.Compact)&&(s.error&&s.error.data?p=`Error data: ${fe(s.error.data)}

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

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

`)),d){let g=s.error?` Request failed: ${s.error.message} (${s.error.code}).`:"";$.log(`Received response '${d.method} - (${s.id})' in ${Date.now()-d.timerStart}ms.${g}`,p)}else $.log(`Received response ${s.id} without active response promise.`,p)}else Te("receive-response",s)}function Te(s,d){if(!$||k===I.Off)return;let p={isLSPMessage:!0,type:s,message:d,timestamp:Date.now()};$.log(p)}function We(){if(xr())throw new $e(Qe.Closed,"Connection is closed.");if(Pe())throw new $e(Qe.Disposed,"Connection is disposed.")}function fs(){if(Mr())throw new $e(Qe.AlreadyListening,"Connection is already listening")}function gs(){if(!Mr())throw new Error("Call listen() first.")}function Be(s){return s===void 0?null:s}function Fr(s){if(s!==null)return s}function Dr(s){return s!=null&&!Array.isArray(s)&&typeof s=="object"}function Xt(s,d){switch(s){case v.ParameterStructures.auto:return Dr(d)?Fr(d):[Be(d)];case v.ParameterStructures.byName:if(!Dr(d))throw new Error("Received parameters by name but param is not an object literal.");return Fr(d);case v.ParameterStructures.byPosition:return[Be(d)];default:throw new Error(`Unknown parameter structure ${s.toString()}`)}}function $r(s,d){let p,g=s.numberOfParams;switch(g){case 0:p=void 0;break;case 1:p=Xt(s.parameterStructures,d[0]);break;default:p=[];for(let M=0;M<d.length&&M<g;M++)p.push(Be(d[M]));if(d.length<g)for(let M=d.length;M<g;M++)p.push(null);break}return p}let Ce={sendNotification:(s,...d)=>{We();let p,g;if(N.string(s)){p=s;let P=d[0],A=0,F=v.ParameterStructures.auto;v.ParameterStructures.is(P)&&(A=1,F=P);let w=d.length,L=w-A;switch(L){case 0:g=void 0;break;case 1:g=Xt(F,d[A]);break;default:if(F===v.ParameterStructures.byName)throw new Error(`Received ${L} parameters for 'by Name' notification parameter structure.`);g=d.slice(A,w).map(_=>Be(_));break}}else{let P=d;p=s.method,g=$r(s,P)}let M={jsonrpc:u,method:p,params:g};return ls(M),e.write(M).catch(P=>{throw i.error("Sending notification failed."),P})},onNotification:(s,d)=>{We();let p;return N.func(s)?T=s:d&&(N.string(s)?(p=s,j.set(s,{type:void 0,handler:d})):(p=s.method,j.set(s.method,{type:s,handler:d}))),{dispose:()=>{p!==void 0?j.delete(p):T=void 0}}},onProgress:(s,d,p)=>{if(W.has(d))throw new Error(`Progress handler for token ${d} already registered`);return W.set(d,p),{dispose:()=>{W.delete(d)}}},sendProgress:(s,d,p)=>Ce.sendNotification(Ye.type,{token:d,value:p}),onUnhandledProgress:Tr.event,sendRequest:(s,...d)=>{We(),gs();let p,g,M;if(N.string(s)){p=s;let w=d[0],L=d[d.length-1],_=0,V=v.ParameterStructures.auto;v.ParameterStructures.is(w)&&(_=1,V=w);let B=d.length;Xn.CancellationToken.is(L)&&(B=B-1,M=L);let ie=B-_;switch(ie){case 0:g=void 0;break;case 1:g=Xt(V,d[_]);break;default:if(V===v.ParameterStructures.byName)throw new Error(`Received ${ie} parameters for 'by Name' request parameter structure.`);g=d.slice(_,B).map(hs=>Be(hs));break}}else{let w=d;p=s.method,g=$r(s,w);let L=s.numberOfParams;M=Xn.CancellationToken.is(w[L])?w[L]:void 0}let P=o++,A;M&&(A=M.onCancellationRequested(()=>{let w=pe.sender.sendCancellation(Ce,P);return w===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${P}`),Promise.resolve()):w.catch(()=>{i.log(`Sending cancellation messages for id ${P} failed`)})}));let F={jsonrpc:u,id:P,method:p,params:g};return ds(F),typeof pe.sender.enableCancellation=="function"&&pe.sender.enableCancellation(F),new Promise(async(w,L)=>{let _=ie=>{w(ie),pe.sender.cleanup(P),A?.dispose()},V=ie=>{L(ie),pe.sender.cleanup(P),A?.dispose()},B={method:p,timerStart:Date.now(),resolve:_,reject:V};try{z.set(P,B),await e.write(F)}catch(ie){throw z.delete(P),B.reject(new v.ResponseError(v.ErrorCodes.MessageWriteError,ie.message?ie.message:"Unknown reason")),i.error("Sending request failed."),ie}})},onRequest:(s,d)=>{We();let p=null;return tr.is(s)?(p=void 0,y=s):N.string(s)?(p=null,d!==void 0&&(p=s,R.set(s,{handler:d,type:void 0}))):d!==void 0&&(p=s.method,R.set(s.method,{type:s,handler:d})),{dispose:()=>{p!==null&&(p!==void 0?R.delete(p):y=void 0)}}},hasPendingResponse:()=>z.size>0,trace:async(s,d,p)=>{let g=!1,M=Q.Text;p!==void 0&&(N.boolean(p)?g=p:(g=p.sendNotification||!1,M=p.traceFormat||Q.Text)),k=s,Se=M,k===I.Off?$=void 0:$=d,g&&!xr()&&!Pe()&&await Ce.sendNotification(nr.type,{value:I.toString(s)})},onError:Yt.event,onClose:kr.event,onUnhandledNotification:Pr.event,onDispose:Cr.event,end:()=>{e.end()},dispose:()=>{if(Pe())return;ue=te.Disposed,Cr.fire(void 0);let s=new v.ResponseError(v.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let d of z.values())d.reject(s);z=new Map,Y=new Map,He=new Set,G=new Bi.LinkedMap,N.func(e.dispose)&&e.dispose(),N.func(t.dispose)&&t.dispose()},listen:()=>{We(),fs(),ue=te.Listening,t.listen(is)},inspect:()=>{(0,Wi.default)().console.log("inspect")}};return Ce.onNotification(Rt.type,s=>{if(k===I.Off||!$)return;let d=k===I.Verbose||k===I.Compact;$.log(s.message,d?s.verbose:void 0)}),Ce.onNotification(Ye.type,s=>{let d=W.get(s.token);d?d(s.value):Tr.fire(s)}),Ce}E.createMessageConnection=Pa});var Ot=D(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=On();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 or=xn();Object.defineProperty(c,"LinkedMap",{enumerable:!0,get:function(){return or.LinkedMap}});Object.defineProperty(c,"LRUCache",{enumerable:!0,get:function(){return or.LRUCache}});Object.defineProperty(c,"Touch",{enumerable:!0,get:function(){return or.Touch}});var Ta=Li();Object.defineProperty(c,"Disposable",{enumerable:!0,get:function(){return Ta.Disposable}});var Ki=Ne();Object.defineProperty(c,"Event",{enumerable:!0,get:function(){return Ki.Event}});Object.defineProperty(c,"Emitter",{enumerable:!0,get:function(){return Ki.Emitter}});var Yi=Et();Object.defineProperty(c,"CancellationTokenSource",{enumerable:!0,get:function(){return Yi.CancellationTokenSource}});Object.defineProperty(c,"CancellationToken",{enumerable:!0,get:function(){return Yi.CancellationToken}});var Qi=Ai();Object.defineProperty(c,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return Qi.SharedArraySenderStrategy}});Object.defineProperty(c,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return Qi.SharedArrayReceiverStrategy}});var sr=Di();Object.defineProperty(c,"MessageReader",{enumerable:!0,get:function(){return sr.MessageReader}});Object.defineProperty(c,"AbstractMessageReader",{enumerable:!0,get:function(){return sr.AbstractMessageReader}});Object.defineProperty(c,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return sr.ReadableStreamMessageReader}});var ar=Ui();Object.defineProperty(c,"MessageWriter",{enumerable:!0,get:function(){return ar.MessageWriter}});Object.defineProperty(c,"AbstractMessageWriter",{enumerable:!0,get:function(){return ar.AbstractMessageWriter}});Object.defineProperty(c,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return ar.WriteableStreamMessageWriter}});var Ca=Hi();Object.defineProperty(c,"AbstractMessageBuffer",{enumerable:!0,get:function(){return Ca.AbstractMessageBuffer}});var q=Ji();Object.defineProperty(c,"ConnectionStrategy",{enumerable:!0,get:function(){return q.ConnectionStrategy}});Object.defineProperty(c,"ConnectionOptions",{enumerable:!0,get:function(){return q.ConnectionOptions}});Object.defineProperty(c,"NullLogger",{enumerable:!0,get:function(){return q.NullLogger}});Object.defineProperty(c,"createMessageConnection",{enumerable:!0,get:function(){return q.createMessageConnection}});Object.defineProperty(c,"ProgressToken",{enumerable:!0,get:function(){return q.ProgressToken}});Object.defineProperty(c,"ProgressType",{enumerable:!0,get:function(){return q.ProgressType}});Object.defineProperty(c,"Trace",{enumerable:!0,get:function(){return q.Trace}});Object.defineProperty(c,"TraceValues",{enumerable:!0,get:function(){return q.TraceValues}});Object.defineProperty(c,"TraceFormat",{enumerable:!0,get:function(){return q.TraceFormat}});Object.defineProperty(c,"SetTraceNotification",{enumerable:!0,get:function(){return q.SetTraceNotification}});Object.defineProperty(c,"LogTraceNotification",{enumerable:!0,get:function(){return q.LogTraceNotification}});Object.defineProperty(c,"ConnectionErrors",{enumerable:!0,get:function(){return q.ConnectionErrors}});Object.defineProperty(c,"ConnectionError",{enumerable:!0,get:function(){return q.ConnectionError}});Object.defineProperty(c,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return q.CancellationReceiverStrategy}});Object.defineProperty(c,"CancellationSenderStrategy",{enumerable:!0,get:function(){return q.CancellationSenderStrategy}});Object.defineProperty(c,"CancellationStrategy",{enumerable:!0,get:function(){return q.CancellationStrategy}});Object.defineProperty(c,"MessageStrategy",{enumerable:!0,get:function(){return q.MessageStrategy}});var Oa=ye();c.RAL=Oa.default});var eo=D(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});var Xi=ce("util"),le=Ot(),Mt=class t extends le.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 Xi.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)}};Mt.emptyBuffer=Buffer.allocUnsafe(0);var cr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),le.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),le.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),le.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),le.Disposable.create(()=>this.stream.off("data",e))}},dr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),le.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),le.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),le.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()}},Zi=Object.freeze({messageBuffer:Object.freeze({create:t=>new Mt(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 Xi.TextDecoder(e.charset).decode(t)))}catch(n){return Promise.reject(n)}}})}),stream:Object.freeze({asReadableStream:t=>new cr(t),asWritableStream:t=>new dr(t)}),console,timer:Object.freeze({setTimeout(t,e,...n){let r=setTimeout(t,e,...n);return{dispose:()=>clearTimeout(r)}},setImmediate(t,...e){let n=setImmediate(t,...e);return{dispose:()=>clearImmediate(n)}},setInterval(t,e,...n){let r=setInterval(t,e,...n);return{dispose:()=>clearInterval(r)}}})});function lr(){return Zi}(function(t){function e(){le.RAL.install(Zi)}t.install=e})(lr||(lr={}));ur.default=lr});var ro=D(S=>{"use strict";var Ma=S&&S.__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]})),xa=S&&S.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ma(e,t,n)};Object.defineProperty(S,"__esModule",{value:!0});S.createMessageConnection=S.createServerSocketTransport=S.createClientSocketTransport=S.createServerPipeTransport=S.createClientPipeTransport=S.generateRandomPipeName=S.StreamMessageWriter=S.StreamMessageReader=S.SocketMessageWriter=S.SocketMessageReader=S.PortMessageWriter=S.PortMessageReader=S.IPCMessageWriter=S.IPCMessageReader=void 0;var Ve=eo();Ve.default.install();var to=ce("path"),La=ce("os"),Na=ce("crypto"),Nt=ce("net"),X=Ot();xa(Ot(),S);var pr=class extends X.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),X.Disposable.create(()=>this.process.off("message",e))}};S.IPCMessageReader=pr;var fr=class extends X.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(){}};S.IPCMessageWriter=fr;var gr=class extends X.AbstractMessageReader{constructor(e){super(),this.onData=new X.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)}};S.PortMessageReader=gr;var hr=class extends X.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(){}};S.PortMessageWriter=hr;var _e=class extends X.ReadableStreamMessageReader{constructor(e,n="utf-8"){super((0,Ve.default)().stream.asReadableStream(e),n)}};S.SocketMessageReader=_e;var ke=class extends X.WriteableStreamMessageWriter{constructor(e,n){super((0,Ve.default)().stream.asWritableStream(e),n),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};S.SocketMessageWriter=ke;var xt=class extends X.ReadableStreamMessageReader{constructor(e,n){super((0,Ve.default)().stream.asReadableStream(e),n)}};S.StreamMessageReader=xt;var Lt=class extends X.WriteableStreamMessageWriter{constructor(e,n){super((0,Ve.default)().stream.asWritableStream(e),n)}};S.StreamMessageWriter=Lt;var no=process.env.XDG_RUNTIME_DIR,Aa=new Map([["linux",107],["darwin",103]]);function Fa(){let t=(0,Na.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${t}-sock`;let e;no?e=to.join(no,`vscode-ipc-${t}.sock`):e=to.join(La.tmpdir(),`vscode-${t}.sock`);let n=Aa.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}S.generateRandomPipeName=Fa;function Da(t,e="utf-8"){let n,r=new Promise((i,o)=>{n=i});return new Promise((i,o)=>{let a=(0,Nt.createServer)(l=>{a.close(),n([new _e(l,e),new ke(l,e)])});a.on("error",o),a.listen(t,()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}S.createClientPipeTransport=Da;function $a(t,e="utf-8"){let n=(0,Nt.createConnection)(t);return[new _e(n,e),new ke(n,e)]}S.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,Nt.createServer)(l=>{a.close(),n([new _e(l,e),new ke(l,e)])});a.on("error",o),a.listen(t,"127.0.0.1",()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}S.createClientSocketTransport=Va;function ja(t,e="utf-8"){let n=(0,Nt.createConnection)(t,"127.0.0.1");return[new _e(n,e),new ke(n,e)]}S.createServerSocketTransport=ja;function qa(t){let e=t;return e.read!==void 0&&e.addListener!==void 0}function Ua(t){let e=t;return e.write!==void 0&&e.addListener!==void 0}function Ha(t,e,n,r){n||(n=X.NullLogger);let i=qa(t)?new xt(t):t,o=Ua(e)?new Lt(e):e;return X.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,X.createMessageConnection)(i,o,n,r)}S.createMessageConnection=Ha});var At=D((Ml,io)=>{"use strict";io.exports=ro()});import{join as vd}from"node:path";import*as dt from"os";import tn from"node:path";import{fileURLToPath as Js}from"node:url";import{createRequire as Vs}from"node:module";import{platform as js,type as qs}from"node:os";import{join as fi,resolve as Us}from"node:path";import{fileURLToPath as Hs}from"node:url";var at=rt(ui(),1);function ct(t={}){return(t.platform??process.platform)!=="linux"?"gnu":(t.detectLibcFamily??at.familySync)()===at.MUSL?"musl":"gnu"}function pi(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`${pi(t,e)}-${process.arch}`}function Bs(){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 Z;function hi(){if(Z!==void 0)return Z;switch(qs()){case"Windows_NT":Z="win32";break;case"Darwin":Z="darwin";break;case"Linux":Z="linux";break;case"AIX":Z="aix";break;case"FreeBSD":case"DragonFly":Z="freebsd";break;case"OpenBSD":Z="openbsd";break;case"NetBSD":Z="netbsd";break;case"SunOS":Z="sunos";break;default:Z=js();break}return Z}function mi(t,e){let n=Ws(),r=`${t}.node`,i=`${t}.${Bs()}.node`,o=[];for(let l of e){let u=Us(l),y=fi(u,"prebuilds",n,r),R=gi(y);if(R.ok)return R.value;o.push({path:y,err:R.err});let T=fi(u,i),j=gi(T);if(j.ok)return j.value;o.push({path:T,err:j.err})}let a=o.map(l=>`  ${l.path}: ${Gs(l.err)}`).join(`
`);throw new Error(`Native addon "${t}" not found for ${n}. Tried:
${a}`)}function Gs(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return Object.prototype.toString.call(t)}}function gi(t){try{return{ok:!0,value:zs(t)}}catch(e){return{ok:!1,err:e}}}function zs(t){return Vs(Hs(import.meta.url))(t)}var yi="__copilotRuntimeAddon__";function Ks(){let t=globalThis,e=t[yi];return e||(e={addon:null},t[yi]=e),e}function vi(){let t=Ks();if(t.addon)return t.addon;let e=tn.dirname(Js(import.meta.url)),n=mi("runtime",[e,tn.resolve(e,".."),tn.resolve(e,"..","..","runtime")]);return t.addon=n,n}var Ys;function Ie(){return Ys??=vi()}var Ei="__copilot_git_exec_error__:",Qs=new Set(["gitRemotesAsync","gitSubmodulePathsAsync","gitWorkingTreeStatusAsync","gitCurrentBranchAsync","gitCurrentBranchRemoteAsync","gitDefaultBranchAsync","gitHashFileAsync","gitCommandAsync","gitMutateAsync","gitMergeBaseAsync","gitDiffForRefAsync","gitDiffNameStatusAsync","gitStatusPorcelainAsync","gitStatusPorcelainAllAsync","gitDiffFileAsync","gitUntrackedPathsAsync"]),bi=new Map;function Xs(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ii(t,e){return Reflect.get(t,e)}function Zs(t){return typeof t=="function"}function Si(t){if(!(t instanceof Error)||!t.message.startsWith(Ei))return t;let e;try{e=JSON.parse(t.message.slice(Ei.length))}catch{return t}let n=e.name==="RangeError"?new RangeError(e.message):new Error(e.message),r=n;return e.kind==="spawn"?(he(r,e,"errno"),he(r,e,"code"),he(r,e,"syscall"),he(r,e,"path"),he(r,e,"spawnargs")):(he(r,e,"code"),he(r,e,"killed"),he(r,e,"signal")),r.cmd=e.cmd,r.stdout=wi(e.stdout,e.stdoutUtf16CodeUnits),r.stderr=wi(e.stderr,e.stderrUtf16CodeUnits),n}function wi(t,e){if(!e)return t;let n="",r=8192;for(let i=0;i<e.length;i+=r)n+=String.fromCharCode(...e.slice(i,i+r));return n}function he(t,e,n){Xs(e,n)&&(t[n]=e[n])}function ea(t,e){if(!Qs.has(t)||typeof e!="function")return e;let n=bi.get(t);return n||(n=(...r)=>{try{let i=Ie(),o=Ii(i,t);if(!Zs(o))return o;let a=o(...r);return a&&typeof a.then=="function"?a.catch(l=>{throw Si(l)}):a}catch(i){throw Si(i)}},bi.set(t,n)),n}var J=new Proxy({},{get:(t,e)=>ea(e,Ii(Ie(),e)),has:(t,e)=>Reflect.has(Ie(),e),set:(t,e,n)=>Reflect.set(Ie(),e,n),ownKeys:()=>Reflect.ownKeys(Ie()),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(Ie(),e),defineProperty:(t,e,n)=>Reflect.defineProperty(Ie(),e,n)});function Ri(t,e){return J.resolveCopilotHome(t?.configDir??null,process.env.COPILOT_HOME??null,dt.homedir())}var jd=dt.tmpdir();var nn=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(){await this.writePromise}async dispose(){await this.flush()}outputPath(){return this.logWriter?.outputPath()}logToLevel(e,n){this.logWriter?this.writePromise=this.logWriter.writeLog(e,n):this.initialQueue.push({method:e,message:n})}info(e){this.logToLevel("info",e)}debug(e){this.logToLevel("debug",e)}warning(e){this.logToLevel("warning",e)}error(e){this.logToLevel("error",e instanceof Error?e.message:e)}log(e){this.error(e)}isDebug(){return!1}shouldLog(e){return!0}notice(e){this.info(e instanceof Error?e.message:e)}startGroup(e,n){this.info(`--- Start of group: ${e} ---`)}endGroup(e){this.info("--- End of group ---")}},h=new nn;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";var rn=["GITHUB_COPILOT_GITHUB_TOKEN","GITHUB_TOKEN","COPILOT_GITHUB_TOKEN","GITHUB_COPILOT_API_TOKEN","CAPI_HMAC_KEY","CAPI_HMAC_KEY_OVERRIDE","ANTHROPIC_API_KEY","AIP_SWE_AGENT_TOKEN","CAPI_AZURE_KEY_VAULT_URI","COPILOT_JOB_NONCE","GITHUB_MCP_SERVER_TOKEN","OPENAI_BASE_URL","OPENAI_API_KEY","COPILOT_AGENT_REQUEST_HEADERS","AZURE_OPENAI_API_KEY","AZURE_OPENAI_API_ENDPOINT","AZURE_OPENAI_KEY_VAULT_URI","AZURE_OPENAI_KEY_VAULT_SECRET_NAME","BLACKBIRD_AUTH_METIS_API_KEY","BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","GITHUB_VERIFICATION_TOKEN","COPILOT_PROVIDER_API_KEY","COPILOT_PROVIDER_BEARER_TOKEN"],Wd=["COPILOT_AGENT_CALLBACK_URL","COPILOT_AGENT_MODEL","COPILOT_AGENT_REASONING_EFFORT","COPILOT_AGENT_JOB_ID","COPILOT_AGENT_PROMPT","COPILOT_AGENT_PUSH","COPILOT_FIREWALL_ENABLED","COPILOT_FIREWALL_ALLOW_LIST","GITHUB_COPILOT_INTEGRATION_ID","COPILOT_INTEGRATION_ID_OVERRIDE","COPILOT_AGENT_PREVIOUS_SESSION_IDS","COPILOT_AGENT_EVENT_URL","COPILOT_AGENT_EVENT_TYPE","COPILOT_AGENT_USE_CODEQL","COPILOT_AGENT_USE_CCR","COPILOT_AGENT_USE_SECRET_SCANNING","COPILOT_AGENT_USE_DEPENDENCY_VULN","NODE_ENV","COPILOT_AGENT_ACTOR","COPILOT_AGENT_ACTOR_ID","COPILOT_AGENT_ACTOR_TYPE","COPILOT_API_URL","GITHUB_COPILOT_MCP_JSON_FROM_INPUT","COPILOT_PROVIDER_BASE_URL","COPILOT_PROVIDER_TYPE","COPILOT_PROVIDER_WIRE_API","COPILOT_PROVIDER_AZURE_API_VERSION","COPILOT_PROVIDER_MODEL_ID","COPILOT_PROVIDER_WIRE_MODEL","COPILOT_PROVIDER_MODEL_LIMITS_ID","COPILOT_PROVIDER_MAX_PROMPT_TOKENS","COPILOT_PROVIDER_MAX_OUTPUT_TOKENS","GITHUB_TOKEN_VARNAME","COPILOT_OFFLINE",...rn];var ta=["token","secret","key","hmacKey","modelBasedRetrievalToken","metisApiKey","capiSessionToken","nonce","apiKey","bearerToken","mcpServerToken"];function on(t,e=[]){for(let[n,r]of Object.entries(t))if(r!==null)switch(typeof r){case"object":on(r,e);break;case"undefined":break;default:if(ta.includes(n)){let i=String(r).trim();i!=""&&e.push(i)}break}return e}import*as _i from"process";function Ge(t){let e=_i.env[t];if(e&&e.trim()!=="")return e}var na=["GITHUB_COPILOT_OIDC_","GITHUB_AGENTIC_APP_OIDC_"];var ki=new FinalizationRegistry(t=>{try{J.secretFilterDispose(t)}catch{}}),lt=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;constructor(){this.handle=J.secretFilterCreate(),ki.register(this,this.handle,this.finalizerToken)}setRunner(e){this.runner=e,this.logger=e.logger}applySettings(e){this.settings=e}addSecretEnvVarNames(e){for(let n of e)this.additionalSecretEnvVarNames.add(n)}isAdditionalSecretValue(e){return this.disposed?!1:J.secretFilterIsAdditionalSecretValue(this.handle,e)}getAdditionalSecretValues(){return new Set(this.disposed?[]:J.secretFilterGetAdditionalSecretValues(this.handle))}getRawAdditionalSecretValues(){return new Set(this.disposed?[]:J.secretFilterGetRawAdditionalSecretValues(this.handle))}addSecretValues(e){let n=this.disposed?0:J.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,i=this.disposed?{value:r,changed:!1}:J.secretFilterFilter(this.handle,r,this.getSourceSecretValues());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.disposed?e:J.secretFilterFilterJsonString(this.handle,e,this.getSourceSecretValues())}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,ki.unregister(this.finalizerToken),J.secretFilterDispose(this.handle))}getSourceSecretValues(){let e=[];for(let n of rn){let r=Ge(n);r&&e.push(r)}for(let n of this.additionalSecretEnvVarNames){let r=Ge(n);r&&e.push(r)}for(let n of ra()){let r=Ge(n);r&&e.push(r)}if(this.runner)for(let n of this.runner.sensitiveKeys){let r=Ge(n);r&&e.push(r)}if(this.settings){let n=on(this.settings);for(let r of n)e.push(r)}return[...new Set(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 Pi(...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 ut=class{logLevel;debugEnvironmentVariables;secretFilter=lt.getInstance();constructor(e,n){e===void 0?Pi(...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 Pi(...this.debugEnvironmentVariables??[])}};var pt=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 ft=class extends ut{constructor(n,r,i){super(r,i);this.filePath=n;this.queue=new pt(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 so=rt(At(),1);var oo=["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 Ft=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 oo)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 so.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 Dt=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 Ft({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 Ga(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 Ga(e)}var je=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="VoiceBackendError"}code};function mr(t){return t.code!==void 0?new je(t.message,t.code):new Error(t.message)}function $t(t){return t instanceof Error?t:new Error(String(t))}async function ao(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 yr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};function Ze(t,e,n){let r,i=new Promise((o,a)=>{r=setTimeout(()=>a(new yr(n)),e)});return Promise.race([t,i]).finally(()=>{r&&clearTimeout(r)})}var co="nemotron-3.5-asr-streaming-0.6b",lo=new Set([co,"nemotron-speech-streaming-en-0.6b","nemotron-speech-streaming-es-0.6b"]);function uo(t){return t.find(e=>e.inCatalog&&e.alias===co)}var za="github-copilot-cli",Ja="automatic-speech-recognition",Ka={AzureCatalogFilter:"'',test"},po=1e4,fo=2e3,Vt=class{events;installer;managerFactory;liveSessionFactory;nativeLocation;managerPromise;downloads=new Map;loaded=null;sessions=new Map;outstandingTeardowns=new Set;disposed=!1;constructor(e){this.events=e.events,this.installer=e.installer,this.managerFactory=e.managerFactory,this.liveSessionFactory=e.liveSessionFactory}checkRuntime(e){this.runCheckRuntime(e)}async runCheckRuntime(e){try{if(this.managerFactory){this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"});return}let n=await this.installer.inspect();n.kind==="downloaded"?(this.nativeLocation=n.location,this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"})):n.kind==="update-available"?this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"update-available"}):this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"not-downloaded"})}catch(n){h.error(`[voice-engine] checkRuntime failed: ${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)Ya(a)&&lo.has(a.alias)&&i.push(Xa(a));this.events.submit({type:"internal:catalogFetched",generation:e,models:i})}catch(n){let r=b(n);h.error(`[voice-engine] fetchCatalog failed: ${r}`),this.events.submit({type:"internal:catalogFetchFailed",generation:e,reason:r})}}installRuntime(e){this.runInstallRuntime(e)}async runInstallRuntime(e){try{let n=await this.installer.install();this.nativeLocation=n,this.events.submit({type:"internal:runtimeInstalled",generation:e})}catch(n){let r=b(n);h.error(`[voice-engine] installRuntime failed: ${r}`),this.events.submit({type:"internal:runtimeInstallFailed",generation:e,reason:r})}}downloadModel(e,n){let r=this.downloads.get(e);if(r&&!r.abortController.signal.aborted){r.generations.add(n);return}let i=new Set([n]),o=new AbortController,a={promise:Promise.resolve(),generations:i,abortController:o};a.promise=this.runDownload(e,i,o.signal),this.downloads.set(e,a)}cancelDownload(e){let n=this.downloads.get(e);n&&n.abortController.abort()}async runDownload(e,n,r){try{await(await this.getVariant(e)).download(o=>{for(let a of n)try{this.events.submit({type:"internal:modelDownloadProgress",generation:a,variantId:e,percent:o})}catch(l){h.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);h.error(`[voice-engine] downloadModel '${e}' failed: ${o}`);for(let a of n)this.events.submit({type:"internal:modelDownloadFailed",generation:a,variantId:e,reason:o})}}finally{this.downloads.get(e)?.abortController.signal===r&&this.downloads.delete(e)}}loadModel(e,n){this.runLoad(e,n)}async runLoad(e,n){try{let r=await this.getVariant(e);if(!r.isCached)throw new Error(`Voice model '${e}' is not downloaded.`);await r.load(),this.loaded&&this.loaded.variantId!==e&&h.warning(`[voice-engine] loadModel: replacing loaded model '${this.loaded.variantId}' with '${e}' (reducer should have unloaded first)`),this.loaded={variantId:e,variant:r},this.events.submit({type:"internal:modelLoaded",generation:n,variantId:e})}catch(r){let i=b(r);h.error(`[voice-engine] loadModel '${e}' failed: ${i}`),this.events.submit({type:"internal:modelLoadFailed",generation:n,variantId:e,reason:i})}}unloadModel(e){this.runUnload(e)}async runUnload(e){let n=this.loaded&&this.loaded.variantId===e?this.loaded:null;if(n&&(this.loaded=null),!n){this.events.submit({type:"internal:modelUnloaded",variantId:e});return}try{await n.variant.unload(),this.events.submit({type:"internal:modelUnloaded",variantId:e})}catch(r){let i=b(r);h.error(`[voice-engine] unloadModel '${e}' failed: ${i}`),this.events.submit({type:"internal:modelUnloadFailed",variantId:e,reason:i}),this.events.submit({type:"internal:modelUnloaded",variantId:e})}}deleteModel(e){this.runDelete(e)}async openSttSession(e,n){if(this.disposed)return{ok:!1,subreason:"session-open-failed"};if(this.sessions.has(e))return h.warning(`[voice-engine] openSttSession(${e}): sessionId already in use`),{ok:!1,subreason:"session-open-failed"};let r=this.loaded&&this.loaded.variantId===n?this.loaded:void 0;if(!r)return{ok:!1,subreason:"model-unavailable"};let i={phase:"opening",cancelled:!1};this.sessions.set(e,i);let o=this.runOpenSession(e,r,i);return this.trackTeardown(o.then(()=>{}).catch(()=>{})),o}async runOpenSession(e,n,r){let i;try{i=await this.openStreamingSession(e,n.variant)}catch(a){return h.error(`[voice-engine] openSttSession(${e}) failed: ${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=>h.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){h.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=>h.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){h.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,h.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=>h.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=Qa(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 Ze(e.sdk.stop(),po,"Streaming session stop timed out."),await Ze(e.drainTask,po,"Streaming session drain timed out."),e.committed+e.tail}async teardownSession(e){await this.disposeSdk(e.sdk)}async disposeSdk(e){await Ze(e.dispose(),fo,"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 Ze(e.variant.unload(),fo,"variant.unload timed out").catch(n=>{h.error(`[voice-engine] dispose: variant.unload failed: ${b(n)}`)})}}}async runDelete(e){try{(await this.getVariant(e)).removeFromCache()}catch(n){h.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 ao(async()=>ce("foundry-local-sdk").FoundryLocalManager.createAsync({appName:za,libraryPath:e.corePath,additionalSettings:{...Ka}}))}};function Ya(t){return t.info.task===Ja}function Qa(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,go=-1,ho=150,jt=class{events;pvRecorderLoader;state={tag:"idle"};disposed=!1;constructor(e){this.events=e.events,this.pvRecorderLoader=e.pvRecorderLoader??(async()=>ce("@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 h.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,go,o)})();return this.state={tag:"starting",sessionId:e,deviceId:go,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,ne(()=>i.stop())):r.commitDrain=!0;let a=(async()=>{e==="commit"&&(await Promise.race([o,yo(ho)]).catch(()=>{}),r.stopped=!0,ne(()=>i.stop())),await Promise.race([o,yo(ho)]).catch(()=>{}),ne(()=>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,ne(()=>e.recorder.stop()),await e.loop.catch(()=>{}),ne(()=>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){h.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;ne(()=>u.stop()),ne(()=>u.release())}this.failOpen(r,mo(l));return}if(r.stopped||this.disposed){ne(()=>o.stop()),ne(()=>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"}),ne(()=>e.stop()),ne(()=>e.release());let l=mo(a);h.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 mo(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 yo(t){return new Promise(e=>setTimeout(e,t))}function ne(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 qt(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 Eo(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 Er(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 re(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=uo(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(Eo(t,o)){let u=++e.nextLoadGeneration;e.modelLoad={kind:"loading",variantId:o,generation:u},t.state={kind:"loading",variantId:o},n.push({type:"loadModel",variantId:o,generation:u});return}if((t.state.kind!=="downloading"||t.state.variantId!==o)&&(t.state={kind:"downloading",variantId:o}),!t.inFlightDownloads.some(u=>u.variantId===o)){let u=Er(e,o);t.inFlightDownloads.push({variantId:o}),n.push({type:"downloadModel",variantId:o,generation:u})}}function bo(t){return t.kind==="starting"||t.kind==="runtime-missing"||t.kind==="installing-runtime"||t.kind==="fetching-catalog"||t.kind==="failed"}function So(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 gc(t,e,n,r);case"rpc:refreshCatalog":return hc(t,e,n,r);case"rpc:openSession":return mc(t,e,n,r);case"rpc:finishSession":return yc(t,e,n,r);case"rpc:acknowledgeOperationError":return vc(t,e,n,r);case"internal:catalogFetched":return Ec(t,e,n,r);case"internal:catalogFetchFailed":return bc(t,e,n,r);case"internal:runtimeChecked":return Sc(t,e,n,r);case"internal:runtimeInstalled":return wc(t,e,n,r);case"internal:runtimeInstallFailed":return Ic(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 kc(t,e,n,r);case"internal:modelDownloadFailed":return Pc(t,e,n,r);case"internal:modelLoaded":return Tc(t,e,n,r);case"internal:modelLoadFailed":return Cc(t,e,n,r);case"internal:modelUnloaded":return Oc(t,e,n,r);case"internal:modelUnloadFailed":return Mc(t,e,n,r);case"internal:micError":return Ac(t,e,n,r);case"internal:sessionWarmed":return xc(t,e,n,r);case"internal:sessionWarmupFailed":return Lc(t,e,n,r);case"internal:sttFinal":return Fc(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,qt(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){re(t,e,{kind:"lost",reason:"engine-disabled"},n);for(let r of t.inFlightDownloads)Er(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,qt(t,e);let o=t.enabled;return i&&!o&&(re(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 bo(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,qt(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(bo(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(Eo(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=Er(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(R=>R.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,y=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||y)&&(t.selectedTarget=null,e.clientEnabled=!1,qt(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 gc(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 hc(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 yc(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"?(re(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)):(re(t,e,{kind:"discarded"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"discarded"}}),f(t,e,r))}function vc(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 bc(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 wc(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 Ic(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 kc(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 Pc(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})`}),re(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 Tc(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 Cc(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})`}),re(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 Oc(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 xc(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 Lc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||(Nc(i.ownerConnectionId,n.sessionId,n.failure,r),re(t,e,{kind:"lost",reason:n.failure.side==="mic"?"mic-error":"stt-error"},r)),f(t,e,r)}function Nc(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 Ac(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}),re(t,e,{kind:"lost",reason:"mic-error"},r),f(t,e,r)}function Fc(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 re(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}),re(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&&re(t,e,{kind:"lost",reason:"engine-disabled"},r),f(t,e,r)}function wo(){return{state:{kind:"starting"},enabled:!1,selectedTarget:null,models:[],catalogStatus:"ok",inFlightDownloads:[],session:null,lastOperationError:null}}function Io(){return{generations:{runtimeInstall:0,runtimeCheck:0,downloadByVariant:new Map,catalogFetch:0},nextLoadGeneration:0,modelLoad:{kind:"unloaded"},currentSession:null,clientEnabled:!1,pendingDelete:null}}function Ro(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),y=0;for(let G=l;G<u;G++){let z=o[G*2],Y=(o[G*2+1]<<8|z)<<16>>16,k=Y<0?-Y:Y;k>y&&(y=k)}let R=y/32768,T=Math.min(1,Math.sqrt(R)),j=(u-l)/16e3*1e3,W=T>i?e:n,C=1-Math.exp(-j/Math.max(.001,W));i=i+(T-i)*C}},current(){return i},reset(){i=0}}}function Vc(t){throw new Error(`Unhandled EngineEffect type: ${t.type}`)}var _o=64,Ht=class{snapshot;internal;host;foundry;mic;unsubscribeConnected;unsubscribeDisconnected;disposed=!1;dispatchDepth=0;levelMeter;constructor(e){this.snapshot=wo(),this.internal=Io(),this.host=e.host,this.levelMeter=Ro(),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){h.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){h.error(`[VoiceEngine] onPcmFrame threw: ${b(r)}`)}}}}submit(e){if(!this.disposed){if(this.dispatchDepth>=_o){h.error(`[VoiceEngine] dispatch depth exceeded ${_o} 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}=So(this.snapshot,this.internal,e);this.snapshot=i,this.internal=o;for(let u of a)try{this.dispatch(u)}catch(y){h.error(`[VoiceEngine] dispatching effect '${u.type}' threw: ${b(y)}`)}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"&&h.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){h.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,y])=>{this.disposed||(u.ok&&y.ok?this.submit({type:"internal:sessionWarmed",sessionId:n}):u.ok?y.ok||this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"stt",subreason:y.subreason}}):this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"mic",subreason:u.subreason}}))},u=>{h.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=>{h.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":h.warning(`[VoiceEngine] ${e.message}`);break;default:Vc(e)}}};import{existsSync as br}from"node:fs";import{dirname as ko,join as Sr}from"node:path";import{fileURLToPath as jc}from"node:url";function Po(t){let{importMetaUrl:e,filename:n,label:r}=t,i;try{i=ko(jc(e))}catch(y){throw new Error(`Voice ${r} worker bundle unavailable: cannot resolve module URL (${b(y)}).`)}let o=Sr(i,n);if(br(o))return o;let a=qc(i),l=a?Sr(a,"dist-cli",n):void 0;if(l&&br(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(br(Sr(e,"package.json")))return e;let n=ko(e);if(n===e)return;e=n}}function To(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var wr=16*1024;function Ir(t,e,n=h){let r=Uc(t.level)?t.level:"info",i=typeof t.message=="string"?t.message:To(t.message);n[r](`[${e} worker] ${Hc(i)}`)}function Uc(t){return t==="debug"||t==="info"||t==="warning"||t==="error"}function Hc(t){return t.length<=wr?t:`${t.slice(0,wr)}\u2026 [truncated, ${t.length-wr} more chars]`}import{Worker as Wc}from"node:worker_threads";var Co=(t,e)=>new Wc(t,e);import{createRequire as Gc}from"node:module";import*as be from"node:fs/promises";import*as ee from"node:path";import{createHash as zc}from"node:crypto";import{join as et,basename as Pu}from"node:path";import{homedir as Rr}from"node:os";function Bc(){return process.env.XDG_CACHE_HOME||et(Rr(),".cache")}function Oo(){if(process.platform==="darwin")return et(Rr(),"Library","Caches","copilot");if(process.platform==="win32"){let t=process.env.LOCALAPPDATA||et(Rr(),".cache");return et(t,"copilot")}return et(Bc(),"copilot")}var Jc=1,Kc=".complete";var Lo={"win32-x64":"win-x64","win32-arm64":"win-arm64","linux-x64":"linux-x64","darwin-arm64":"osx-arm64"};function Yc(){return typeof __foundryRequire<"u"&&__foundryRequire||Gc(import.meta.url)}var Wt;function Qc(){if(Wt)return Wt;try{let t=Yc()("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 Wt=t,Wt}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=Qc();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 ee.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=Lo[`${e}-${n}`];if(!r)throw new Error(`Voice mode not supported on ${e}-${n}`);let i=t??process.env.COPILOT_CACHE_HOME??Oo(),o=Xc(e),a=zc("sha256").update(JSON.stringify({schema:Jc,artifacts:o})).digest("hex").slice(0,12);return ee.join(i,"foundry",a,r)}async function Ao(t={}){let e=t.platform??process.platform,n=t.arch??process.arch,r=`${e}-${n}`,i=Lo[r];if(!i)return{kind:"unsupported-platform",platformKey:r};let o=td(t.cacheRoot,e,n),a=ed(e);if(await Mo(o,a))return{kind:"downloaded",location:{corePath:Zc(o,e)}};let l=ee.dirname(ee.dirname(o)),u;try{u=await be.readdir(l)}catch{return{kind:"not-downloaded"}}let y=ee.basename(ee.dirname(o));for(let R of u){if(R===y)continue;let T=ee.join(l,R,i);if(await Mo(T,a))return{kind:"update-available"}}return{kind:"not-downloaded"}}async function Mo(t,e){return await xo(ee.join(t,Kc))?(await Promise.all(e.map(r=>xo(ee.join(t,r))))).every(Boolean):!1}async function xo(t){try{return await be.access(t),!0}catch{return!1}}var Fo=5e3;function Do(t={}){let{cacheRoot:e,workerFactory:n=Co,workerScriptPath:r,inspectImpl:i=Ao}=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??Po({importMetaUrl:import.meta.url,filename:"voice-installer.worker.js",label:"installer"}),onProgress:l}).then(y=>(a={result:{kind:"downloaded",location:y},expiry:Date.now()+Fo},y)).catch(y=>{throw o=void 0,a=void 0,y});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($t(a));return}let i=!1,o=a=>{i||(i=!0,r.terminate().catch(l=>{h.warning(`[voice-runtime] installer worker terminate failed: ${b(l)}`)}),a())};r.on("message",a=>{if(a==null||typeof a!="object"){h.warning("[voice-runtime] installer worker posted a malformed message; ignoring");return}let l=a;if(l.kind==="log"){Ir(l,"Installer");return}if(l.kind==="download-started"){if(!t.onProgress)return;try{t.onProgress({kind:"indeterminate"})}catch(u){h.warning(`[voice-runtime] installer onProgress threw: ${b(u)}`)}return}if(l.kind==="ok"){o(()=>e(l.location));return}if(l.kind==="error"){o(()=>n(mr(l.error)));return}}),r.on("error",a=>{o(()=>n($t(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 $o(t,e){od(t,`${e}
`,{encoding:"utf8"})}function Vo(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 jo(t){try{id(t)}catch{}}var zt=rt(At(),1);import{unlinkSync as sd}from"node:fs";import{createConnection as ad,createServer as cd}from"node:net";var qo=rt(At(),1),Bt=class extends qo.AbstractMessageWriter{socket;errorCount=0;ended=!1;constructor(e){super(),this.socket=e,e.on("close",()=>this.fireClose()),e.on("error",n=>this.fireError(n,void 0,0))}write(e){if(this.ended)return Promise.resolve();try{let n=JSON.stringify(e);if(n===void 0)throw new Error("FastSocketMessageWriter: message serialized to undefined");let r=Buffer.from(n,"utf-8"),i=Buffer.from(`Content-Length: ${r.byteLength}\r
\r
`,"ascii"),o=Buffer.concat([i,r],i.byteLength+r.byteLength);return this.socket.write(o),Promise.resolve()}catch(n){return this.errorCount++,this.fireError(n,e,this.errorCount),Promise.reject(n instanceof Error?n:new Error(String(n)))}}end(){if(!this.ended){this.ended=!0;try{this.socket.end()}catch{}}}dispose(){if(super.dispose(),!this.ended){this.ended=!0;try{this.socket.end()}catch{}}}};var Gt=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,h.info(`voice server: server stopping (clients=${this.host.connectionCount})`);let e=this.server;this.server=null,e&&await new Promise(n=>{e.close(()=>n())})}handleSocket(e){if(this.stopped){e.destroy();return}let n=(0,zt.createMessageConnection)(new zt.SocketMessageReader(e),new Bt(e));try{let r=this.host.registerConnection({connection:n});h.info(`voice server: client connected id=${r.connectionId} (clients=${this.host.connectionCount})`)}catch(r){h.error(`voice server: registerConnection failed: ${r.message}`);try{n.dispose()}catch{}e.destroy()}}};function 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 y=ad(t);y.once("connect",()=>{y.destroy(),n(null)}),y.once("error",R=>{let T=R.code;if(T==="ECONNREFUSED"||T==="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 gd}from"node:crypto";import{mkdirSync as Ho}from"node:fs";import{homedir as Wo,tmpdir as hd}from"node:os";import{join as Ue}from"node:path";import{readFileSync as ld}from"fs";import{dirname as ud,join as _r}from"path";import{fileURLToPath as pd}from"url";var tt=null;function Uo(){return fd().version}function fd(){if(tt!==null)return tt;try{let t=pd(import.meta.url),e=ud(t),n=[_r(e,"package.json"),_r(e,"../package.json"),_r(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 tt=a,a}catch{continue}let r={name:"unknown",version:"unknown"};return tt=r,r}catch{let e={name:"unknown",version:"unknown"};return tt=e,e}}var md=8,Jt="copilot-voice",yd=100;function Bo(t={}){let e=t.platform??process.platform,n=t.env??process.env,r=t.tmpDir??hd(),i=t.cliVersion??Uo();if(e==="win32"){let R=Kt(n.USERPROFILE??n.HOMEPATH??n.USERNAME??t.homeDir??Wo()??"anon"),T=Kt(`${i}|${R}`),j=`\\\\.\\pipe\\${Jt}-${T}`,W=Ue(r,Jt);return Ho(W,{recursive:!0}),{address:j,pidFile:Ue(W,`${T}.pid`),endpointHash:T}}let o=Kt(i),a=n.XDG_RUNTIME_DIR,l=Kt(n.HOME??t.homeDir??Wo()??n.USER??"anon"),u=a?Ue(a,Jt):Ue(r,`${Jt}-${l}`);Ho(u,{recursive:!0,mode:448});let y=Ue(u,`${o}.sock`);return y.length>yd&&h.warning(`voice server: Unix socket path is ${y.length} bytes (macOS limit is 104): ${y}`),{address:y,pidFile:Ue(u,`${o}.pid`),endpointHash:o}}function Kt(t){return gd("sha256").update(t).digest("hex").slice(0,md)}var zo="COPILOT_VOICE_SERVER_BOOT";function Jo(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}if(!Go(e))return{};let n=e.voice;if(!Go(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 Go(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ed=10,Ko=1,Yo=6e4;async function wp(){let t=Bo(),e=bd(t.endpointHash),n=new ft(e);h.setLogWriter(n),h.info(`voice server: boot pid=${process.pid} endpoint=${t.address}`);let r=Do(),i=new Dt,o=new Ht({host:i,foundryFactory:C=>new Vt({events:C,installer:r}),micFactory:C=>new jt({events:C}),bootSettings:Jo(process.env[zo])});i.setSubmit(C=>o.submit(C));let a=!1,l=null,u=()=>{l===null&&(l=setTimeout(()=>{l=null,h.info("voice server: idle timeout, shutting down"),W("idle timeout").catch(()=>{})},Yo))},y=()=>{l!==null&&(clearTimeout(l),l=null)};i.onClientConnected(()=>y()),i.onClientDisconnected(()=>{a||i.connectionCount===0&&u()}),u();let R=new Gt({host:i,address:t.address}),T;try{T=await R.start()}catch(C){h.error(`voice server: bind threw: ${C.stack??String(C)}`),await n.writeQueue,process.exit(Ko)}T==="lost"&&(h.info(`voice server: bind-loser, another voice server owns ${t.address}`),await o.dispose().catch(()=>{}),await n.writeQueue,process.exit(Ed));try{$o(t.pidFile,process.pid)}catch(C){h.error(`voice server: writeServerPidFile failed: ${C.message}`),await R.stop(),await o.dispose().catch(()=>{}),await n.writeQueue,process.exit(Ko)}let j=()=>{Vo(t.pidFile)===process.pid&&jo(t.pidFile)},W=async C=>{if(a)return;a=!0,y(),h.info(`voice server: shutdown (${C})`);let G=R.stop().catch(z=>{h.error(`voice server: server.stop failed: ${z.message}`)});i.dispose(),await G,await o.dispose().catch(z=>{h.error(`voice server: engine.dispose failed: ${z.message}`)}),j(),await n.writeQueue.catch(()=>{}),process.exit(0)};for(let C of["SIGINT","SIGTERM","SIGHUP"])process.on(C,()=>{W(`signal ${C}`).catch(()=>{})});process.on("uncaughtException",C=>{h.error(`voice server: uncaughtException: ${C.stack??String(C)}`),W("uncaughtException").catch(()=>{})}),process.on("unhandledRejection",C=>{h.error(`voice server: unhandledRejection: ${String(C)}`)}),process.on("exit",()=>{j()}),h.info(`voice server: ready (idle timer armed ${Yo}ms)`)}function bd(t){return vd(Ri(void 0,"state"),"logs",`voice-server-${t}.log`)}export{wp as runVoiceServer};//# sourceMappingURL=https://main.vscode-cdn.net/sourcemaps/a22d00300655c17490ce63dffc28bcdcedcd82c4/node_modules/@github/copilot-linux-x64/voice-server.js.map
