(()=>{const stack=new Error().stack;stack&&(globalThis._sentryDebugIds=globalThis._sentryDebugIds||{},globalThis._sentryDebugIds[stack]="71131338-e7bb-549c-92fe-025088b3a249",globalThis._sentryDebugIdIdentifier="sentry-dbid-71131338-e7bb-549c-92fe-025088b3a249");})();

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

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

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

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

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

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

`:d=`No parameters provided.

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

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

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

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

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

`:d=`No parameters provided.

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

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

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

`)),d){let y=s.error?` Request failed: ${s.error.message} (${s.error.code}).`:"";W.log(`Received response '${d.method} - (${s.id})' in ${Date.now()-d.timerStart}ms.${y}`,p)}else W.log(`Received response ${s.id} without active response promise.`,p)}else Ce("receive-response",s)}function Ce(s,d){if(!W||M===T.Off)return;let p={isLSPMessage:!0,type:s,message:d,timestamp:Date.now()};W.log(p)}function Ue(){if(Nr())throw new $e(Ze.Closed,"Connection is closed.");if(Pe())throw new $e(Ze.Disposed,"Connection is disposed.")}function hs(){if(Mr())throw new $e(Ze.AlreadyListening,"Connection is already listening")}function ms(){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 en(s,d){switch(s){case S.ParameterStructures.auto:return Dr(d)?Fr(d):[Be(d)];case S.ParameterStructures.byName:if(!Dr(d))throw new Error("Received parameters by name but param is not an object literal.");return Fr(d);case S.ParameterStructures.byPosition:return[Be(d)];default:throw new Error(`Unknown parameter structure ${s.toString()}`)}}function Vr(s,d){let p,y=s.numberOfParams;switch(y){case 0:p=void 0;break;case 1:p=en(s.parameterStructures,d[0]);break;default:p=[];for(let L=0;L<d.length&&L<y;L++)p.push(Be(d[L]));if(d.length<y)for(let L=d.length;L<y;L++)p.push(null);break}return p}let Te={sendNotification:(s,...d)=>{Ue();let p,y;if(V.string(s)){p=s;let N=d[0],$=0,j=S.ParameterStructures.auto;S.ParameterStructures.is(N)&&($=1,j=N);let C=d.length,D=C-$;switch(D){case 0:y=void 0;break;case 1:y=en(j,d[$]);break;default:if(j===S.ParameterStructures.byName)throw new Error(`Received ${D} parameters for 'by Name' notification parameter structure.`);y=d.slice($,C).map(x=>Be(x));break}}else{let N=d;p=s.method,y=Vr(s,N)}let L={jsonrpc:h,method:p,params:y};return ps(L),e.write(L).catch(N=>{throw i.error("Sending notification failed."),N})},onNotification:(s,d)=>{Ue();let p;return V.func(s)?_=s:d&&(V.string(s)?(p=s,k.set(s,{type:void 0,handler:d})):(p=s.method,k.set(s.method,{type:s,handler:d}))),{dispose:()=>{p!==void 0?k.delete(p):_=void 0}}},onProgress:(s,d,p)=>{if(F.has(d))throw new Error(`Progress handler for token ${d} already registered`);return F.set(d,p),{dispose:()=>{F.delete(d)}}},sendProgress:(s,d,p)=>Te.sendNotification(Xe.type,{token:d,value:p}),onUnhandledProgress:Cr.event,sendRequest:(s,...d)=>{Ue(),ms();let p,y,L;if(V.string(s)){p=s;let C=d[0],D=d[d.length-1],x=0,U=S.ParameterStructures.auto;S.ParameterStructures.is(C)&&(x=1,U=C);let Q=d.length;Xn.CancellationToken.is(D)&&(Q=Q-1,L=D);let oe=Q-x;switch(oe){case 0:y=void 0;break;case 1:y=en(U,d[x]);break;default:if(U===S.ParameterStructures.byName)throw new Error(`Received ${oe} parameters for 'by Name' request parameter structure.`);y=d.slice(x,Q).map(ys=>Be(ys));break}}else{let C=d;p=s.method,y=Vr(s,C);let D=s.numberOfParams;L=Xn.CancellationToken.is(C[D])?C[D]:void 0}let N=o++,$;L&&($=L.onCancellationRequested(()=>{let C=fe.sender.sendCancellation(Te,N);return C===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${N}`),Promise.resolve()):C.catch(()=>{i.log(`Sending cancellation messages for id ${N} failed`)})}));let j={jsonrpc:h,id:N,method:p,params:y};return us(j),typeof fe.sender.enableCancellation=="function"&&fe.sender.enableCancellation(j),new Promise(async(C,D)=>{let x=oe=>{C(oe),fe.sender.cleanup(N),$?.dispose()},U=oe=>{D(oe),fe.sender.cleanup(N),$?.dispose()},Q={method:p,timerStart:Date.now(),resolve:x,reject:U};try{w.set(N,Q),await e.write(j)}catch(oe){throw w.delete(N),Q.reject(new S.ResponseError(S.ErrorCodes.MessageWriteError,oe.message?oe.message:"Unknown reason")),i.error("Sending request failed."),oe}})},onRequest:(s,d)=>{Ue();let p=null;return tr.is(s)?(p=void 0,u=s):V.string(s)?(p=null,d!==void 0&&(p=s,f.set(s,{handler:d,type:void 0}))):d!==void 0&&(p=s.method,f.set(s.method,{type:s,handler:d})),{dispose:()=>{p!==null&&(p!==void 0?f.delete(p):u=void 0)}}},hasPendingResponse:()=>w.size>0,trace:async(s,d,p)=>{let y=!1,L=X.Text;p!==void 0&&(V.boolean(p)?y=p:(y=p.sendNotification||!1,L=p.traceFormat||X.Text)),M=s,be=L,M===T.Off?W=void 0:W=d,y&&!Nr()&&!Pe()&&await Te.sendNotification(nr.type,{value:T.toString(s)})},onError:Xt.event,onClose:Ir.event,onUnhandledNotification:Pr.event,onDispose:Tr.event,end:()=>{e.end()},dispose:()=>{if(Pe())return;pe=re.Disposed,Tr.fire(void 0);let s=new S.ResponseError(S.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let d of w.values())d.reject(s);w=new Map,K=new Map,H=new Set,I=new zi.LinkedMap,V.func(e.dispose)&&e.dispose(),V.func(t.dispose)&&t.dispose()},listen:()=>{Ue(),hs(),pe=re.Listening,t.listen(ss)},inspect:()=>{(0,Ji.default)().console.log("inspect")}};return Te.onNotification(It.type,s=>{if(M===T.Off||!W)return;let d=M===T.Verbose||M===T.Compact;W.log(s.message,d?s.verbose:void 0)}),Te.onNotification(Xe.type,s=>{let d=F.get(s.token);d?d(s.value):Cr.fire(s)}),Te}b.createMessageConnection=Va});var Nt=q(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=xn();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=Nn();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 $a=Ai();Object.defineProperty(c,"Disposable",{enumerable:!0,get:function(){return $a.Disposable}});var Yi=Ae();Object.defineProperty(c,"Event",{enumerable:!0,get:function(){return Yi.Event}});Object.defineProperty(c,"Emitter",{enumerable:!0,get:function(){return Yi.Emitter}});var Xi=wt();Object.defineProperty(c,"CancellationTokenSource",{enumerable:!0,get:function(){return Xi.CancellationTokenSource}});Object.defineProperty(c,"CancellationToken",{enumerable:!0,get:function(){return Xi.CancellationToken}});var Zi=Di();Object.defineProperty(c,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return Zi.SharedArraySenderStrategy}});Object.defineProperty(c,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return Zi.SharedArrayReceiverStrategy}});var sr=$i();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 ja=Bi();Object.defineProperty(c,"AbstractMessageBuffer",{enumerable:!0,get:function(){return ja.AbstractMessageBuffer}});var B=Qi();Object.defineProperty(c,"ConnectionStrategy",{enumerable:!0,get:function(){return B.ConnectionStrategy}});Object.defineProperty(c,"ConnectionOptions",{enumerable:!0,get:function(){return B.ConnectionOptions}});Object.defineProperty(c,"NullLogger",{enumerable:!0,get:function(){return B.NullLogger}});Object.defineProperty(c,"createMessageConnection",{enumerable:!0,get:function(){return B.createMessageConnection}});Object.defineProperty(c,"ProgressToken",{enumerable:!0,get:function(){return B.ProgressToken}});Object.defineProperty(c,"ProgressType",{enumerable:!0,get:function(){return B.ProgressType}});Object.defineProperty(c,"Trace",{enumerable:!0,get:function(){return B.Trace}});Object.defineProperty(c,"TraceValues",{enumerable:!0,get:function(){return B.TraceValues}});Object.defineProperty(c,"TraceFormat",{enumerable:!0,get:function(){return B.TraceFormat}});Object.defineProperty(c,"SetTraceNotification",{enumerable:!0,get:function(){return B.SetTraceNotification}});Object.defineProperty(c,"LogTraceNotification",{enumerable:!0,get:function(){return B.LogTraceNotification}});Object.defineProperty(c,"ConnectionErrors",{enumerable:!0,get:function(){return B.ConnectionErrors}});Object.defineProperty(c,"ConnectionError",{enumerable:!0,get:function(){return B.ConnectionError}});Object.defineProperty(c,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return B.CancellationReceiverStrategy}});Object.defineProperty(c,"CancellationSenderStrategy",{enumerable:!0,get:function(){return B.CancellationSenderStrategy}});Object.defineProperty(c,"CancellationStrategy",{enumerable:!0,get:function(){return B.CancellationStrategy}});Object.defineProperty(c,"MessageStrategy",{enumerable:!0,get:function(){return B.MessageStrategy}});var qa=ve();c.RAL=qa.default});var no=q(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});var eo=de("util"),ue=Nt(),Ot=class t extends ue.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return t.emptyBuffer}fromString(e,n){return Buffer.from(e,n)}toString(e,n){return e instanceof Buffer?e.toString(n):new eo.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)}};Ot.emptyBuffer=Buffer.allocUnsafe(0);var cr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ue.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ue.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ue.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),ue.Disposable.create(()=>this.stream.off("data",e))}},dr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ue.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ue.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ue.Disposable.create(()=>this.stream.off("end",e))}write(e,n){return new Promise((r,i)=>{let o=a=>{a==null?r():i(a)};typeof e=="string"?this.stream.write(e,n,o):this.stream.write(e,o)})}end(){this.stream.end()}},to=Object.freeze({messageBuffer:Object.freeze({create:t=>new Ot(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 eo.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 to}(function(t){function e(){ue.RAL.install(to)}t.install=e})(lr||(lr={}));ur.default=lr});var oo=q(P=>{"use strict";var Ha=P&&P.__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]})),Wa=P&&P.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ha(e,t,n)};Object.defineProperty(P,"__esModule",{value:!0});P.createMessageConnection=P.createServerSocketTransport=P.createClientSocketTransport=P.createServerPipeTransport=P.createClientPipeTransport=P.generateRandomPipeName=P.StreamMessageWriter=P.StreamMessageReader=P.SocketMessageWriter=P.SocketMessageReader=P.PortMessageWriter=P.PortMessageReader=P.IPCMessageWriter=P.IPCMessageReader=void 0;var je=no();je.default.install();var ro=de("path"),Ua=de("os"),Ba=de("crypto"),Ft=de("net"),Z=Nt();Wa(Nt(),P);var pr=class extends Z.AbstractMessageReader{constructor(e){super(),this.process=e;let n=this.process;n.on("error",r=>this.fireError(r)),n.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),Z.Disposable.create(()=>this.process.off("message",e))}};P.IPCMessageReader=pr;var fr=class extends Z.AbstractMessageWriter{constructor(e){super(),this.process=e,this.errorCount=0;let n=this.process;n.on("error",r=>this.fireError(r)),n.on("close",()=>this.fireClose)}write(e){try{return typeof this.process.send=="function"&&this.process.send(e,void 0,void 0,n=>{n?(this.errorCount++,this.handleError(n,e)):this.errorCount=0}),Promise.resolve()}catch(n){return this.handleError(n,e),Promise.reject(n)}}handleError(e,n){this.errorCount++,this.fireError(e,n,this.errorCount)}end(){}};P.IPCMessageWriter=fr;var gr=class extends Z.AbstractMessageReader{constructor(e){super(),this.onData=new Z.Emitter,e.on("close",()=>this.fireClose),e.on("error",n=>this.fireError(n)),e.on("message",n=>{this.onData.fire(n)})}listen(e){return this.onData.event(e)}};P.PortMessageReader=gr;var hr=class extends Z.AbstractMessageWriter{constructor(e){super(),this.port=e,this.errorCount=0,e.on("close",()=>this.fireClose()),e.on("error",n=>this.fireError(n))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(n){return this.handleError(n,e),Promise.reject(n)}}handleError(e,n){this.errorCount++,this.fireError(e,n,this.errorCount)}end(){}};P.PortMessageWriter=hr;var ke=class extends Z.ReadableStreamMessageReader{constructor(e,n="utf-8"){super((0,je.default)().stream.asReadableStream(e),n)}};P.SocketMessageReader=ke;var Ie=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,je.default)().stream.asWritableStream(e),n),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};P.SocketMessageWriter=Ie;var Lt=class extends Z.ReadableStreamMessageReader{constructor(e,n){super((0,je.default)().stream.asReadableStream(e),n)}};P.StreamMessageReader=Lt;var At=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,je.default)().stream.asWritableStream(e),n)}};P.StreamMessageWriter=At;var io=process.env.XDG_RUNTIME_DIR,Ja=new Map([["linux",107],["darwin",103]]);function za(){let t=(0,Ba.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${t}-sock`;let e;io?e=ro.join(io,`vscode-ipc-${t}.sock`):e=ro.join(Ua.tmpdir(),`vscode-${t}.sock`);let n=Ja.get(process.platform);return n!==void 0&&e.length>n&&(0,je.default)().console.warn(`WARNING: IPC handle "${e}" is longer than ${n} characters.`),e}P.generateRandomPipeName=za;function Ga(t,e="utf-8"){let n,r=new Promise((i,o)=>{n=i});return new Promise((i,o)=>{let a=(0,Ft.createServer)(l=>{a.close(),n([new ke(l,e),new Ie(l,e)])});a.on("error",o),a.listen(t,()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}P.createClientPipeTransport=Ga;function Ka(t,e="utf-8"){let n=(0,Ft.createConnection)(t);return[new ke(n,e),new Ie(n,e)]}P.createServerPipeTransport=Ka;function Qa(t,e="utf-8"){let n,r=new Promise((i,o)=>{n=i});return new Promise((i,o)=>{let a=(0,Ft.createServer)(l=>{a.close(),n([new ke(l,e),new Ie(l,e)])});a.on("error",o),a.listen(t,"127.0.0.1",()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}P.createClientSocketTransport=Qa;function Ya(t,e="utf-8"){let n=(0,Ft.createConnection)(t,"127.0.0.1");return[new ke(n,e),new Ie(n,e)]}P.createServerSocketTransport=Ya;function Xa(t){let e=t;return e.read!==void 0&&e.addListener!==void 0}function Za(t){let e=t;return e.write!==void 0&&e.addListener!==void 0}function ec(t,e,n,r){n||(n=Z.NullLogger);let i=Xa(t)?new Lt(t):t,o=Za(e)?new At(e):e;return Z.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,Z.createMessageConnection)(i,o,n,r)}P.createMessageConnection=ec});var Dt=q((jl,so)=>{"use strict";so.exports=oo()});import{join as Ld}from"node:path";import*as gt from"os";import on from"node:path";import{createRequire as Ys}from"node:module";import{fileURLToPath as Xs}from"node:url";var tn=class{initialQueue=[];initialQueueResolvers=Promise.withResolvers();logWriter=null;cachedOutputPath;writePromise=this.initialQueueResolvers.promise;setLogWriter(e){this.logWriter=e,this.cachedOutputPath=void 0;for(let n of this.initialQueue)this.writeTo(e,n.method,n.message);this.initialQueue=[],this.initialQueueResolvers.resolve()}async flush(){if(!this.logWriter)return;let e=this.logWriter,n=(async()=>{try{await this.writePromise,await e.flush?.()}catch{}})(),r,i=new Promise(o=>{r=setTimeout(o,5e3),r.unref?.()});try{await Promise.race([n,i])}finally{r&&clearTimeout(r)}}async dispose(){await this.flush()}outputPath(){return this.cachedOutputPath??=this.logWriter?.outputPath()}logToLevel(e,n){this.logWriter?this.writeTo(this.logWriter,e,n):this.initialQueue.push({method:e,message:n})}writeTo(e,n,r){if(e.write&&e.flush){e.write(n,r),this.writePromise=e.flush().catch(()=>{});return}this.writePromise=e.writeLog(n,r).catch(()=>{})}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 ---")}},m=new tn;import{createRequire as qs}from"node:module";import{platform as Hs,type as Ws}from"node:os";import{join as fi,resolve as Us}from"node:path";import{fileURLToPath as Bs}from"node:url";var ut=at(ui(),1);function pt(t={}){return(t.platform??process.platform)!=="linux"?"gnu":t.detectLibcFamily?t.detectLibcFamily()==="musl"?"musl":"gnu":(0,ut.familySync)()===ut.MUSL?"musl":"gnu"}function pi(t=process.platform,e){let n=e??(t==="linux"?pt():"gnu");return t==="linux"&&n==="musl"?"linuxmusl":t}function Js(){let t=hi(),e=t==="linux"?pt({platform:t}):"gnu";return`${pi(t,e)}-${process.arch}`}function zs(){let t=hi(),{arch:e}=process;switch(t){case"win32":return`win32-${e}-msvc`;case"darwin":return`darwin-${e}`;case"linux":return`linux-${e}-${pt({platform:t})}`;default:throw new Error(`Unsupported platform: ${t}/${e}`)}}var ee;function hi(){if(ee!==void 0)return ee;switch(Ws()){case"Windows_NT":ee="win32";break;case"Darwin":ee="darwin";break;case"Linux":ee="linux";break;case"AIX":ee="aix";break;case"FreeBSD":case"DragonFly":ee="freebsd";break;case"OpenBSD":ee="openbsd";break;case"NetBSD":ee="netbsd";break;case"SunOS":ee="sunos";break;default:ee=Hs();break}return ee}function mi(t,e){let n=Js(),r=`${t}.node`,i=`${t}.${zs()}.node`,o=[];for(let l of e){let h=Us(l),u=fi(h,"prebuilds",n,r),f=gi(u);if(f.ok)return f.value;o.push({path:u,err:f.err});let _=fi(h,i),k=gi(_);if(k.ok)return k.value;o.push({path:_,err:k.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:Ks(t)}}catch(e){return{ok:!1,err:e}}}function Ks(t){return qs(Bs(import.meta.url))(t)}var yi="__copilot_sqlite_error";function vi(t){if(!(t instanceof Error))return t;let e=Qs(t.message);if(!e)return t;let n=new Error(e.message);return n.code="ERR_SQLITE_ERROR",n.errcode=e.errcode,n.errstr=e.errstr,n}function Qs(t){if(!t.startsWith(`${yi}:`))return;let e=t.slice(yi.length+1);try{let n=JSON.parse(e);if(typeof n.message=="string"&&typeof n.errcode=="number"&&typeof n.errstr=="string")return{message:n.message,errcode:n.errcode,errstr:n.errstr}}catch{return}}var ft="COPILOT_RUNTIME_OOP",Zs=new Set(["NativeRunnerLogger"]),Ii=new Set(["log","debug","info","notice","warning","error","startGroup","endGroup","write"]),Je,ea=new Set(["flush","dispose"]),ta=new Set(["writeLog"]),Si=5e3,na="dispose";function ra(t){let e,n=new Promise(r=>{e=setTimeout(()=>{m.debug(`[nativeRuntime] pipeline drain gave up after ${Si}ms; trailing log lines were dropped`),r(void 0)},Si),e.unref?.()});return Promise.race([t,n]).finally(()=>{e&&clearTimeout(e)})}function ia(){return typeof __napiOopRequire<"u"&&__napiOopRequire||Ys(import.meta.url)}function oa(){return process.env[ft]==="1"||process.env[ft]==="true"}function sa(t,e,n){let r=new Set((t.classes??[]).map(o=>o.name)),i={};for(let o of t.classes??[]){let a=o.methods.find(f=>f.js_name==="constructor"),l=a?a.rust_name:`${o.name}.constructor`,h=Zs.has(o.name),u=class{__provider;__handle;constructor(...f){let _=f[f.length-1],k=f.slice(0,f.length-1);this.__provider=_,this.__handle=_.call(l,k),_.trackExternal(this.__handle)}};Object.defineProperty(u,"name",{value:o.name}),u.__fromHandle=function(f,_){let k=Object.create(u.prototype);return k.__provider=f,k.__handle=_,f.trackExternal(_),k};for(let f of o.methods){if(f.js_name==="constructor")continue;let _=r.has(f.ret),k=f.rust_name,F=(E,I)=>_?e[f.ret].__fromHandle(E.__provider,I):I;if(f.is_static){let E=I=>_?e[f.ret].__fromHandle(n,I):I;u[f.js_name]=f.is_async?async(...I)=>E(await n.callAsync(k,I)):(...I)=>E(n.call(k,I));continue}if(f.is_getter){Object.defineProperty(u.prototype,f.js_name,{configurable:!0,get(){return f.is_async?(async()=>F(this,await this.__provider.callAsync(k,[this.__handle])))():F(this,this.__provider.call(k,[this.__handle]))}});continue}if(h&&!f.is_async&&f.ret==="void"&&Ii.has(f.js_name)){u.prototype[f.js_name]=function(...E){let I=this.__provider,w=this.__handle;Je=(Je??Promise.resolve()).then(async()=>{try{await I.callAsync(k,[w,...E])}catch{}})};continue}if(h&&f.is_async&&ta.has(f.js_name)){u.prototype[f.js_name]=function(...E){let I=this.__provider,w=this.__handle,H=(Je??Promise.resolve()).then(()=>I.callAsync(k,[w,...E]));return Je=H.then(()=>{},()=>{}),H.then(()=>{})};continue}if(h&&f.is_async&&ea.has(f.js_name)){let E=f.js_name===na;u.prototype[f.js_name]=async function(...I){let w=H=>E?ra(H):H;return await w(Je??Promise.resolve()),F(this,await w(this.__provider.callAsync(k,[this.__handle,...I])))};continue}u.prototype[f.js_name]=f.is_async?async function(...E){return F(this,await this.__provider.callAsync(k,[this.__handle,...E]))}:function(...E){return F(this,this.__provider.call(k,[this.__handle,...E]))}}i[o.name]=u,e[o.name]=u}return i}function aa(){let{bindClasses:t,connectFromEnvSync:e,createSyncBinding:n,SOCKET_ENV:r}=ia()("napi-oop-runtime");if(!process.env[r])throw new Error(`${ft} is set but ${r} is not; the out-of-process runtime must be launched by the Rust provider parent, which exports the connect-back socket.`);let i=e();if(delete process.env[ft],!i.manifest)throw new Error("out-of-process provider did not advertise a surface manifest in its handshake");let o=JSON.parse(i.manifest),a=new Set((o.classes??[]).map(w=>w.name)),l=o.functions.filter(w=>w.is_async).map(w=>w.js_name),h=o.functions.filter(w=>w.ret==="ExternalObject").map(w=>w.js_name),u={};for(let w of o.functions)u[w.js_name]=w.rust_name;let f=n(i,l,h,u),_={},k=sa(o,_,i),F={};for(let w of o.functions)a.has(w.ret)&&(F[w.js_name]={cls:_[w.ret],isAsync:w.is_async,rustName:w.rust_name});let E=t(f,i,k,F),I=new Map((o.constants??[]).map(w=>[w.js_name,w.value]));return I.size===0?E:new Proxy(E,{get(w,H,K){return typeof H=="string"&&I.has(H)?I.get(H):Reflect.get(w,H,K)},has(w,H){return typeof H=="string"&&I.has(H)?!0:Reflect.has(w,H)}})}var Ei="__copilotRuntimeAddon__";function ca(){let t=globalThis,e=t[Ei];return e||(e={addon:null},t[Ei]=e),e}function da(){let t=ca();if(t.addon)return t.addon;if(oa()){m.debug("[nativeRuntime] out-of-process mode: skipping the in-process runtime .node; all native calls are remoted to the Rust provider");let r=aa();return t.addon=r,r}m.debug("[nativeRuntime] in-process mode: loading the native runtime .node addon into this process");let e=on.dirname(Xs(import.meta.url)),n=mi("runtime",[e,on.resolve(e,".."),on.resolve(e,"..","..","native","runtime")]);return t.addon=n,n}var la;function Ne(){return la??=da()}var wi="\0__copilot_git_structured_error__\0",bi="__copilot_session_fs_error:";function ua(t){if(!(t instanceof Error)||!t.message.startsWith(wi))return t;let e;try{e=JSON.parse(t.message.slice(wi.length))}catch{return t}let n=new Error(typeof e.message=="string"?e.message:"");typeof e.name=="string"&&(n.name=e.name);for(let[r,i]of Object.entries(e))r!=="message"&&r!=="name"&&(n[r]=i);return n}function pa(t){if(!(t instanceof Error)||!t.message.startsWith(bi))return t;let e;try{e=JSON.parse(t.message.slice(bi.length))}catch{return t}let n=typeof e.code=="string"?e.code:"UNKNOWN",r=typeof e.path=="string"?e.path:"sqliteQuery",i=typeof e.message=="string"&&e.message?`: ${e.message}`:"",o=new Error(`${n}: ${r}${i}`);return o.code=n,o.path=r,o}function me(t){let e=vi(t);return e!==t?e:pa(t)}function Ri(t){return t??void 0}function fa(t){class e{inner;constructor(...r){this.inner=new t(...r)}async execute(r,i,o){try{return Ri(await this.inner.execute(r,i,o))}catch(a){throw me(a)}}async batch(r){try{return(await this.inner.batch(r)).map(Ri)}catch(i){throw me(i)}}async transaction(r){try{return await this.inner.transaction(r)}catch(i){throw me(i)}}async getTableNames(){try{return await this.inner.getTableNames()}catch(r){throw me(r)}}async getTableNamesIfExists(){try{return await this.inner.getTableNamesIfExists()}catch(r){throw me(r)}}async getTodoStatus(){try{return await this.inner.getTodoStatus()}catch(r){throw me(r)}}async getCurrentIntent(){try{return await this.inner.getCurrentIntent()}catch(r){throw me(r)}}async closeAll(){try{await this.inner.closeAll()}catch(r){throw me(r)}}}return Object.defineProperty(e,"name",{value:"SessionDatabaseHandle"}),e}function _i(t){return JSON.stringify(t,(e,n)=>typeof n=="number"&&!Number.isFinite(n)?{__copilot_forge_number:String(n)}:n)??"null"}var ga=new Set(["runnerCreateNoopLogger","runnerCreateNoopExec"]);function ha(t){if(typeof t!="object"||t===null||!("__handle"in t)||!("__provider"in t))return t;let e=t,n=Object.create(e);n.__provider=e.__provider,n.__handle=e.__handle;for(let r of Ii)typeof e[r]=="function"&&(n[r]=()=>{});return n}var ki=new WeakMap;function ma(t,e,n){let r=ki.get(t);return r||(r=new Map,ki.set(t,r)),r.has(e)||r.set(e,n()),r.get(e)}function ya(t,e){let n=Reflect.get(t,e);if(typeof n=="function"&&e==="SessionDatabaseHandle")return fa(n);if(typeof n=="function"&&typeof e=="string"&&ga.has(e)){let r=n;return()=>ma(t,e,()=>{let i=r.call(t);return e==="runnerCreateNoopLogger"?ha(i):i})}if(typeof n=="function"&&e==="sessionStoreTrackingPostToolUsePlan"){let r=n;return(i,o,a)=>r.call(t,_i(i),_i(o),a)}if(typeof n=="function"&&typeof e=="string"&&/^git[A-Z]/.test(e)){let r=n;return(...i)=>{let o=r.apply(t,i);return o instanceof Promise?o.catch(a=>{throw ua(a)}):o}}return n}var J=new Proxy({},{get:(t,e)=>ya(Ne(),e),has:(t,e)=>Reflect.has(Ne(),e),set:(t,e,n)=>Reflect.set(Ne(),e,n),ownKeys:()=>Reflect.ownKeys(Ne()),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(Ne(),e),defineProperty:(t,e,n)=>Reflect.defineProperty(Ne(),e,n)});function Pi(t,e){return J.resolveCopilotHome(t?.configDir??null,process.env.COPILOT_HOME??null,gt.homedir())}var sl=gt.tmpdir();function ht(t){let e=[],n=!1,r=()=>{n||(e.push(...t()),n=!0)};return new Proxy(e,{get(i,o,a){r();let l=Reflect.get(i,o,a);return typeof l!="function"?l:(...h)=>Reflect.apply(l,i,h)},set(i,o,a,l){return r(),Reflect.set(i,o,a,l)},has(i,o){return r(),Reflect.has(i,o)},deleteProperty(i,o){return r(),Reflect.deleteProperty(i,o)},defineProperty(i,o,a){return r(),Reflect.defineProperty(i,o,a)},getOwnPropertyDescriptor(i,o){return r(),Reflect.getOwnPropertyDescriptor(i,o)},ownKeys(i){return r(),Reflect.ownKeys(i)}})}var Ci=ht(()=>J.settingsSecretEnvVarNames()),dl=ht(()=>J.settingsEnvVarNamesToFilterFromShellsAndMcp()),ll=ht(()=>J.settingsEnvVarNamesToFilterFromShellsOnly()),ul=ht(()=>J.settingsOtelEnvVarPrefixesToFilterFromShells());function va(t){return JSON.stringify(t,(e,n)=>{switch(typeof n){case"bigint":return n.toString();case"function":case"symbol":return;default:return n}})??"null"}function Ti(t,e=[]){let n=J.settingsGetSecretValues(va(t));if(!n.ok)throw new Error(n.errorMessage??"Failed to get settings secret values");return e.push(...JSON.parse(n.json)),e}function ze(t){return J.environmentNonEmptyValue(process.env[t])??void 0}var Sa=["GITHUB_COPILOT_OIDC_","GITHUB_AGENTIC_APP_OIDC_"];var Ge=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;disposed=!1;runner;logger;settings;additionalSecretEnvVarNames=new Set;sourceSecretsDirty=!0;hasNativeFilterConsumer=!1;constructor(){this.handle=new J.SecretFilterHandle}get nativeHandle(){return this.ensureSourceSecretsSynced(),this.handle}get nativeHandleId(){return this.hasNativeFilterConsumer=!0,this.nativeHandle.id??void 0}setRunner(e){this.runner=e,this.logger=e.logger;let n=this.handle.id??void 0;n!==void 0&&typeof e.setSecretFilter=="function"?(this.hasNativeFilterConsumer=!0,this.markSourceSecretsDirty(),e.setSecretFilter(n)):(this.hasNativeFilterConsumer=!1,this.markSourceSecretsDirty())}applySettings(e){this.settings=e,this.markSourceSecretsDirty()}addSecretEnvVarNames(e){for(let n of e)this.additionalSecretEnvVarNames.add(n);this.markSourceSecretsDirty()}isAdditionalSecretValue(e){return this.disposed?!1:this.handle.isAdditionalSecretValue(e)}getAdditionalSecretValues(){return new Set(this.disposed?[]:this.handle.getAdditionalSecretValues())}getRawAdditionalSecretValues(){return new Set(this.disposed?[]:this.handle.getRawAdditionalSecretValues())}addSecretValues(e){let n=this.disposed?0:this.handle.addSecretValues(e);this.logger?.debug(`[filter]: registered ${n} new filterable value(s) (${e.length} provided, total tracked: ${this.getRawAdditionalSecretValues().size})`)}filterSecrets(e){let n=typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"message"),r=n?e.message??e.toString():e;this.ensureSourceSecretsSynced();let i=this.disposed?{value:r,changed:!1}:this.handle.filter(r,[]);return this.logger&&i.changed&&this.logger.debug(`[filter]: filtered content (original length=${r.length}, filtered length=${i.value.length})`),n?(e.message=i.value,e):i.value}async filterSecretsAsync(e){if(this.ensureSourceSecretsSynced(),this.disposed)return e;let n=this.handle.id;if(n==null)throw new Error("Secret filter handle is unavailable.");let r=await J.secretFilterFilterAsync(n,e,[]);return this.logger&&r.changed&&this.logger.debug(`[filter]: filtered content (original length=${e.length}, filtered length=${r.value.length})`),r.value}filterSecretsFromJsonString(e){return this.ensureSourceSecretsSynced(),this.disposed?e:this.handle.filterJsonString(e,[])}filterSecretsFromJsonSerializable(e){if(e==null)return e;let n=JSON.stringify(e);return n===void 0?e:JSON.parse(this.filterSecretsFromJsonString(n))}syncSourceSecretsToNative(){this.ensureSourceSecretsSynced()}getSourceSecretValuesSnapshot(){return[...new Set([...this.getSourceSecretValues(),...this.getRawAdditionalSecretValues()])]}filterSecretsFromObj(e){if(e==null)return e;if(typeof e=="string")return this.filterSecrets(e);if(typeof e=="number"){let n=this.filterSecrets(e.toString()),r=Number(n);return isNaN(r)?n:r}if(Array.isArray(e))return e.map(n=>this.filterSecretsFromObj(n));if(typeof e=="object"){if(e instanceof Date||e instanceof RegExp)return e;let n={};for(let[r,i]of Object.entries(e))n[r]=this.filterSecretsFromObj(i);return n}return e}dispose(){this.disposed||(this.disposed=!0,this.handle.dispose(),t.singleton===this&&(t.singleton=void 0))}invalidateSourceSecrets(){this.markSourceSecretsDirty()}markSourceSecretsDirty(){this.sourceSecretsDirty=!0,this.hasNativeFilterConsumer&&this.ensureSourceSecretsSynced()}ensureSourceSecretsSynced(){this.disposed||!this.sourceSecretsDirty||(this.handle.setSourceSecretValues(this.getSourceSecretValues()),this.sourceSecretsDirty=!1)}getSourceSecretValues(){let e=new Set;for(let n of Ci){let r=ze(n);r&&e.add(r)}for(let n of this.additionalSecretEnvVarNames){let r=ze(n);r&&e.add(r)}for(let n of Ea()){let r=ze(n);r&&e.add(r)}if(this.runner)for(let n of this.runner.sensitiveKeys){let r=ze(n);r&&e.add(r)}if(this.settings){let n=Ti(this.settings);for(let r of n)e.add(r)}return[...e]}};function Ea(){let t=[];for(let e of Object.keys(process.env))Sa.some(n=>e.startsWith(n))&&t.push(e);return t}var co=at(Dt(),1);var ao=["setEnabled","selectModel","selectAudioDevice","listAudioDevices","downloadModel","cancelDownload","deleteModel","installRuntime","refreshCatalog","openSession","finishSession","acknowledgeOperationError"];function nc(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{},type:`rpc:${t}`,connectionId:n,requestId:r}}var Vt=class{connectionId;connection;submit;pending=new Map;closeHandlers=new Set;closeDisposable;disposeDisposable;nextRequestId=1;attached=!1;disposed=!1;constructor(e){this.connection=e.connection,this.connectionId=e.connectionId,this.submit=e.submit;for(let n of ao)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 co.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(nc(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 $t=class{peers=new Map;connectedHandlers=new Set;disconnectedHandlers=new Set;submit=null;nextAutoConnectionId=1;disposed=!1;setSubmit(e){this.submit=e}registerConnection(e){if(this.disposed)throw new Error("EngineRpcHost is disposed.");if(!this.submit)throw new Error("EngineRpcHost.registerConnection called before setSubmit.");let n=e.connectionId??this.generateConnectionId();if(this.peers.has(n))throw new Error(`EngineRpcHost: connection id "${n}" already registered.`);let r=new Vt({connection:e.connection,connectionId:n,submit:this.submit});this.peers.set(n,r),r.onClose(()=>{if(this.peers.get(n)===r){this.peers.delete(n);for(let i of this.disconnectedHandlers)i(n)}});try{r.attach();for(let i of this.connectedHandlers)i(n)}catch(i){this.peers.delete(n);try{r.dispose()}catch{}throw i}return r}get connectionCount(){return this.peers.size}dispose(){if(this.disposed)return;this.disposed=!0;let e=[...this.peers.values()];for(let n of e)try{n.dispose()}catch{}}broadcast(e){if(!this.disposed)for(let n of this.peers.values())n.send(e)}sendTo(e,n){this.disposed||this.peers.get(e)?.send(n)}resolveRpc(e,n,r){this.disposed||this.peers.get(e)?.resolveRpc(n,r)}rejectRpc(e,n,r){this.disposed||this.peers.get(e)?.rejectRpc(n,r)}onClientConnected(e){return this.connectedHandlers.add(e),()=>{this.connectedHandlers.delete(e)}}onClientDisconnected(e){return this.disconnectedHandlers.add(e),()=>{this.disconnectedHandlers.delete(e)}}generateConnectionId(){return`c${this.nextAutoConnectionId++}`}};function rc(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 R(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 rc(e)}var qe=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 qe(t.message,t.code):new Error(t.message)}function jt(t){return t instanceof Error?t:new Error(String(t))}async function lo(t,e){try{return await t()}catch(n){if((e?.platform??process.platform)!=="win32")throw n;let i=R(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 qe(`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 tt(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 uo="nemotron-3.5-asr-streaming-0.6b",po=new Set([uo,"nemotron-speech-streaming-en-0.6b","nemotron-speech-streaming-es-0.6b"]);function fo(t){return t.find(e=>e.inCatalog&&e.alias===uo)}var ic="github-copilot-cli",oc="automatic-speech-recognition",sc={AzureCatalogFilter:"'',test"},go=1e4,ho=2e3,qt=class{events;installer;managerFactory;liveSessionFactory;nativeLocation;managerPromise;downloads=new Map;loaded=null;sessions=new Map;outstandingTeardowns=new Set;disposed=!1;constructor(e){this.events=e.events,this.installer=e.installer,this.managerFactory=e.managerFactory,this.liveSessionFactory=e.liveSessionFactory}checkRuntime(e){this.runCheckRuntime(e)}async runCheckRuntime(e){try{if(this.managerFactory){this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"});return}let n=await this.installer.inspect();n.kind==="downloaded"?(this.nativeLocation=n.location,this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"})):n.kind==="update-available"?this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"update-available"}):this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"not-downloaded"})}catch(n){m.error(`[voice-engine] checkRuntime failed: ${R(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)ac(a)&&po.has(a.alias)&&i.push(dc(a));this.events.submit({type:"internal:catalogFetched",generation:e,models:i})}catch(n){let r=R(n);m.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=R(n);m.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){m.warning(`[voice-engine] download progress callback threw: ${R(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=R(i);m.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&&m.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=R(r);m.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=R(r);m.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 m.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 m.error(`[voice-engine] openSttSession(${e}) failed: ${R(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=>m.warning(`[voice-engine] orphan teardown(${e}) failed: ${R(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){m.error(`[voice-engine] runEnd(${n}) failed: ${R(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=>m.warning(`[voice-engine] teardown(${n}) failed: ${R(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){m.warning(`[voice-engine] runCancel(${e.sessionId}) teardown: ${R(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,m.error(`[voice-engine] session(${e.sessionId}) failed: ${R(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=>m.warning(`[voice-engine] failSession teardown: ${R(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=cc(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 tt(e.sdk.stop(),go,"Streaming session stop timed out."),await tt(e.drainTask,go,"Streaming session drain timed out."),e.committed+e.tail}async teardownSession(e){await this.disposeSdk(e.sdk)}async disposeSdk(e){await tt(e.dispose(),ho,"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 tt(e.variant.unload(),ho,"variant.unload timed out").catch(n=>{m.error(`[voice-engine] dispose: variant.unload failed: ${R(n)}`)})}}}async runDelete(e){try{(await this.getVariant(e)).removeFromCache()}catch(n){m.error(`[voice-engine] deleteModel '${e}' failed: ${R(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 lo(async()=>de("foundry-local-sdk").FoundryLocalManager.createAsync({appName:ic,libraryPath:e.corePath,additionalSettings:{...sc}}))}};function ac(t){return t.info.task===oc}function cc(t){return t.content?.[0]?.text??""}function dc(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 So=1600,Eo=15,nt=-1,mo=150,Ht=class{events;pvRecorderLoader;state={tag:"idle"};disposed=!1;constructor(e){this.events=e.events,this.pvRecorderLoader=e.pvRecorderLoader??(async()=>de("@picovoice/pvrecorder-node"))}openForSession(e,n){if(this.disposed)return Promise.resolve({ok:!1,subreason:"cancelled"});let r=this.state;switch(r.tag){case"idle":return this.beginStart(e,n,void 0);case"stopping":return this.beginStart(e,n,r.teardown);case"starting":case"active":return m.error(`[voice-mic] openForSession(${e}) while ${r.tag} for session ${r.sessionId} \u2014 engine contract violation`),Promise.resolve({ok:!1,subreason:"in-use"});default:return r}}beginStart(e,n,r){let i,o=new Promise(h=>{i=h}),a={stopped:!1,commitDrain:!1,resolveOpen:i},l=(async()=>{r&&await r.catch(()=>{}),await this.runStart(e,n,a)})();return this.state={tag:"starting",sessionId:e,device:n,cancel:a,startTask:l},o}closeSession(e){let n=this.state;switch(n.tag){case"idle":case"stopping":return n.tag==="stopping"?n.teardown:Promise.resolve();case"starting":{n.cancel.stopped=!0,n.cancel.resolveOpen({ok:!1,subreason:"cancelled"});let r=n.startTask.then(()=>{},()=>{});return this.state={tag:"stopping",teardown:r},r.then(()=>{this.state.tag==="stopping"&&this.state.teardown===r&&(this.state={tag:"idle"})},()=>{}),r}case"active":{let r=n.cancel,i=n.recorder,o=n.loop;e==="discard"?(r.stopped=!0,te(()=>i.stop())):r.commitDrain=!0;let a=(async()=>{e==="commit"&&(await Promise.race([o,vo(mo)]).catch(()=>{}),r.stopped=!0,te(()=>i.stop())),await Promise.race([o,vo(mo)]).catch(()=>{}),te(()=>i.release())})();return this.state={tag:"stopping",teardown:a},a.then(()=>{this.state.tag==="stopping"&&this.state.teardown===a&&(this.state={tag:"idle"})},()=>{}),a}default:return n}}async dispose(){if(this.disposed)return;this.disposed=!0;let e=this.state;switch(e.tag){case"idle":return;case"starting":{e.cancel.stopped=!0,e.cancel.resolveOpen({ok:!1,subreason:"cancelled"}),await e.startTask.catch(()=>{}),this.state={tag:"idle"};return}case"active":{e.cancel.stopped=!0,te(()=>e.recorder.stop()),await e.loop.catch(()=>{}),te(()=>e.recorder.release()),this.state={tag:"idle"};return}case"stopping":{await e.teardown.catch(()=>{}),this.state={tag:"idle"};return}default:return e}}async listDevices(){if(this.disposed)return{ok:!1,reason:"unavailable"};if(this.state.tag==="stopping"&&await this.state.teardown.catch(()=>{}),this.disposed||this.state.tag!=="idle")return{ok:!1,reason:"unavailable"};let e;try{e=await this.pvRecorderLoader()}catch(r){return m.warning(`[voice-mic] listDevices: pvrecorder-node load failed: ${R(r)}`),{ok:!1,reason:"unavailable"}}if(this.disposed||this.state.tag!=="idle")return{ok:!1,reason:"unavailable"};let n;try{n=e.PvRecorder.getAvailableDevices()}catch(r){return m.warning(`[voice-mic] getAvailableDevices failed: ${R(r)}`),{ok:!1,reason:"unavailable"}}return n.length===0?{ok:!0,devices:n,defaultDevice:null}:{ok:!0,devices:n,defaultDevice:uc(e)}}async runStart(e,n,r){if(r.stopped||this.disposed){this.exitCancelled(r);return}let i;try{i=await this.pvRecorderLoader()}catch(u){m.error(`[voice-mic] pvrecorder-node load failed: ${R(u)}`),this.failOpen(r,"hardware-error");return}if(r.stopped||this.disposed){this.exitCancelled(r);return}let o=lc(i,n);n!==null&&o.deviceId===nt&&m.warning(`[voice-mic] requested device "${n?.name}" (#${n?.occurrence}) unavailable; using system default`);let l;try{l=new i.PvRecorder(So,o.deviceId,Eo),l.start()}catch(u){if(l!==void 0){let f=l;te(()=>f.stop()),te(()=>f.release())}this.failOpen(r,yo(u));return}if(r.stopped||this.disposed){te(()=>l.stop()),te(()=>l.release()),this.exitCancelled(r);return}let h=this.runReadLoop(l,e,r);this.state={tag:"active",sessionId:e,device:n,cancel:r,recorder:l,loop:h},r.resolveOpen({ok:!0})}failOpen(e,n){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:n})}exitCancelled(e){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:"cancelled"})}async runReadLoop(e,n,r){for(;!r.stopped;){let i;try{i=await e.read()}catch(a){if(r.stopped||r.commitDrain)return;r.stopped=!0,this.state.tag==="active"&&this.state.cancel===r&&(this.state={tag:"idle"}),te(()=>e.stop()),te(()=>e.release());let l=yo(a);m.error(`[voice-mic] read loop failed (${l}): ${R(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 lc(t,e){if(e===null)return{deviceId:nt};let n;try{n=t.PvRecorder.getAvailableDevices()}catch{return{deviceId:nt}}let r=0;for(let i=0;i<n.length;i++)if(n[i]===e.name){if(r===e.occurrence)return{deviceId:i};r++}return{deviceId:nt}}function uc(t){let e;try{return e=new t.PvRecorder(So,nt,Eo),e.getSelectedDevice()}catch(n){return m.warning(`[voice-mic] default-device probe failed: ${R(n)}`),null}finally{if(e!==void 0){let n=e;te(()=>n.release())}}}function yo(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 vo(t){return new Promise(e=>setTimeout(e,t))}function te(t){try{t()}catch{}}function pc(t){return{state:t.state,enabled:t.enabled,selectedTarget:t.selectedTarget,models:t.models.map(e=>({...e})),catalogStatus:t.catalogStatus,inFlightDownloads:t.inFlightDownloads.map(e=>({...e})),session:t.session?{...t.session}:null,lastOperationError:t.lastOperationError?{...t.lastOperationError}:null,selectedDevice:t.selectedDevice?{...t.selectedDevice}:null}}function fc(t){return{generations:{runtimeInstall:t.generations.runtimeInstall,runtimeCheck:t.generations.runtimeCheck,downloadByVariant:new Map(t.generations.downloadByVariant),catalogFetch:t.generations.catalogFetch},nextLoadGeneration:t.nextLoadGeneration,modelLoad:{...t.modelLoad},currentSession:t.currentSession?{...t.currentSession}:null,clientEnabled:t.clientEnabled,pendingDelete:t.pendingDelete?{...t.pendingDelete}:null}}function Wt(t,e){t.enabled=e.clientEnabled}function He(t,e){return t.models.find(n=>n.variantId===e)}function wo(t,e){let n=He(t,e);return!!n&&(n.inCatalog||n.cached)}function bo(t,e){let n=He(t,e);return!!n&&n.cached}function rt(t){return t.currentSession!==null}function gc(t,e){t.session=e.currentSession?{id:e.currentSession.id,status:e.currentSession.status}:null}function vr(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 hc(t,e,n){t.pendingFinishReply&&(n.push({type:"replyResolve",connectionId:t.pendingFinishReply.connectionId,requestId:t.pendingFinishReply.requestId,result:e}),t.pendingFinishReply=void 0)}function ie(t,e,n,r){let i=e.currentSession;i&&(r.push({type:"cancelSession",sessionId:i.id}),hc(i,n,r),e.currentSession=null,t.session=null)}function mc(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 h=fo(t.models);h?.cached&&(t.selectedTarget=h.variantId)}let i=t.selectedTarget,o=t.enabled&&i!==null&&wo(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(bo(t,o)){let h=++e.nextLoadGeneration;e.modelLoad={kind:"loading",variantId:o,generation:h},t.state={kind:"loading",variantId:o},n.push({type:"loadModel",variantId:o,generation:h});return}if((t.state.kind!=="downloading"||t.state.variantId!==o)&&(t.state={kind:"downloading",variantId:o}),!t.inFlightDownloads.some(h=>h.variantId===o)){let h=vr(e,o);t.inFlightDownloads.push({variantId:o}),n.push({type:"downloadModel",variantId:o,generation:h})}}function Ro(t){return t.kind==="starting"||t.kind==="runtime-missing"||t.kind==="installing-runtime"||t.kind==="fetching-catalog"||t.kind==="failed"}function _o(t,e,n){let r=pc(t),i=fc(e),a=yc(r,i,n,[]);return mc(a.snapshot,a.internal,a.effects),gc(a.snapshot,a.internal),a}function yc(t,e,n,r){switch(n.type){case"boot":return vc(t,e,n,r);case"shutdown":return Sc(t,e,r);case"rpc:setEnabled":return Ec(t,e,n,r);case"rpc:selectModel":return wc(t,e,n,r);case"rpc:selectAudioDevice":return bc(t,e,n,r);case"rpc:listAudioDevices":return Rc(t,e,n,r);case"rpc:downloadModel":return _c(t,e,n,r);case"rpc:cancelDownload":return kc(t,e,n,r);case"rpc:deleteModel":return Ic(t,e,n,r);case"rpc:installRuntime":return Pc(t,e,n,r);case"rpc:refreshCatalog":return Cc(t,e,n,r);case"rpc:openSession":return Tc(t,e,n,r);case"rpc:finishSession":return xc(t,e,n,r);case"rpc:acknowledgeOperationError":return Mc(t,e,n,r);case"internal:catalogFetched":return Nc(t,e,n,r);case"internal:catalogFetchFailed":return Oc(t,e,n,r);case"internal:runtimeChecked":return Lc(t,e,n,r);case"internal:runtimeInstalled":return Ac(t,e,n,r);case"internal:runtimeInstallFailed":return Fc(t,e,n,r);case"internal:modelDownloadProgress":return Dc(t,e,n,r);case"internal:modelDownloaded":return Vc(t,e,n,r);case"internal:modelDownloadCancelled":return $c(t,e,n,r);case"internal:modelDownloadFailed":return jc(t,e,n,r);case"internal:modelLoaded":return qc(t,e,n,r);case"internal:modelLoadFailed":return Hc(t,e,n,r);case"internal:modelUnloaded":return Wc(t,e,n,r);case"internal:modelUnloadFailed":return Uc(t,e,n,r);case"internal:micError":return Gc(t,e,n,r);case"internal:sessionWarmed":return Bc(t,e,n,r);case"internal:sessionWarmupFailed":return Jc(t,e,n,r);case"internal:sttFinal":return Kc(t,e,n,r);case"internal:sttError":return Qc(t,e,n,r);case"client:disconnected":return Yc(t,e,n,r)}}function g(t,e,n){return{snapshot:t,internal:e,effects:n}}function vc(t,e,n,r){e.clientEnabled=n.bootEnabled,Wt(t,e),t.selectedTarget=n.bootSelectedModel,t.selectedDevice=n.bootSelectedDevice,t.state={kind:"starting"};let i=++e.generations.runtimeCheck;return r.push({type:"checkRuntime",generation:i}),g(t,e,r)}function Sc(t,e,n){ie(t,e,{kind:"lost",reason:"engine-disabled"},n);for(let r of t.inFlightDownloads)vr(e,r.variantId);return t.inFlightDownloads=[],e.generations.runtimeInstall++,e.generations.runtimeCheck++,e.generations.catalogFetch++,t.state={kind:"failed",reason:"shutdown"},g(t,e,n)}function Ec(t,e,n,r){let i=e.clientEnabled;e.clientEnabled=n.enabled,Wt(t,e);let o=t.enabled;return i&&!o&&(ie(t,e,{kind:"lost",reason:"engine-disabled"},r),(t.state.kind==="downloading"||t.state.kind==="loading"||t.state.kind==="ready")&&(t.state={kind:"no-model"})),!i&&o&&t.state.kind==="model-failed"&&(t.state={kind:"no-model"},t.lastOperationError=null),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function wc(t,e,n,r){return Ro(t.state)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),g(t,e,r)):rt(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):wo(t,n.variantId)?(e.clientEnabled=!0,Wt(t,e),t.state.kind==="model-failed"&&(t.state={kind:"no-model"}),n.variantId===t.selectedTarget&&t.enabled?(r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)):(t.selectedTarget=n.variantId,t.lastOperationError=null,t.state.kind==="downloading"&&t.state.variantId!==n.variantId&&(t.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r))):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-not-found",variantId:n.variantId}}),g(t,e,r))}function bc(t,e,n,r){return rt(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):(t.selectedDevice=n.device?{name:n.device.name,occurrence:n.device.occurrence}:null,r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r))}function Rc(t,e,n,r){return rt(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):(r.push({type:"listAudioDevices",connectionId:n.connectionId,requestId:n.requestId}),g(t,e,r))}function _c(t,e,n,r){if(Ro(t.state))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),g(t,e,r);if(!He(t,n.variantId))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-not-found",variantId:n.variantId}}),g(t,e,r);if(bo(t,n.variantId))return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r);if(!t.inFlightDownloads.some(o=>o.variantId===n.variantId)){let o=vr(e,n.variantId);t.inFlightDownloads.push({variantId:n.variantId}),r.push({type:"downloadModel",variantId:n.variantId,generation:o})}return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function kc(t,e,n,r){return t.inFlightDownloads.some(o=>o.variantId===n.variantId)&&(r.push({type:"cancelDownload",variantId:n.variantId}),e.generations.downloadByVariant.set(n.variantId,(e.generations.downloadByVariant.get(n.variantId)??0)+1),t.inFlightDownloads=t.inFlightDownloads.filter(o=>o.variantId!==n.variantId),t.selectedTarget===n.variantId&&(t.selectedTarget=null,t.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function Ic(t,e,n,r){if(t.inFlightDownloads.some(f=>f.variantId===n.variantId))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-in-use"}}),g(t,e,r);if(n.variantId===t.selectedTarget&&rt(e))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r);let o=e.modelLoad;if((o.kind==="loading"||o.kind==="unloading")&&o.variantId===n.variantId)return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-in-use"}}),g(t,e,r);let a=He(t,n.variantId),l=o.kind==="loaded"&&o.variantId===n.variantId,h=n.variantId===t.selectedTarget,u=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)),(h||u)&&(t.selectedTarget=null,e.clientEnabled=!1,Wt(t,e),(t.state.kind==="downloading"||t.state.kind==="loading"||t.state.kind==="ready"||t.state.kind==="model-failed")&&(t.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function Pc(t,e,n,r){if(t.state.kind!=="runtime-missing")return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"invalid-state"}}),g(t,e,r);let i=++e.generations.runtimeInstall;return t.state={kind:"installing-runtime",cacheState:t.state.cacheState},r.push({type:"installRuntime",generation:i}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function Cc(t,e,n,r){if((t.state.kind==="no-model"||t.state.kind==="downloading"||t.state.kind==="loading"||t.state.kind==="ready"||t.state.kind==="model-failed")&&t.catalogStatus!=="fetching"){let o=++e.generations.catalogFetch;t.catalogStatus="fetching",r.push({type:"fetchCatalog",generation:o})}return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function Tc(t,e,n,r){return t.enabled?rt(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):t.selectedTarget?t.state.kind!=="ready"?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),g(t,e,r)):(e.currentSession={id:n.sessionId,ownerConnectionId:n.connectionId,status:"opening"},r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),r.push({type:"warmupSession",sessionId:n.sessionId,variantId:t.selectedTarget,device:t.selectedDevice}),g(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"invalid-state"}}),g(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"engine-disabled"}}),g(t,e,r))}function xc(t,e,n,r){let i=e.currentSession;if(!(i!==null&&i.id===n.sessionId&&i.ownerConnectionId===n.connectionId)){let a=n.commit?{kind:"lost",reason:"unknown-session"}:{kind:"discarded"};return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:a}),g(t,e,r)}return n.commit?i!==null&&i.status==="opening"?(ie(t,e,{kind:"lost",reason:"not-ready"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"lost",reason:"not-ready"}}),g(t,e,r)):i!==null&&i.pendingFinishReply?(r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"lost",reason:"not-ready"}}),g(t,e,r)):(i!==null&&(i.pendingFinishReply={connectionId:n.connectionId,requestId:n.requestId}),r.push({type:"commitSession",sessionId:n.sessionId}),g(t,e,r)):(ie(t,e,{kind:"discarded"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"discarded"}}),g(t,e,r))}function Mc(t,e,n,r){return t.lastOperationError=null,t.state.kind==="model-failed"&&(t.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function Nc(t,e,n,r){return n.generation!==e.generations.catalogFetch||(t.models=n.models.map(i=>({...i})),t.catalogStatus="ok",(t.state.kind==="starting"||t.state.kind==="fetching-catalog")&&(t.state={kind:"no-model"})),g(t,e,r)}function Oc(t,e,n,r){return n.generation!==e.generations.catalogFetch||(t.catalogStatus="failed",(t.state.kind==="starting"||t.state.kind==="fetching-catalog")&&(t.state={kind:"no-model"})),g(t,e,r)}function Lc(t,e,n,r){if(n.generation!==e.generations.runtimeCheck||t.state.kind!=="starting")return g(t,e,r);if(n.cacheState!=="installed")return t.state={kind:"runtime-missing",cacheState:n.cacheState},g(t,e,r);t.state={kind:"fetching-catalog"},t.catalogStatus="fetching";let i=++e.generations.catalogFetch;return r.push({type:"fetchCatalog",generation:i}),g(t,e,r)}function Ac(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return g(t,e,r);if(t.state.kind==="installing-runtime"){t.state={kind:"fetching-catalog"},t.catalogStatus="fetching";let i=++e.generations.catalogFetch;r.push({type:"fetchCatalog",generation:i})}return g(t,e,r)}function Fc(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return g(t,e,r);t.state.kind==="installing-runtime"&&(t.state={kind:"runtime-missing",cacheState:t.state.cacheState});let i={operation:"installRuntime",reason:n.reason};t.lastOperationError=i;let o={type:"operationError",error:i};return r.push({type:"broadcast",event:o}),g(t,e,r)}function Dc(t,e,n,r){if(n.generation!==Ut(e,n.variantId))return g(t,e,r);let i={type:"modelDownloadProgress",variantId:n.variantId,percent:n.percent};return r.push({type:"broadcast",event:i}),g(t,e,r)}function Vc(t,e,n,r){if(n.generation!==Ut(e,n.variantId))return g(t,e,r);t.inFlightDownloads=t.inFlightDownloads.filter(o=>o.variantId!==n.variantId);let i=He(t,n.variantId);return i?i.cached=!0:t.models.push({variantId:n.variantId,displayName:n.variantId,cached:!0,inCatalog:!1}),g(t,e,r)}function $c(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"})),g(t,e,r)}function jc(t,e,n,r){if(n.generation!==Ut(e,n.variantId))return g(t,e,r);t.inFlightDownloads=t.inFlightDownloads.filter(a=>a.variantId!==n.variantId),t.state.kind==="downloading"&&t.state.variantId===n.variantId&&(t.selectedTarget=null,t.state={kind:"model-failed",variantId:n.variantId,reason:n.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelDownloadFailed (sessionId=${e.currentSession.id}, variantId=${n.variantId})`}),ie(t,e,{kind:"lost",reason:"engine-disabled"},r)));let i={operation:"downloadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=i;let o={type:"operationError",error:i};return r.push({type:"broadcast",event:o}),g(t,e,r)}function qc(t,e,n,r){let i=e.modelLoad;return i.kind!=="loading"||i.generation!==n.generation||i.variantId!==n.variantId?(r.push({type:"unloadModel",variantId:n.variantId}),g(t,e,r)):(e.modelLoad={kind:"loaded",variantId:n.variantId},t.enabled&&t.selectedTarget===n.variantId&&(t.state={kind:"ready",variantId:n.variantId},t.lastOperationError=null),g(t,e,r))}function Hc(t,e,n,r){let i=e.modelLoad;if(i.kind!=="loading"||i.generation!==n.generation||i.variantId!==n.variantId)return g(t,e,r);e.modelLoad={kind:"unloaded"},t.selectedTarget=null,t.state={kind:"model-failed",variantId:n.variantId,reason:n.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelLoadFailed (sessionId=${e.currentSession.id}, variantId=${n.variantId})`}),ie(t,e,{kind:"lost",reason:"engine-disabled"},r));let o={operation:"loadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=o;let a={type:"operationError",error:o};return r.push({type:"broadcast",event:a}),g(t,e,r)}function Wc(t,e,n,r){let i=e.modelLoad;if(i.kind!=="unloading"||i.variantId!==n.variantId)return g(t,e,r);if(e.modelLoad={kind:"unloaded"},e.pendingDelete&&e.pendingDelete.variantId===n.variantId){r.push({type:"deleteModel",variantId:n.variantId});let o=He(t,n.variantId);o&&(o.cached=!1),(t.state.kind==="ready"||t.state.kind==="loading"||t.state.kind==="downloading")&&t.state.variantId===n.variantId&&(t.state={kind:"no-model"}),e.pendingDelete=null}return g(t,e,r)}function Uc(t,e,n,r){let i={operation:"loadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=i;let o={type:"operationError",error:i};return r.push({type:"broadcast",event:o}),g(t,e,r)}function Bc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||i.status==="opening"&&(i.status="active"),g(t,e,r)}function Jc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||(zc(i.ownerConnectionId,n.sessionId,n.failure,r),ie(t,e,{kind:"lost",reason:n.failure.side==="mic"?"mic-error":"stt-error"},r)),g(t,e,r)}function zc(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 Gc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return g(t,e,r);let o={type:"micError",sessionId:n.sessionId,subreason:n.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:o}),ie(t,e,{kind:"lost",reason:"mic-error"},r),g(t,e,r)}function Kc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return g(t,e,r);let o=i.pendingFinishReply?{kind:"committed",text:n.text}:{kind:"discarded"};return ie(t,e,o,r),g(t,e,r)}function Qc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return g(t,e,r);let o={type:"sttError",sessionId:n.sessionId,subreason:n.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:o}),ie(t,e,{kind:"lost",reason:"stt-error"},r),g(t,e,r)}function Yc(t,e,n,r){let i=e.currentSession;return i&&i.ownerConnectionId===n.connectionId&&ie(t,e,{kind:"lost",reason:"engine-disabled"},r),g(t,e,r)}function ko(){return{state:{kind:"starting"},enabled:!1,selectedTarget:null,models:[],catalogStatus:"ok",inFlightDownloads:[],session:null,lastOperationError:null,selectedDevice: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 Po(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 h=Math.min(a,l+r),u=0;for(let I=l;I<h;I++){let w=o[I*2],K=(o[I*2+1]<<8|w)<<16>>16,M=K<0?-K:K;M>u&&(u=M)}let f=u/32768,_=Math.min(1,Math.sqrt(f)),k=(h-l)/16e3*1e3,F=_>i?e:n,E=1-Math.exp(-k/Math.max(.001,F));i=i+(_-i)*E}},current(){return i},reset(){i=0}}}function Xc(t){throw new Error(`Unhandled EngineEffect type: ${t.type}`)}var Co=64,Bt=class{snapshot;internal;host;foundry;mic;unsubscribeConnected;unsubscribeDisconnected;disposed=!1;dispatchDepth=0;levelMeter;constructor(e){this.snapshot=ko(),this.internal=Io(),this.host=e.host,this.levelMeter=Po(),this.foundry=e.foundryFactory(this.buildFoundryEvents()),this.mic=e.micFactory(this.buildMicEvents()),this.submit({type:"boot",bootEnabled:e.bootSettings.voice?.enabled===!0,bootSelectedModel:e.bootSettings.voice?.selectedModel??null,bootSelectedDevice:e.bootSettings.voice?.selectedDevice??null}),this.unsubscribeConnected=e.host.onClientConnected(n=>{e.host.sendTo(n,{type:"initialize",snapshot:this.snapshot})}),this.unsubscribeDisconnected=e.host.onClientDisconnected(n=>{this.submit({type:"client:disconnected",connectionId:n})})}buildFoundryEvents(){return{submit:e=>{this.submit(e)},onSttPartial:(e,n)=>{if(!this.disposed)try{let r=this.internal.currentSession;if(!r||r.id!==e||r.status!=="active"||r.pendingFinishReply)return;this.host.sendTo(r.ownerConnectionId,{type:"sessionPreview",sessionId:e,partialTranscript:n})}catch(r){m.error(`[VoiceEngine] onSttPartial threw: ${R(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){m.error(`[VoiceEngine] onPcmFrame threw: ${R(r)}`)}}}}submit(e){if(!this.disposed){if(this.dispatchDepth>=Co){m.error(`[VoiceEngine] dispatch depth exceeded ${Co} 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}=_o(this.snapshot,this.internal,e);this.snapshot=i,this.internal=o;for(let h of a)try{this.dispatch(h)}catch(u){m.error(`[VoiceEngine] dispatching effect '${h.type}' threw: ${R(u)}`)}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"&&m.error(`[VoiceEngine] adapter dispose rejected: ${R(n.reason)}`)}emitEnvelope(e,n){try{this.host.sendTo(n,{type:"sessionAudio",sessionId:e,envelope:this.levelMeter.current()})}catch(r){m.error(`[VoiceEngine] emitEnvelope threw: ${R(r)}`)}}dispatch(e){switch(e.type){case"checkRuntime":this.foundry.checkRuntime(e.generation);break;case"fetchCatalog":this.foundry.fetchCatalog(e.generation);break;case"installRuntime":this.foundry.installRuntime(e.generation);break;case"downloadModel":this.foundry.downloadModel(e.variantId,e.generation);break;case"cancelDownload":this.foundry.cancelDownload(e.variantId);break;case"loadModel":this.foundry.loadModel(e.variantId,e.generation);break;case"unloadModel":this.foundry.unloadModel(e.variantId);break;case"deleteModel":this.foundry.deleteModel(e.variantId);break;case"warmupSession":{let{sessionId:n,variantId:r,device:i}=e,o;try{o=this.mic.openForSession(n,i)}catch(u){o=Promise.reject(u instanceof Error?u:new Error(String(u)))}let a=o.then(u=>(u.ok||this.foundry.cancelSttSession(n),u)),l;try{l=this.foundry.openSttSession(n,r)}catch(u){l=Promise.reject(u instanceof Error?u:new Error(String(u)))}let h=l.then(u=>(u.ok||this.mic.closeSession("discard").catch(()=>{}),u));Promise.all([a,h]).then(([u,f])=>{this.disposed||(u.ok&&f.ok?this.submit({type:"internal:sessionWarmed",sessionId:n}):u.ok?f.ok||this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"stt",subreason:f.subreason}}):this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"mic",subreason:u.subreason}}))},u=>{m.error(`[VoiceEngine] warmupSession(${n}) rejected: ${R(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=>{m.error(`[VoiceEngine] commitSession(${n}) drain rejected: ${R(r)}`),!this.disposed&&this.foundry.endSttSession(n)});break}case"replyResolve":this.host.resolveRpc(e.connectionId,e.requestId,e.result);break;case"replyReject":this.host.rejectRpc(e.connectionId,e.requestId,e.reason);break;case"listAudioDevices":{let{connectionId:n,requestId:r}=e,i;try{i=this.mic.listDevices()}catch(o){i=Promise.reject(o instanceof Error?o:new Error(String(o)))}i.then(o=>{this.disposed||this.host.resolveRpc(n,r,o)},o=>{m.error(`[VoiceEngine] listAudioDevices rejected: ${R(o)}`),!this.disposed&&this.host.resolveRpc(n,r,{ok:!1,reason:"unavailable"})});break}case"broadcast":this.host.broadcast(e.event);break;case"sendTo":this.host.sendTo(e.connectionId,e.event);break;case"logWarning":m.warning(`[VoiceEngine] ${e.message}`);break;default:Xc(e)}}};import{existsSync as Sr}from"node:fs";import{dirname as To,join as Er}from"node:path";import{fileURLToPath as Zc}from"node:url";function xo(t){let{importMetaUrl:e,filename:n,label:r}=t,i;try{i=To(Zc(e))}catch(u){throw new Error(`Voice ${r} worker bundle unavailable: cannot resolve module URL (${R(u)}).`)}let o=Er(i,n);if(Sr(o))return o;let a=ed(i),l=a?Er(a,"dist-cli",n):void 0;if(l&&Sr(l))return l;let h=l?`${o}, ${l}`:o;throw new Error(`Voice ${r} worker bundle not found. Searched: ${h}`)}function ed(t){let e=t;for(;;){if(Sr(Er(e,"package.json")))return e;let n=To(e);if(n===e)return;e=n}}function Mo(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var wr=16*1024;function br(t,e,n=m){let r=td(t.level)?t.level:"info",i=typeof t.message=="string"?t.message:Mo(t.message);n[r](`[${e} worker] ${nd(i)}`)}function td(t){return t==="debug"||t==="info"||t==="warning"||t==="error"}function nd(t){return t.length<=wr?t:`${t.slice(0,wr)}\u2026 [truncated, ${t.length-wr} more chars]`}import{Worker as rd}from"node:worker_threads";var No=(t,e)=>new rd(t,e);import{createRequire as od}from"node:module";import*as we from"node:fs/promises";import*as ne from"node:path";import{createHash as sd}from"node:crypto";import{join as it,basename as Fu}from"node:path";import{homedir as Rr}from"node:os";function id(){return process.env.XDG_CACHE_HOME||it(Rr(),".cache")}function Oo(){if(process.platform==="darwin")return it(Rr(),"Library","Caches","copilot");if(process.platform==="win32"){let t=process.env.LOCALAPPDATA||it(Rr(),".cache");return it(t,"copilot")}return it(id(),"copilot")}var ad=1,cd=".complete";var Fo={"win32-x64":"win-x64","win32-arm64":"win-arm64","linux-x64":"linux-x64","darwin-arm64":"osx-arm64"};function dd(){return typeof __foundryRequire<"u"&&__foundryRequire||od(import.meta.url)}var Jt;function ld(){if(Jt)return Jt;try{let t=dd()("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 Jt=t,Jt}catch(t){throw new Error(`Failed to load foundry-local-sdk/deps_versions.json: ${R(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 ud(t=process.platform){let e=ld();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 Do(t){return t==="win32"?".dll":t==="darwin"?".dylib":".so"}function pd(t,e){return ne.join(t,`Microsoft.AI.Foundry.Local.Core${Do(e)}`)}function fd(t){let e=Do(t),n=t==="win32"?"":"lib";return[`Microsoft.AI.Foundry.Local.Core${e}`,`${n}onnxruntime${e}`,`${n}onnxruntime-genai${e}`]}function gd(t,e=process.platform,n=process.arch){let r=Fo[`${e}-${n}`];if(!r)throw new Error(`Voice mode not supported on ${e}-${n}`);let i=t??process.env.COPILOT_CACHE_HOME??Oo(),o=ud(e),a=sd("sha256").update(JSON.stringify({schema:ad,artifacts:o})).digest("hex").slice(0,12);return ne.join(i,"foundry",a,r)}async function Vo(t={}){let e=t.platform??process.platform,n=t.arch??process.arch,r=`${e}-${n}`,i=Fo[r];if(!i)return{kind:"unsupported-platform",platformKey:r};let o=gd(t.cacheRoot,e,n),a=fd(e);if(await Lo(o,a))return{kind:"downloaded",location:{corePath:pd(o,e)}};let l=ne.dirname(ne.dirname(o)),h;try{h=await we.readdir(l)}catch{return{kind:"not-downloaded"}}let u=ne.basename(ne.dirname(o));for(let f of h){if(f===u)continue;let _=ne.join(l,f,i);if(await Lo(_,a))return{kind:"update-available"}}return{kind:"not-downloaded"}}async function Lo(t,e){return await Ao(ne.join(t,cd))?(await Promise.all(e.map(r=>Ao(ne.join(t,r))))).every(Boolean):!1}async function Ao(t){try{return await we.access(t),!0}catch{return!1}}var $o=5e3;function jo(t={}){let{cacheRoot:e,workerFactory:n=No,workerScriptPath:r,inspectImpl:i=Vo}=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()+$o},l},install(l){if(o)return o;a=void 0;let h=hd({cacheRoot:e,workerFactory:n,workerScriptPath:r??xo({importMetaUrl:import.meta.url,filename:"voice-installer.worker.js",label:"installer"}),onProgress:l}).then(u=>(a={result:{kind:"downloaded",location:u},expiry:Date.now()+$o},u)).catch(u=>{throw o=void 0,a=void 0,u});return o=h,h}}}function hd(t){return new Promise((e,n)=>{let r;try{r=t.workerFactory(t.workerScriptPath,{workerData:{cacheRoot:t.cacheRoot}})}catch(a){n(jt(a));return}let i=!1,o=a=>{i||(i=!0,r.terminate().catch(l=>{m.warning(`[voice-runtime] installer worker terminate failed: ${R(l)}`)}),a())};r.on("message",a=>{if(a==null||typeof a!="object"){m.warning("[voice-runtime] installer worker posted a malformed message; ignoring");return}let l=a;if(l.kind==="log"){br(l,"Installer");return}if(l.kind==="download-started"){if(!t.onProgress)return;try{t.onProgress({kind:"indeterminate"})}catch(h){m.warning(`[voice-runtime] installer onProgress threw: ${R(h)}`)}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(jt(a)))}),r.on("exit",a=>{o(()=>n(new Error(`Voice installer worker exited unexpectedly with code ${a}.`)))})})}import{readFileSync as md,unlinkSync as yd,writeFileSync as vd}from"node:fs";function qo(t,e){vd(t,`${e}
`,{encoding:"utf8"})}function Ho(t){let e;try{e=md(t,"utf8")}catch{return null}let n=Number(e.trim());return!Number.isSafeInteger(n)||n<=0?null:n}function Wo(t){try{yd(t)}catch{}}var Kt=at(Dt(),1);import{unlinkSync as Sd}from"node:fs";import{createConnection as Ed,createServer as wd}from"node:net";var Uo=at(Dt(),1),zt=class extends Uo.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 bd(this.address,n=>this.handleSocket(n));return e===null?"lost":(this.server=e,"bound")}async stop(){if(this.stopped)return;this.stopped=!0,m.info(`voice server: server stopping (clients=${this.host.connectionCount})`);let e=this.server;this.server=null,e&&await new Promise(n=>{e.close(()=>n())})}handleSocket(e){if(this.stopped){e.destroy();return}let n=(0,Kt.createMessageConnection)(new Kt.SocketMessageReader(e),new zt(e));try{let r=this.host.registerConnection({connection:n});m.info(`voice server: client connected id=${r.connectionId} (clients=${this.host.connectionCount})`)}catch(r){m.error(`voice server: registerConnection failed: ${r.message}`);try{n.dispose()}catch{}e.destroy()}}};function bd(t,e){return new Promise((n,r)=>{let i=o=>{let a=wd(e),l=h=>{if(a.removeAllListeners(),h.code==="EADDRINUSE"&&o&&process.platform!=="win32"){let u=Ed(t);u.once("connect",()=>{u.destroy(),n(null)}),u.once("error",f=>{let _=f.code;if(_==="ECONNREFUSED"||_==="ENOENT"){try{Sd(t)}catch{}i(!1)}else n(null)});return}if(h.code==="EADDRINUSE"||h.code==="EEXIST"){n(null);return}r(h)};a.once("error",l),a.listen(t,()=>{a.removeListener("error",l),n(a)})};i(!0)})}import{createHash as Pd}from"node:crypto";import{mkdirSync as Jo}from"node:fs";import{homedir as zo,tmpdir as Cd}from"node:os";import{join as We}from"node:path";import{readFileSync as Rd}from"fs";import{dirname as _d,join as _r}from"path";import{fileURLToPath as kd}from"url";var ot=null;function Bo(){return Id().version}function Id(){if(ot!==null)return ot;try{let t=kd(import.meta.url),e=_d(t),n=[_r(e,"package.json"),_r(e,"../package.json"),_r(e,"../../package.json")];for(let i of n)try{let o=JSON.parse(Rd(i,"utf8")),a={name:o.name||"unknown",version:o.version||"unknown",buildMetadata:o.buildMetadata};return ot=a,a}catch{continue}let r={name:"unknown",version:"unknown"};return ot=r,r}catch{let e={name:"unknown",version:"unknown"};return ot=e,e}}var Td=8,Qt="copilot-voice",xd="COPILOT_VOICE_SERVER_INSTANCE",Md=100;function Go(t={}){let e=t.platform??process.platform,n=t.env??process.env,r=t.tmpDir??Cd(),i=t.cliVersion??Bo(),o=n[xd]||void 0;if(e==="win32"){let _=Yt(n.USERPROFILE??n.HOMEPATH??n.USERNAME??t.homeDir??zo()??"anon"),k=Yt(`${i}|${_}${o?`|${o}`:""}`),F=`\\\\.\\pipe\\${Qt}-${k}`,E=We(r,Qt);return Jo(E,{recursive:!0}),{address:F,pidFile:We(E,`${k}.pid`),endpointHash:k}}let a=Yt(o?`${i}|${o}`:i),l=n.XDG_RUNTIME_DIR,h=Yt(n.HOME??t.homeDir??zo()??n.USER??"anon"),u=l?We(l,Qt):We(r,`${Qt}-${h}`);Jo(u,{recursive:!0,mode:448});let f=We(u,`${a}.sock`);return f.length>Md&&m.warning(`voice server: Unix socket path is ${f.length} bytes (macOS limit is 104): ${f}`),{address:f,pidFile:We(u,`${a}.pid`),endpointHash:a}}function Yt(t){return Pd("sha256").update(t).digest("hex").slice(0,Td)}var Ko="COPILOT_VOICE_SERVER_BOOT";function Qo(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}if(!kr(e))return{};let n=Nd(e.voice);return Object.keys(n).length>0?{voice:n}:{}}function Nd(t){let e={};if(!kr(t))return e;let n=t.enabled;typeof n=="boolean"&&(e.enabled=n);let r=t.selectedModel;typeof r=="string"&&r.length>0&&(e.selectedModel=r);let i=Od(t.selectedDevice);return i&&(e.selectedDevice=i),e}function Od(t){if(!kr(t))return;let e=t.name;if(typeof e!="string"||e.length===0)return;let n=t.occurrence,r=typeof n=="number"&&Number.isInteger(n)&&n>=0?n:0;return{name:e,occurrence:r}}function kr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ad=10,Yo=1,Xo=6e4;async function Np(){let t=Go(),e=Fd(t.endpointHash),n=J.runnerCreateFileLogger(e,void 0,void 0,Ge.getInstance().nativeHandleId);m.setLogWriter(n),m.info(`voice server: boot pid=${process.pid} endpoint=${t.address}`);let r=jo(),i=new $t,o=new Bt({host:i,foundryFactory:E=>new qt({events:E,installer:r}),micFactory:E=>new Ht({events:E}),bootSettings:Qo(process.env[Ko])});i.setSubmit(E=>o.submit(E));let a=!1,l=null,h=()=>{l===null&&(l=setTimeout(()=>{l=null,m.info("voice server: idle timeout, shutting down"),F("idle timeout").catch(()=>{})},Xo))},u=()=>{l!==null&&(clearTimeout(l),l=null)};i.onClientConnected(()=>u()),i.onClientDisconnected(()=>{a||i.connectionCount===0&&h()}),h();let f=new Gt({host:i,address:t.address}),_;try{_=await f.start()}catch(E){m.error(`voice server: bind threw: ${E.stack??String(E)}`),await n.flush().catch(()=>{}),process.exit(Yo)}_==="lost"&&(m.info(`voice server: bind-loser, another voice server owns ${t.address}`),await o.dispose().catch(()=>{}),await n.flush().catch(()=>{}),process.exit(Ad));try{qo(t.pidFile,process.pid)}catch(E){m.error(`voice server: writeServerPidFile failed: ${E.message}`),await f.stop(),await o.dispose().catch(()=>{}),await n.flush().catch(()=>{}),process.exit(Yo)}let k=()=>{Ho(t.pidFile)===process.pid&&Wo(t.pidFile)},F=async E=>{if(a)return;a=!0,u(),m.info(`voice server: shutdown (${E})`);let I=f.stop().catch(w=>{m.error(`voice server: server.stop failed: ${w.message}`)});i.dispose(),await I,await o.dispose().catch(w=>{m.error(`voice server: engine.dispose failed: ${w.message}`)}),k(),await n.flush().catch(()=>{}),process.exit(0)};for(let E of["SIGINT","SIGTERM","SIGHUP"])process.on(E,()=>{F(`signal ${E}`).catch(()=>{})});process.on("uncaughtException",E=>{m.error(`voice server: uncaughtException: ${E.stack??String(E)}`),F("uncaughtException").catch(()=>{})}),process.on("unhandledRejection",E=>{m.error(`voice server: unhandledRejection: ${String(E)}`)}),process.on("exit",()=>{k()}),m.info(`voice server: ready (idle timer armed ${Xo}ms)`)}function Fd(t){return Ld(Pi(void 0,"state"),"logs",`voice-server-${t}.log`)}export{Np as runVoiceServer};
