UNPKG

@github/copilot

Version:

GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.

90 lines 130 kB
(()=>{const stack=new Error().stack;stack&&(globalThis._sentryDebugIds=globalThis._sentryDebugIds||{},globalThis._sentryDebugIds[stack]="f7b73147-de81-5fd4-b94c-2faa87111f3a",globalThis._sentryDebugIdIdentifier="sentry-dbid-f7b73147-de81-5fd4-b94c-2faa87111f3a");})();

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

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

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

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

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

`),V.log(`Sending request '${o.method} - (${o.id})'.`,d)}else Re("send-request",o)}function io(o){if(!(T===I.Off||!V))if(ye===Y.Text){let d;(T===I.Verbose||T===I.Compact)&&(o.params?d=`Params: ${le(o.params)}

`:d=`No parameters provided.

`),V.log(`Sending notification '${o.method}'.`,d)}else Re("send-notification",o)}function tt(o,d,p){if(!(T===I.Off||!V))if(ye===Y.Text){let g;(T===I.Verbose||T===I.Compact)&&(o.error&&o.error.data?g=`Error data: ${le(o.error.data)}

`:o.result?g=`Result: ${le(o.result)}

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

`)),V.log(`Sending response '${d} - (${o.id})'. Processing request took ${Date.now()-p}ms`,g)}else Re("send-response",o)}function so(o){if(!(T===I.Off||!V))if(ye===Y.Text){let d;(T===I.Verbose||T===I.Compact)&&o.params&&(d=`Params: ${le(o.params)}

`),V.log(`Received request '${o.method} - (${o.id})'.`,d)}else Re("receive-request",o)}function Zt(o){if(!(T===I.Off||!V||o.method===wt.type.method))if(ye===Y.Text){let d;(T===I.Verbose||T===I.Compact)&&(o.params?d=`Params: ${le(o.params)}

`:d=`No parameters provided.

`),V.log(`Received notification '${o.method}'.`,d)}else Re("receive-notification",o)}function oo(o,d){if(!(T===I.Off||!V))if(ye===Y.Text){let p;if((T===I.Verbose||T===I.Compact)&&(o.error&&o.error.data?p=`Error data: ${le(o.error.data)}

`:o.result?p=`Result: ${le(o.result)}

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

`)),d){let g=o.error?` Request failed: ${o.error.message} (${o.error.code}).`:"";V.log(`Received response '${d.method} - (${o.id})' in ${Date.now()-d.timerStart}ms.${g}`,p)}else V.log(`Received response ${o.id} without active response promise.`,p)}else Re("receive-response",o)}function Re(o,d){if(!V||T===I.Off)return;let p={isLSPMessage:!0,type:o,message:d,timestamp:Date.now()};V.log(p)}function qe(){if(Mr())throw new Fe(Ye.Closed,"Connection is closed.");if(we())throw new Fe(Ye.Disposed,"Connection is disposed.")}function ao(){if(Ar())throw new Fe(Ye.AlreadyListening,"Connection is already listening")}function co(){if(!Ar())throw new Error("Call listen() first.")}function He(o){return o===void 0?null:o}function Fr(o){if(o!==null)return o}function Dr(o){return o!=null&&!Array.isArray(o)&&typeof o=="object"}function Qt(o,d){switch(o){case y.ParameterStructures.auto:return Dr(d)?Fr(d):[He(d)];case y.ParameterStructures.byName:if(!Dr(d))throw new Error("Received parameters by name but param is not an object literal.");return Fr(d);case y.ParameterStructures.byPosition:return[He(d)];default:throw new Error(`Unknown parameter structure ${o.toString()}`)}}function Vr(o,d){let p,g=o.numberOfParams;switch(g){case 0:p=void 0;break;case 1:p=Qt(o.parameterStructures,d[0]);break;default:p=[];for(let A=0;A<d.length&&A<g;A++)p.push(He(d[A]));if(d.length<g)for(let A=d.length;A<g;A++)p.push(null);break}return p}let Te={sendNotification:(o,...d)=>{qe();let p,g;if(L.string(o)){p=o;let P=d[0],x=0,F=y.ParameterStructures.auto;y.ParameterStructures.is(P)&&(x=1,F=P);let _=d.length,N=_-x;switch(N){case 0:g=void 0;break;case 1:g=Qt(F,d[x]);break;default:if(F===y.ParameterStructures.byName)throw new Error(`Received ${N} parameters for 'by Name' notification parameter structure.`);g=d.slice(x,_).map(R=>He(R));break}}else{let P=d;p=o.method,g=Vr(o,P)}let A={jsonrpc:l,method:p,params:g};return io(A),e.write(A).catch(P=>{throw i.error("Sending notification failed."),P})},onNotification:(o,d)=>{qe();let p;return L.func(o)?O=o:d&&(L.string(o)?(p=o,j.set(o,{type:void 0,handler:d})):(p=o.method,j.set(o.method,{type:o,handler:d}))),{dispose:()=>{p!==void 0?j.delete(p):O=void 0}}},onProgress:(o,d,p)=>{if(G.has(d))throw new Error(`Progress handler for token ${d} already registered`);return G.set(d,p),{dispose:()=>{G.delete(d)}}},sendProgress:(o,d,p)=>Te.sendNotification(Je.type,{token:d,value:p}),onUnhandledProgress:Or.event,sendRequest:(o,...d)=>{qe(),co();let p,g,A;if(L.string(o)){p=o;let _=d[0],N=d[d.length-1],R=0,U=y.ParameterStructures.auto;y.ParameterStructures.is(_)&&(R=1,U=_);let B=d.length;Qn.CancellationToken.is(N)&&(B=B-1,A=N);let ne=B-R;switch(ne){case 0:g=void 0;break;case 1:g=Qt(U,d[R]);break;default:if(U===y.ParameterStructures.byName)throw new Error(`Received ${ne} parameters for 'by Name' request parameter structure.`);g=d.slice(R,B).map(uo=>He(uo));break}}else{let _=d;p=o.method,g=Vr(o,_);let N=o.numberOfParams;A=Qn.CancellationToken.is(_[N])?_[N]:void 0}let P=s++,x;A&&(x=A.onCancellationRequested(()=>{let _=ue.sender.sendCancellation(Te,P);return _===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${P}`),Promise.resolve()):_.catch(()=>{i.log(`Sending cancellation messages for id ${P} failed`)})}));let F={jsonrpc:l,id:P,method:p,params:g};return ro(F),typeof ue.sender.enableCancellation=="function"&&ue.sender.enableCancellation(F),new Promise(async(_,N)=>{let R=ne=>{_(ne),ue.sender.cleanup(P),x?.dispose()},U=ne=>{N(ne),ue.sender.cleanup(P),x?.dispose()},B={method:p,timerStart:Date.now(),resolve:R,reject:U};try{z.set(P,B),await e.write(F)}catch(ne){throw z.delete(P),B.reject(new y.ResponseError(y.ErrorCodes.MessageWriteError,ne.message?ne.message:"Unknown reason")),i.error("Sending request failed."),ne}})},onRequest:(o,d)=>{qe();let p=null;return tr.is(o)?(p=void 0,v=o):L.string(o)?(p=null,d!==void 0&&(p=o,w.set(o,{handler:d,type:void 0}))):d!==void 0&&(p=o.method,w.set(o.method,{type:o,handler:d})),{dispose:()=>{p!==null&&(p!==void 0?w.delete(p):v=void 0)}}},hasPendingResponse:()=>z.size>0,trace:async(o,d,p)=>{let g=!1,A=Y.Text;p!==void 0&&(L.boolean(p)?g=p:(g=p.sendNotification||!1,A=p.traceFormat||Y.Text)),T=o,ye=A,T===I.Off?V=void 0:V=d,g&&!Mr()&&!we()&&await Te.sendNotification(nr.type,{value:I.toString(o)})},onError:Yt.event,onClose:Tr.event,onUnhandledNotification:Pr.event,onDispose:Cr.event,end:()=>{e.end()},dispose:()=>{if(we())return;de=X.Disposed,Cr.fire(void 0);let o=new y.ResponseError(y.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let d of z.values())d.reject(o);z=new Map,J=new Map,$e=new Set,W=new ji.LinkedMap,L.func(e.dispose)&&e.dispose(),L.func(t.dispose)&&t.dispose()},listen:()=>{qe(),ao(),de=X.Listening,t.listen(Qs)},inspect:()=>{(0,Ui.default)().console.log("inspect")}};return Te.onNotification(wt.type,o=>{if(T===I.Off||!V)return;let d=T===I.Verbose||T===I.Compact;V.log(o.message,d?o.verbose:void 0)}),Te.onNotification(Je.type,o=>{let d=G.get(o.token);d?d(o.value):Or.fire(o)}),Te}E.createMessageConnection=ba});var kt=D(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.ProgressType=c.ProgressToken=c.createMessageConnection=c.NullLogger=c.ConnectionOptions=c.ConnectionStrategy=c.AbstractMessageBuffer=c.WriteableStreamMessageWriter=c.AbstractMessageWriter=c.MessageWriter=c.ReadableStreamMessageReader=c.AbstractMessageReader=c.MessageReader=c.SharedArrayReceiverStrategy=c.SharedArraySenderStrategy=c.CancellationToken=c.CancellationTokenSource=c.Emitter=c.Event=c.Disposable=c.LRUCache=c.Touch=c.LinkedMap=c.ParameterStructures=c.NotificationType9=c.NotificationType8=c.NotificationType7=c.NotificationType6=c.NotificationType5=c.NotificationType4=c.NotificationType3=c.NotificationType2=c.NotificationType1=c.NotificationType0=c.NotificationType=c.ErrorCodes=c.ResponseError=c.RequestType9=c.RequestType8=c.RequestType7=c.RequestType6=c.RequestType5=c.RequestType4=c.RequestType3=c.RequestType2=c.RequestType1=c.RequestType0=c.RequestType=c.Message=c.RAL=void 0;c.MessageStrategy=c.CancellationStrategy=c.CancellationSenderStrategy=c.CancellationReceiverStrategy=c.ConnectionError=c.ConnectionErrors=c.LogTraceNotification=c.SetTraceNotification=c.TraceFormat=c.TraceValues=c.Trace=void 0;var k=kn();Object.defineProperty(c,"Message",{enumerable:!0,get:function(){return k.Message}});Object.defineProperty(c,"RequestType",{enumerable:!0,get:function(){return k.RequestType}});Object.defineProperty(c,"RequestType0",{enumerable:!0,get:function(){return k.RequestType0}});Object.defineProperty(c,"RequestType1",{enumerable:!0,get:function(){return k.RequestType1}});Object.defineProperty(c,"RequestType2",{enumerable:!0,get:function(){return k.RequestType2}});Object.defineProperty(c,"RequestType3",{enumerable:!0,get:function(){return k.RequestType3}});Object.defineProperty(c,"RequestType4",{enumerable:!0,get:function(){return k.RequestType4}});Object.defineProperty(c,"RequestType5",{enumerable:!0,get:function(){return k.RequestType5}});Object.defineProperty(c,"RequestType6",{enumerable:!0,get:function(){return k.RequestType6}});Object.defineProperty(c,"RequestType7",{enumerable:!0,get:function(){return k.RequestType7}});Object.defineProperty(c,"RequestType8",{enumerable:!0,get:function(){return k.RequestType8}});Object.defineProperty(c,"RequestType9",{enumerable:!0,get:function(){return k.RequestType9}});Object.defineProperty(c,"ResponseError",{enumerable:!0,get:function(){return k.ResponseError}});Object.defineProperty(c,"ErrorCodes",{enumerable:!0,get:function(){return k.ErrorCodes}});Object.defineProperty(c,"NotificationType",{enumerable:!0,get:function(){return k.NotificationType}});Object.defineProperty(c,"NotificationType0",{enumerable:!0,get:function(){return k.NotificationType0}});Object.defineProperty(c,"NotificationType1",{enumerable:!0,get:function(){return k.NotificationType1}});Object.defineProperty(c,"NotificationType2",{enumerable:!0,get:function(){return k.NotificationType2}});Object.defineProperty(c,"NotificationType3",{enumerable:!0,get:function(){return k.NotificationType3}});Object.defineProperty(c,"NotificationType4",{enumerable:!0,get:function(){return k.NotificationType4}});Object.defineProperty(c,"NotificationType5",{enumerable:!0,get:function(){return k.NotificationType5}});Object.defineProperty(c,"NotificationType6",{enumerable:!0,get:function(){return k.NotificationType6}});Object.defineProperty(c,"NotificationType7",{enumerable:!0,get:function(){return k.NotificationType7}});Object.defineProperty(c,"NotificationType8",{enumerable:!0,get:function(){return k.NotificationType8}});Object.defineProperty(c,"NotificationType9",{enumerable:!0,get:function(){return k.NotificationType9}});Object.defineProperty(c,"ParameterStructures",{enumerable:!0,get:function(){return k.ParameterStructures}});var sr=Mn();Object.defineProperty(c,"LinkedMap",{enumerable:!0,get:function(){return sr.LinkedMap}});Object.defineProperty(c,"LRUCache",{enumerable:!0,get:function(){return sr.LRUCache}});Object.defineProperty(c,"Touch",{enumerable:!0,get:function(){return sr.Touch}});var Sa=Oi();Object.defineProperty(c,"Disposable",{enumerable:!0,get:function(){return Sa.Disposable}});var Gi=Me();Object.defineProperty(c,"Event",{enumerable:!0,get:function(){return Gi.Event}});Object.defineProperty(c,"Emitter",{enumerable:!0,get:function(){return Gi.Emitter}});var Bi=Et();Object.defineProperty(c,"CancellationTokenSource",{enumerable:!0,get:function(){return Bi.CancellationTokenSource}});Object.defineProperty(c,"CancellationToken",{enumerable:!0,get:function(){return Bi.CancellationToken}});var Wi=ki();Object.defineProperty(c,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return Wi.SharedArraySenderStrategy}});Object.defineProperty(c,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return Wi.SharedArrayReceiverStrategy}});var or=Mi();Object.defineProperty(c,"MessageReader",{enumerable:!0,get:function(){return or.MessageReader}});Object.defineProperty(c,"AbstractMessageReader",{enumerable:!0,get:function(){return or.AbstractMessageReader}});Object.defineProperty(c,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return or.ReadableStreamMessageReader}});var ar=Di();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 _a=Vi();Object.defineProperty(c,"AbstractMessageBuffer",{enumerable:!0,get:function(){return _a.AbstractMessageBuffer}});var $=Hi();Object.defineProperty(c,"ConnectionStrategy",{enumerable:!0,get:function(){return $.ConnectionStrategy}});Object.defineProperty(c,"ConnectionOptions",{enumerable:!0,get:function(){return $.ConnectionOptions}});Object.defineProperty(c,"NullLogger",{enumerable:!0,get:function(){return $.NullLogger}});Object.defineProperty(c,"createMessageConnection",{enumerable:!0,get:function(){return $.createMessageConnection}});Object.defineProperty(c,"ProgressToken",{enumerable:!0,get:function(){return $.ProgressToken}});Object.defineProperty(c,"ProgressType",{enumerable:!0,get:function(){return $.ProgressType}});Object.defineProperty(c,"Trace",{enumerable:!0,get:function(){return $.Trace}});Object.defineProperty(c,"TraceValues",{enumerable:!0,get:function(){return $.TraceValues}});Object.defineProperty(c,"TraceFormat",{enumerable:!0,get:function(){return $.TraceFormat}});Object.defineProperty(c,"SetTraceNotification",{enumerable:!0,get:function(){return $.SetTraceNotification}});Object.defineProperty(c,"LogTraceNotification",{enumerable:!0,get:function(){return $.LogTraceNotification}});Object.defineProperty(c,"ConnectionErrors",{enumerable:!0,get:function(){return $.ConnectionErrors}});Object.defineProperty(c,"ConnectionError",{enumerable:!0,get:function(){return $.ConnectionError}});Object.defineProperty(c,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return $.CancellationReceiverStrategy}});Object.defineProperty(c,"CancellationSenderStrategy",{enumerable:!0,get:function(){return $.CancellationSenderStrategy}});Object.defineProperty(c,"CancellationStrategy",{enumerable:!0,get:function(){return $.CancellationStrategy}});Object.defineProperty(c,"MessageStrategy",{enumerable:!0,get:function(){return $.MessageStrategy}});var Ia=ge();c.RAL=Ia.default});var Ji=D(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});var zi=oe("util"),ce=kt(),At=class t extends ce.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 zi.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)}};At.emptyBuffer=Buffer.allocUnsafe(0);var cr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ce.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ce.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ce.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),ce.Disposable.create(()=>this.stream.off("data",e))}},dr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ce.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ce.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ce.Disposable.create(()=>this.stream.off("end",e))}write(e,n){return new Promise((r,i)=>{let s=a=>{a==null?r():i(a)};typeof e=="string"?this.stream.write(e,n,s):this.stream.write(e,s)})}end(){this.stream.end()}},Ki=Object.freeze({messageBuffer:Object.freeze({create:t=>new At(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 zi.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 ur(){return Ki}(function(t){function e(){ce.RAL.install(Ki)}t.install=e})(ur||(ur={}));lr.default=ur});var Qi=D(S=>{"use strict";var wa=S&&S.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ra=S&&S.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&wa(e,t,n)};Object.defineProperty(S,"__esModule",{value:!0});S.createMessageConnection=S.createServerSocketTransport=S.createClientSocketTransport=S.createServerPipeTransport=S.createClientPipeTransport=S.generateRandomPipeName=S.StreamMessageWriter=S.StreamMessageReader=S.SocketMessageWriter=S.SocketMessageReader=S.PortMessageWriter=S.PortMessageReader=S.IPCMessageWriter=S.IPCMessageReader=void 0;var De=Ji();De.default.install();var Yi=oe("path"),Ta=oe("os"),Pa=oe("crypto"),Lt=oe("net"),Z=kt();Ra(kt(),S);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))}};S.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(){}};S.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)}};S.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(){}};S.PortMessageWriter=hr;var _e=class extends Z.ReadableStreamMessageReader{constructor(e,n="utf-8"){super((0,De.default)().stream.asReadableStream(e),n)}};S.SocketMessageReader=_e;var Ie=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,De.default)().stream.asWritableStream(e),n),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};S.SocketMessageWriter=Ie;var Mt=class extends Z.ReadableStreamMessageReader{constructor(e,n){super((0,De.default)().stream.asReadableStream(e),n)}};S.StreamMessageReader=Mt;var Nt=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,De.default)().stream.asWritableStream(e),n)}};S.StreamMessageWriter=Nt;var Zi=process.env.XDG_RUNTIME_DIR,Oa=new Map([["linux",107],["darwin",103]]);function Ca(){let t=(0,Pa.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${t}-sock`;let e;Zi?e=Yi.join(Zi,`vscode-ipc-${t}.sock`):e=Yi.join(Ta.tmpdir(),`vscode-${t}.sock`);let n=Oa.get(process.platform);return n!==void 0&&e.length>n&&(0,De.default)().console.warn(`WARNING: IPC handle "${e}" is longer than ${n} characters.`),e}S.generateRandomPipeName=Ca;function ka(t,e="utf-8"){let n,r=new Promise((i,s)=>{n=i});return new Promise((i,s)=>{let a=(0,Lt.createServer)(u=>{a.close(),n([new _e(u,e),new Ie(u,e)])});a.on("error",s),a.listen(t,()=>{a.removeListener("error",s),i({onConnected:()=>r})})})}S.createClientPipeTransport=ka;function Aa(t,e="utf-8"){let n=(0,Lt.createConnection)(t);return[new _e(n,e),new Ie(n,e)]}S.createServerPipeTransport=Aa;function Ma(t,e="utf-8"){let n,r=new Promise((i,s)=>{n=i});return new Promise((i,s)=>{let a=(0,Lt.createServer)(u=>{a.close(),n([new _e(u,e),new Ie(u,e)])});a.on("error",s),a.listen(t,"127.0.0.1",()=>{a.removeListener("error",s),i({onConnected:()=>r})})})}S.createClientSocketTransport=Ma;function Na(t,e="utf-8"){let n=(0,Lt.createConnection)(t,"127.0.0.1");return[new _e(n,e),new Ie(n,e)]}S.createServerSocketTransport=Na;function La(t){let e=t;return e.read!==void 0&&e.addListener!==void 0}function xa(t){let e=t;return e.write!==void 0&&e.addListener!==void 0}function Fa(t,e,n,r){n||(n=Z.NullLogger);let i=La(t)?new Mt(t):t,s=xa(e)?new Nt(e):e;return Z.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,Z.createMessageConnection)(i,s,n,r)}S.createMessageConnection=Fa});var xt=D((Cu,Xi)=>{"use strict";Xi.exports=Qi()});import{join as ld}from"node:path";import*as rt from"os";import*as Ee from"path";var vo=".copilot";function jr(t,e){return t?.configDir?t.configDir:process.env.COPILOT_HOME?process.env.COPILOT_HOME:Ee.join(rt.homedir(),vo)}var hd=rt.tmpdir();var Xt=class{initialQueue=[];initialQueueResolvers=Promise.withResolvers();logWriter=null;writePromise=this.initialQueueResolvers.promise;setLogWriter(e){this.logWriter=e;for(let n of this.initialQueue)this.writePromise=this.logWriter.writeLog(n.method,n.message);this.initialQueue=[],this.initialQueueResolvers.resolve()}async flush(){await this.writePromise}async dispose(){await this.flush()}outputPath(){return this.logWriter?.outputPath()}logToLevel(e,n){this.logWriter?this.writePromise=this.logWriter.writeLog(e,n):this.initialQueue.push({method:e,message:n})}info(e){this.logToLevel("info",e)}debug(e){this.logToLevel("debug",e)}warning(e){this.logToLevel("warning",e)}error(e){this.logToLevel("error",e instanceof Error?e.message:e)}log(e){this.error(e)}isDebug(){return!1}shouldLog(e){return!0}notice(e){this.info(e instanceof Error?e.message:e)}startGroup(e,n){this.info(`--- Start of group: ${e} ---`)}endGroup(e){this.info("--- End of group ---")}},h=new Xt;import{constants as Zo}from"fs";import{access as Qo,appendFile as Xo,mkdir as ea}from"fs/promises";import{dirname as ta}from"path";import nn from"node:path";import{fileURLToPath as Ho}from"node:url";import{createRequire as xo}from"node:module";import{platform as Fo}from"node:os";import{join as gi,resolve as Do}from"node:path";import{fileURLToPath as Vo}from"node:url";var at=nt(pi(),1);function ct(t={}){return(t.platform??process.platform)!=="linux"?"gnu":(t.detectLibcFamily??at.familySync)()===at.MUSL?"musl":"gnu"}function fi(t=process.platform,e){let n=e??(t==="linux"?ct():"gnu");return t==="linux"&&n==="musl"?"linuxmusl":t}function Uo(){let t=mi(),e=t==="linux"?ct({platform:t}):"gnu";return`${fi(t,e)}-${process.arch}`}function jo(){let t=mi(),{arch:e}=process;switch(t){case"win32":return`win32-${e}-msvc`;case"darwin":return`darwin-${e}`;case"linux":return`linux-${e}-${ct({platform:t})}`;default:throw new Error(`Unsupported platform: ${t}/${e}`)}}var dt;function mi(){return dt!==void 0||(dt=process.report?.getReport()?.header?.platform??Fo()),dt}function vi(t,e){let n=Uo(),r=`${t}.node`,i=`${t}.${jo()}.node`,s=[];for(let u of e){let l=Do(u),v=gi(l,"prebuilds",n,r),w=hi(v);if(w.ok)return w.value;s.push({path:v,err:w.err});let O=gi(l,i),j=hi(O);if(j.ok)return j.value;s.push({path:O,err:j.err})}let a=s.map(u=>`  ${u.path}: ${$o(u.err)}`).join(`
`);throw new Error(`Native addon "${t}" not found for ${n}. Tried:
${a}`)}function $o(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 hi(t){try{return{ok:!0,value:qo(t)}}catch(e){return{ok:!1,err:e}}}function qo(t){return xo(Vo(import.meta.url))(t)}var yi="__copilotRuntimeAddon__";function Go(){let t=globalThis,e=t[yi];return e||(e={addon:null},t[yi]=e),e}function Ei(){let t=Go();if(t.addon)return t.addon;let e=nn.dirname(Ho(import.meta.url)),n=vi("runtime",[e,nn.resolve(e,".."),nn.resolve(e,"..","..","runtime")]);return t.addon=n,n}var Bo;function Ce(){return Bo??=Ei()}var Wo=new Proxy({},{get:(t,e)=>Reflect.get(Ce(),e),has:(t,e)=>Reflect.has(Ce(),e),set:(t,e,n)=>Reflect.set(Ce(),e,n),ownKeys:()=>Reflect.ownKeys(Ce()),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(Ce(),e),defineProperty:(t,e,n)=>Reflect.defineProperty(Ce(),e,n)});var zo=["token","secret","key","hmacKey","modelBasedRetrievalToken","metisApiKey","capiSessionToken","nonce","apiKey","bearerToken","mcpServerToken"];function rn(t,e=[]){for(let[n,r]of Object.entries(t))if(r!==null)switch(typeof r){case"object":rn(r,e);break;case"undefined":break;default:if(zo.includes(n)){let i=String(r).trim();i!=""&&e.push(i)}break}return e}var sn=["GITHUB_COPILOT_GITHUB_TOKEN","GITHUB_TOKEN","COPILOT_GITHUB_TOKEN","GITHUB_COPILOT_API_TOKEN","CAPI_HMAC_KEY","CAPI_HMAC_KEY_OVERRIDE","ANTHROPIC_API_KEY","AIP_SWE_AGENT_TOKEN","CAPI_AZURE_KEY_VAULT_URI","COPILOT_JOB_NONCE","GITHUB_MCP_SERVER_TOKEN","OPENAI_BASE_URL","OPENAI_API_KEY","COPILOT_AGENT_REQUEST_HEADERS","AZURE_OPENAI_API_KEY","AZURE_OPENAI_API_ENDPOINT","AZURE_OPENAI_KEY_VAULT_URI","AZURE_OPENAI_KEY_VAULT_SECRET_NAME","BLACKBIRD_AUTH_METIS_API_KEY","BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","GITHUB_VERIFICATION_TOKEN","COPILOT_PROVIDER_API_KEY","COPILOT_PROVIDER_BEARER_TOKEN"],Kd=["COPILOT_AGENT_CALLBACK_URL","COPILOT_AGENT_MODEL","COPILOT_AGENT_JOB_ID","COPILOT_AGENT_PROMPT","COPILOT_AGENT_PUSH","COPILOT_FIREWALL_ENABLED","COPILOT_FIREWALL_ALLOW_LIST","GITHUB_COPILOT_INTEGRATION_ID","COPILOT_INTEGRATION_ID_OVERRIDE","COPILOT_AGENT_PREVIOUS_SESSION_IDS","COPILOT_AGENT_EVENT_URL","COPILOT_AGENT_EVENT_TYPE","COPILOT_AGENT_USE_CODEQL","COPILOT_AGENT_USE_CCR","COPILOT_AGENT_USE_SECRET_SCANNING","COPILOT_AGENT_USE_DEPENDENCY_VULN","NODE_ENV","COPILOT_AGENT_ACTOR","COPILOT_AGENT_ACTOR_ID","COPILOT_AGENT_ACTOR_TYPE","COPILOT_API_URL","GITHUB_COPILOT_MCP_JSON_FROM_INPUT","COPILOT_PROVIDER_BASE_URL","COPILOT_PROVIDER_TYPE","COPILOT_PROVIDER_WIRE_API","COPILOT_PROVIDER_AZURE_API_VERSION","COPILOT_PROVIDER_MODEL_ID","COPILOT_PROVIDER_WIRE_MODEL","COPILOT_PROVIDER_MODEL_LIMITS_ID","COPILOT_PROVIDER_MAX_PROMPT_TOKENS","COPILOT_PROVIDER_MAX_OUTPUT_TOKENS","GITHUB_TOKEN_VARNAME","COPILOT_OFFLINE",...sn];import*as bi from"process";function Ge(t){let e=bi.env[t];if(e&&e.trim()!=="")return e}var Ko=["GITHUB_COPILOT_OIDC_","GITHUB_AGENTIC_APP_OIDC_"],Jo=[/\b(?:eyJ0eXAiOi|eyJhbGciOi|eyJ4NXQiOi|eyJraWQiOi)[^\s'";]+/g,/\bBearer\s+[^\s'";]+/g,/\b(?:Password|Pwd)=(?:[^\s'";]+|"[^"]+")/gi,/\s+-(?:Password|Pwd)\s+(?:[^\s'";]+|"[^"]+")/gi,/\bv1\.[0-9A-Fa-f]{40}\b/g,/\bgh[pousr]{1}_[A-Za-z0-9]{36}\b/g,/\bgithub_pat_[0-9][A-Za-z0-9]{21}_[A-Za-z0-9]{59}\b/g,/(?<![a-zA-Z\d+\-.])[a-zA-Z][a-zA-Z\d+\-.]*:\/\/([a-zA-Z\d\-._~!$&'()*+,;=%]+):([a-zA-Z\d\-._~!$&'()*+,;=:%]*)@/g,/\b[0-9A-Za-z-_~.]{3}7Q~[0-9A-Za-z-_~.]{31}\b|\b[0-9A-Za-z-_~.]{3}8Q~[0-9A-Za-z-_~.]{34}\b/g,/\b[0-9A-Za-z+/]{76}(APIM|ACDb|\+(ABa|AMC|ASt))[0-9A-Za-z+/]{5}[AQgw]==/g,/\b[0-9A-Za-z+/]{33}(AIoT|\+(ASb|AEh|ARm))[A-P][0-9A-Za-z+/]{5}=/g,/\b[0-9A-Za-z_-]{44}AzFu[0-9A-Za-z\-_]{5}[AQgw]==/g,/\b[0-9A-Za-z]{42}AzSe[A-D][0-9A-Za-z]{5}\b/g,/\b[0-9A-Za-z+/]{42}\+ACR[A-D][0-9A-Za-z+/]{5}\b/g,/\b[0-9A-Za-z]{33}AzCa[A-P][0-9A-Za-z]{5}=/g,/\boy2[a-p][0-9a-z]{15}[aq][0-9a-z]{11}[eu][bdfhjlnprtvxz357][a-p][0-9a-z]{11}[aeimquy4]\b/g,/\bnpm_[0-9A-Za-z]{36}\b/g,/\bx-ghcr-signature=[^&]+/g],Si="******",ut=class t{static singleton;static getInstance(){return t.singleton||(t.singleton=new t),t.singleton}static __resetForTests(){t.singleton=void 0}secretValuesToFilter;runner;logger;settings;additionalSecretEnvVarNames=new Set;additionalSecretValues=new Set;additionalSecretRawValues=new Set;constructor(){}setRunner(e){this.runner=e,this.logger=e.logger,this.secretValuesToFilter=void 0}applySettings(e){this.settings=e,this.secretValuesToFilter=void 0}addSecretEnvVarNames(e){for(let n of e)this.additionalSecretEnvVarNames.add(n);this.secretValuesToFilter=void 0}isAdditionalSecretValue(e){return this.additionalSecretValues.has(e)}getAdditionalSecretValues(){return new Set(this.additionalSecretValues)}getRawAdditionalSecretValues(){return new Set(this.additionalSecretRawValues)}addSecretValues(e){let n=this.additionalSecretRawValues.size;for(let r of e)this.addSecretValue(r);this.logger?.debug(`[filter]: registered ${this.additionalSecretRawValues.size-n} new filterable value(s) (${e.length} provided, total tracked: ${this.additionalSecretRawValues.size})`)}addSecretValue(e){if(e=e?.trim(),!e)return!1;let n=Buffer.from(e,"utf8").toString("base64"),r=!this.additionalSecretValues.has(e);return r&&(this.additionalSecretValues.add(e),this.additionalSecretValues.add(n),this.additionalSecretRawValues.add(e)),this.secretValuesToFilter&&!this.secretValuesToFilter.has(e)&&(this.secretValuesToFilter.add(e),this.secretValuesToFilter.add(n)),r}filterSecrets(e){let n=typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"message"),r=n?e.message??e.toString():e,i=r,s=this.getSecretValues();for(let a of s)i=i.replaceAll(a,Si);for(let a of Jo)i=i.replaceAll(a,Si);return this.logger&&i!==r&&this.logger.debug(`[filter]: filtered content (original length=${r.length}, filtered length=${i.length})`),n?(e.message=i,e):i}filterSecretsFromJsonString(e){try{let n=JSON.parse(e),r=this.filterSecretsFromObj(n);return JSON.stringify(r)}catch{return this.filterSecrets(e)}}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}getSecretValues(){if(this.secretValuesToFilter)return this.secretValuesToFilter;let e={secretEnvVars:!1,runner:!1,settings:!1},n=new Set;for(let r of sn){let i=Ge(r);i&&Be(n,i)}for(let r of this.additionalSecretEnvVarNames){let i=Ge(r);i&&Be(n,i)}e.secretEnvVars=!0;for(let r of Yo()){let i=Ge(r);i&&Be(n,i)}e.oidcEnvVarNames=!0;for(let r of this.additionalSecretValues)n.add(r);if(e.additionalSecretValues=!0,this.runner){for(let r of this.runner.sensitiveKeys){let i=Ge(r);i&&Be(n,i)}e.runner=!0}if(this.settings){let r=rn(this.settings);for(let i of r)Be(n,i);e.settings=!0}return Object.values(e).every(r=>r)&&(this.secretValuesToFilter=n,this.logger?.debug("Caching secret values to filter from all sources.")),n}};function Be(t,e){t.add(e),t.add(Buffer.from(e,"utf8").toString("base64"))}function Yo(){let t=[];for(let e of Object.keys(process.env))Ko.some(n=>e.startsWith(n))&&t.push(e);return t}function _i(...t){let e=new Set(["DEBUG","COPILOT_AGENT_DEBUG",...t]);for(let n of e)if(process.env[n]==="1"||process.env[n]?.toLocaleLowerCase()==="true")return!0;return!1}var lt=class{logLevel;debugEnvironmentVariables;secretFilter=ut.getInstance();constructor(e,n){e===void 0?_i(...n??[])?this.logLevel=4:this.logLevel=3:this.logLevel=e,this.debugEnvironmentVariables=n}filterSecrets(e){return typeof e=="string"?this.secretFilter.filterSecrets(e):this.secretFilter.filterSecrets(e)}shouldLog(e){return this.logLevel===void 0||this.logLevel>=e}isDebug(){return _i(...this.debugEnvironmentVariables??[])}};var pt=class{constructor(e,n){this.writeFn=e;this.onError=n}pendingData="";drainScheduled=!1;writeQueue=Promise.resolve();_writeCount=0;append(e){try{this.pendingData+=e}catch(n){this.onError?.(n);return}this.drainScheduled||(this.drainScheduled=!0,this.writeQueue=this.writeQueue.then(()=>this.drain()))}enqueue(e){this.writeQueue=this.writeQueue.then(async()=>{try{await e()}catch(n){this.onError?.(n)}})}async flush(){await this.writeQueue}reset(){this.pendingData="",this.drainScheduled=!1,this._writeCount=0}get stats(){return{writeCount:this._writeCount,pendingLength:this.pendingData.length,drainScheduled:this.drainScheduled}}async drain(){for(;this.pendingData.length>0;){let e=this.pendingData;this.pendingData="";try{await this.writeFn(e),this._writeCount++}catch(n){if(this.onError?.(n),this.pendingData.length>0)continue;break}}this.drainScheduled=!1}};var ft=class extends lt{constructor(n,r,i){super(r,i);this.filePath=n;this.queue=new pt(s=>Xo(this.filePath,s)),this.queue.enqueue(()=>na(ta(this.filePath)))}queue;get writeQueue(){return this.queue.flush()}outputPath(){return this.filePath}log(n){this.write("LOG",n)}debug(n){super.shouldLog(4)&&this.write("DEBUG",this.filterSecrets(n).toString())}info(n){super.shouldLog(3)&&this.write("INFO",this.filterSecrets(n).toString())}notice(n){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(n).toString())}warning(n){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(n).toString())}error(n){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(n).toString())}startGroup(n,r){super.shouldLog(r||3)&&this.write("START-GROUP",n)}endGroup(n){super.shouldLog(n||3)&&this.write("END-GROUP","")}get stats(){return this.queue.stats}write(n,r){let s=`${new Date().toISOString()} [${n}] ${r}
`;this.queue.append(s)}writeLog(n,r){switch(n){case"debug":this.debug(r);break;case"info":this.info(r);break;case"warning":this.warning(r);break;case"error":this.error(r);break;default:{let i=n;break}}return this.writeQueue}};async function na(t){try{await Qo(t,Zo.F_OK)}catch{await ea(t,{recursive:!0})}}var ts=nt(xt(),1);var es=["setEnabled","selectModel","downloadModel","cancelDownload","deleteModel","installRuntime","refreshCatalog","openSession","finishSession","acknowledgeOperationError"];function Va(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{},type:`rpc:${t}`,connectionId:n,requestId:r}}var Ft=class{connectionId;connection;submit;pending=new Map;closeHandlers=new Set;closeDisposable;disposeDisposable;nextRequestId=1;attached=!1;disposed=!1;constructor(e){this.connection=e.connection,this.connectionId=e.connectionId,this.submit=e.submit;for(let n of es)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 ts.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,s)=>{this.pending.set(r,{resolve:i,reject:s});try{this.submit(Va(e,n,this.connectionId,r))}catch(a){this.pending.delete(r),s(a)}})}handleClose(){this.disposed||this.dispose()}rejectAllPending(e){if(this.pending.size===0)return;let n=[...this.pending.values()];this.pending.clear();for(let r of n)r.reject(e)}};var Dt=class{peers=new Map;connectedHandlers=new Set;disconnectedHandlers=new Set;submit=null;nextAutoConnectionId=1;disposed=!1;setSubmit(e){this.submit=e}registerConnection(e){if(this.disposed)throw new Error("EngineRpcHost is disposed.");if(!this.submit)throw new Error("EngineRpcHost.registerConnection called before setSubmit.");let n=e.connectionId??this.generateConnectionId();if(this.peers.has(n))throw new Error(`EngineRpcHost: connection id "${n}" already registered.`);let r=new Ft({connection:e.connection,connectionId:n,submit:this.submit});this.peers.set(n,r),r.onClose(()=>{if(this.peers.get(n)===r){this.peers.delete(n);for(let i of this.disconnectedHandlers)i(n)}});try{r.attach();for(let i of this.connectedHandlers)i(n)}catch(i){this.peers.delete(n);try{r.dispose()}catch{}throw i}return r}get connectionCount(){return this.peers.size}dispose(){if(this.disposed)return;this.disposed=!0;let e=[...this.peers.values()];for(let n of e)try{n.dispose()}catch{}}broadcast(e){if(!this.disposed)for(let n of this.peers.values())n.send(e)}sendTo(e,n){this.disposed||this.peers.get(e)?.send(n)}resolveRpc(e,n,r){this.disposed||this.peers.get(e)?.resolveRpc(n,r)}rejectRpc(e,n,r){this.disposed||this.peers.get(e)?.rejectRpc(n,r)}onClientConnected(e){return this.connectedHandlers.add(e),()=>{this.connectedHandlers.delete(e)}}onClientDisconnected(e){return this.disconnectedHandlers.add(e),()=>{this.disconnectedHandlers.delete(e)}}generateConnectionId(){return`c${this.nextAutoConnectionId++}`}};function Ua(t){if(t.includes("<!DOCTYPE")||t.includes("<html")){let e=Math.min(t.indexOf("<!DOCTYPE")!==-1?t.indexOf("<!DOCTYPE"):1/0,t.indexOf("<html")!==-1?t.indexOf("<html"):1/0),n=t.substring(0,e).trim();return n?`${n} [HTML error page omitted]`:"[HTML error page omitted]"}return t}function b(t){let e;if(t instanceof Error)e=String(t);else if(typeof t=="object"&&t!==null)try{e=JSON.stringify(t)??"[object]"}catch{return"[object with circular reference]"}else e=String(t);return Ua(e)}var Ve=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="VoiceBackendError"}};function mr(t){return t.code!==void 0?new Ve(t.message,t.code):new Error(t.message)}function Vt(t){return t instanceof Error?t:new Error(String(t))}async function ns(t,e){try{return await t()}catch(n){if((e?.platform??process.platform)!=="win32")throw n;let i=b(n);if(!/Failed to load (?:dependency|core) library/i.test(i))throw n;let a=(e?.arch??process.arch)==="arm64"?"https://aka.ms/vs/17/release/vc_redist.arm64.exe":"https://aka.ms/vs/17/release/vc_redist.x64.exe";throw new Ve(`Voice mode requires the Microsoft Visual C++ Redistributable (2015-2022). Download and install it, then try again: ${a}`,"windows-runtime-missing",{cause:n})}}var vr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};function Qe(t,e,n){let r,i=new Promise((s,a)=>{r=setTimeout(()=>a(new vr(n)),e)});return Promise.race([t,i]).finally(()=>{r&&clearTimeout(r)})}var rs="nemotron-speech-streaming-en-0.6b",is=new Set([rs,"nemotron-speech-streaming-es-0.6b"]);function ss(t){return t.find(e=>e.inCatalog&&e.alias===rs)}var ja="github-copilot-cli",$a="automatic-speech-recognition",qa={AzureCatalogFilter:"'',test"},os=1e4,as=2e3,Ut=class{events;installer;managerFactory;liveSessionFactory;nativeLocation;managerPromise;downloads=new Map;loaded=null;sessions=new Map;outstandingTeardowns=new Set;disposed=!1;constructor(e){this.events=e.events,this.installer=e.installer,this.managerFactory=e.managerFactory,this.liveSessionFactory=e.liveSessionFactory}checkRuntime(e){this.runCheckRuntime(e)}async runCheckRuntime(e){try{if(this.managerFactory){this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"});return}let n=await this.installer.inspect();n.kind==="downloaded"?(this.nativeLocation=n.location,this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"})):n.kind==="update-available"?this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"update-available"}):this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"not-downloaded"})}catch(n){h.error(`[voice-engine] checkRuntime failed: ${b(n)}`),this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"not-downloaded"})}}fetchCatalog(e){this.runFetchCatalog(e)}async runFetchCatalog(e){try{let r=await(await this.getManager()).catalog.getModels(),i=[];for(let s of r)for(let a of s.variants)Ha(a)&&is.has(a.alias)&&i.push(Ba(a));this.events.submit({type:"internal:catalogFetched",generation:e,models:i})}catch(n){let r=b(n);h.error(`[voice-engine] fetchCatalog failed: ${r}`),this.events.submit({type:"internal:catalogFetchFailed",generation:e,reason:r})}}installRuntime(e){this.runInstallRuntime(e)}async runInstallRuntime(e){try{let n=await this.installer.install();this.nativeLocation=n,this.events.submit({type:"internal:runtimeInstalled",generation:e})}catch(n){let r=b(n);h.error(`[voice-engine] installRuntime failed: ${r}`),this.events.submit({type:"internal:runtimeInstallFailed",generation:e,reason:r})}}downloadModel(e,n){let r=this.downloads.get(e);if(r&&!r.abortController.signal.aborted){r.generations.add(n);return}let i=new Set([n]),s=new AbortController,a={promise:Promise.resolve(),generations:i,abortController:s};a.promise=this.runDownload(e,i,s.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(s=>{for(let a of n)try{this.events.submit({type:"internal:modelDownloadProgress",generation:a,variantId:e,percent:s})}catch(u){h.warning(`[voice-engine] download progress callback threw: ${b(u)}`)}},r);for(let s of n)this.events.submit({type:"internal:modelDownloaded",generation:s,variantId:e})}catch(i){if(r.aborted)for(let s of n)this.events.submit({type:"internal:modelDownloadCancelled",generation:s,variantId:e});else{let s=b(i);h.error(`[voice-engine] downloadModel '${e}' failed: ${s}`);for(let a of n)this.events.submit({type:"internal:modelDownloadFailed",generation:a,variantId:e,reason:s})}}finally{this.downloads.get(e)?.abortController.signal===r&&this.downloads.delete(e)}}loadModel(e,n){this.runLoad(e,n)}async runLoad(e,n){try{let r=await this.getVariant(e);if(!r.isCached)throw new Error(`Voice model '${e}' is not downloaded.`);await r.load(),this.loaded&&this.loaded.variantId!==e&&h.warning(`[voice-engine] loadModel: replacing loaded model '${this.loaded.variantId}' with '${e}' (reducer should have unloaded first)`),this.loaded={variantId:e,variant:r},this.events.submit({type:"internal:modelLoaded",generation:n,variantId:e})}catch(r){let i=b(r);h.error(`[voice-engine] loadModel '${e}' failed: ${i}`),this.events.submit({type:"internal:modelLoadFailed",generation:n,variantId:e,reason:i})}}unloadModel(e){this.runUnload(e)}async runUnload(e){let n=this.loaded&&this.loaded.variantId===e?this.loaded:null;if(n&&(this.loaded=null),!n){this.events.submit({type:"internal:modelUnloaded",variantId:e});return}try{await n.variant.unload(),this.events.submit({type:"internal:modelUnloaded",variantId:e})}catch(r){let i=b(r);h.error(`[voice-engine] unloadModel '${e}' failed: ${i}`),this.events.submit({type:"internal:modelUnloadFailed",variantId:e,reason:i}),this.events.submit({type:"internal:modelUnloaded",variantId:e})}}deleteModel(e){this.runDelete(e)}async openSttSession(e,n){if(this.disposed)return{ok:!1,subreason:"session-open-failed"};if(this.sessions.has(e))return h.warning(`[voice-engine] openSttSession(${e}): sessionId already in use`),{ok:!1,subreason:"session-open-failed"};let r=this.loaded&&this.loaded.variantId===n?this.loaded:void 0;if(!r)return{ok:!1,subreason:"model-unavailable"};let i={phase:"opening",cancelled:!1};this.sessions.set(e,i);let s=this.runOpenSession(e,r,i);return this.trackTeardown(s.then(()=>{}).catch(()=>{})),s}async runOpenSession(e,n,r){let i;try{i=await this.openStreamingSession(e,n.variant)}catch(a){return h.error(`[voice-engine] openSttSession(${e}) failed: ${b(a)}`),this.sessions.get(e)===r&&this.sessions.delete(e),{ok:!1,subreason:r.cancelled?"cancelled":"session-open-failed"}}let s=this.sessions.get(e);return s!==r||r.cancelled?(s===r&&this.sessions.delete(e),this.trackTeardown(this.teardownSession(i).catch(a=>h.warning(`[voice-engine] orphan teardown(${e}) failed: ${b(a)}`))),{ok:!1,subreason:"cancelled"}):(this.sessions.set(e,{phase:"active",session:i}),i.drainTask=this.runStreamingDrain(i),{ok:!0})}appendSttPcm(e,n){if(this.disposed)return;let r=this.sessions.get(e);if(!r||r.phase!=="active")return;let i=r.session;if(!i.error)try{let s=i.sdk.append(n);s instanceof Promise&&s.catch(a=>this.failSession(i,"drain-failed",a))}catch(s){this.failSession(i,"drain-failed",s)}}endSttSession(e){if(this.disposed)return;let n=this.sessions.get(e);if(!n)return;if(n.phase==="opening"){n.cancelled=!0,this.sessions.delete(e);return}let r=n.session;this.sessions.delete(e),this.trackTeardown(this.runEnd(r))}async runEnd(e){let n=e.sessionId;try{if(e.error){this.events.submit({type:"internal:sttError",sessionId:n,subreason:"drain-failed"});return}let r;try{r=await this.stopStreaming(e)}catch(i){h.error(`[voice-engine] runEnd(${n}) failed: ${b(i)}`),this.events.submit({type:"internal:sttError",sessionId:n,subreason:"drain-failed"});return}if(e.error){this.events.submit({type:"internal:sttError",sessionId:n,subreason:"drain-failed"});return}this.events.submit({type:"internal:sttFinal",sessionId:n,text:r})}finally{await this.teardownSession(e).catch(r=>h.warning(`[voice-engine] teardown(${n}) failed: ${b(r)}`))}}cancelSttSession(e){if(this.disposed)return;let n=this.sessions.get(e);if(!n)return;if(n.phase==="opening"){n.cancelled=!0,this.sessions.delete(e);return}let r=n.session;r.cancelled=!0,this.sessions.delete(e),this.trackTeardown(this.runCancel(r))}async runCancel(e){try{await this.disposeSdk(e.sdk)}catch(n){h.warning(`[voice-engine] runCancel(${e.sessionId}) teardown: ${b(n)}`)}}trackTeardown(e){this.outstandingTeardowns.add(e),e.finally(()=>this.outstandingTeardowns.delete(e)).catch(()=>{})}failSession(e,n,r){if(e.error)return;let i=r instanceof Error?r:new Error(String(r));e.error=i,h.error(`[voice-engine] session(${e.sessionId}) failed: ${b(i)}`);let s=this.sessions.get(e.sessionId);!s||s.phase!=="active"||s.session!==e||(this.sessions.delete(e.sessionId),this.events.submit({type:"internal:sttError",sessionId:e.sessionId,subreason:n}),this.trackTeardown(this.teardownSession(e).catch(a=>h.warning(`[voice-engine] failSession teardown: ${b(a)}`))))}async openStreamingSession(e,n){let r=this.liveSessionFactory?await this.liveSessionFactory(n):n.createAudioClient().createLiveTranscriptionSession();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=Ga(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 Qe(e.sdk.stop(),os,"Streaming session stop timed out."),await Qe(e.drainTask,os,"Streaming session drain timed out."),e.committed+e.tail}async teardownSession(e){await this.disposeSdk(e.sdk)}async disposeSdk(e){await Qe(e.dispose(),as,"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 Qe(e.variant.unload(),as,"variant.unload timed out").catch(n=>{h.error(`[voice-engine] dispose: variant.unload failed: ${b(n)}`)})}}}async runDelete(e){try{(await this.getVariant(e)).removeFromCache()}catch(n){h.error(`[voice-engine] deleteModel '${e}' failed: ${b(n)}`)}}async getVariant(e){return(await this.getManager()).catalog.getModelVariant(e)}getManager(){return this.managerPromise||(this.managerPromise=this.initManager().catch(e=>{throw this.managerPromise=void 0,e})),this.managerPromise}async initManager(){if(this.managerFactory)return this.managerFactory();if(!this.nativeLocation)throw new Error("LocalFoundryEngineAdapter: manager-backed operation before checkRuntime/installRuntime");let e=this.nativeLocation;return ns(async()=>oe("foundry-local-sdk").FoundryLocalManager.createAsync({appName:ja,libraryPath:e.corePath,additionalSettings:{...qa}}))}};function Ha(t){return t.info.task===$a}function Ga(t){return t.content?.[0]?.text??""}function Ba(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 Wa=1600,za=15,cs=-1,ds=150,jt=class{events;pvRecorderLoader;state={tag:"idle"};disposed=!1;constructor(e){this.events=e.events,this.pvRecorderLoader=e.pvRecorderLoader??(async()=>oe("@picovoice/pvrecorder-node"))}openForSession(e){if(this.disposed)return Promise.resolve({ok:!1,subreason:"cancelled"});let n=this.state;switch(n.tag){case"idle":return this.beginStart(e,void 0);case"stopping":return this.beginStart(e,n.teardown);case"starting":case"active":return h.error(`[voice-mic] openForSession(${e}) while ${n.tag} for session ${n.sessionId} \u2014 engine contract violation`),Promise.resolve({ok:!1,subreason:"in-use"});default:return n}}beginStart(e,n){let r,i=new Promise(u=>{r=u}),s={stopped:!1,commitDrain:!1,resolveOpen:r},a=(async()=>{n&&await n.catch(()=>{}),await this.runStart(e,cs,s)})();return this.state={tag:"starting",sessionId:e,deviceId:cs,cancel:s,startTask:a},i}closeSession(e){let n=this.state;switch(n.tag){case"idle":case"stopping":return n.tag==="stopping"?n.teardown:Promise.resolve();case"starting":{n.cancel.stopped=!0,n.cancel.resolveOpen({ok:!1,subreason:"cancelled"});let r=n.startTask.then(()=>{},()=>{});return this.state={tag:"stopping",teardown:r},r.then(()=>{this.state.tag==="stopping"&&this.state.teardown===r&&(this.state={tag:"idle"})},()=>{}),r}case"active":{let r=n.cancel,i=n.recorder,s=n.loop;e==="discard"?(r.stopped=!0,ee(()=>i.stop())):r.commitDrain=!0;let a=(async()=>{e==="commit"&&(await Promise.race([s,ls(ds)]).catch(()=>{}),r.stopped=!0,ee(()=>i.stop())),await Promise.race([s,ls(ds)]).catch(()=>{}),ee(()=>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,ee(()=>e.recorder.stop()),await e.loop.catch(()=>{}),ee(()=>e.recorder.release()),this.state={tag:"idle"};return}case"stopping":{await e.teardown.catch(()=>{}),this.state={tag:"idle"};return}default:return e}}async runStart(e,n,r){if(r.stopped||this.disposed){this.exitCancelled(r);return}let i;try{i=await this.pvRecorderLoader()}catch(u){h.error(`[voice-mic] pvrecorder-node load failed: ${b(u)}`),this.failOpen(r,"hardware-error");return}if(r.stopped||this.disposed){this.exitCancelled(r);return}let s;try{s=new i.PvRecorder(Wa,n,za),s.start()}catch(u){if(s!==void 0){let l=s;ee(()=>l.stop()),ee(()=>l.release())}this.failOpen(r,us(u));return}if(r.stopped||this.disposed){ee(()=>s.stop()),ee(()=>s.release()),this.exitCancelled(r);return}let a=this.runReadLoop(s,e,r);this.state={tag:"active",sessionId:e,deviceId:n,cancel:r,recorder:s,loop:a},r.resolveOpen({ok:!0})}failOpen(e,n){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:n})}exitCancelled(e){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:"cancelled"})}async runReadLoop(e,n,r){for(;!r.stopped;){let i;try{i=await e.read()}catch(a){if(r.stopped||r.commitDrain)return;r.stopped=!0,this.state.tag==="active"&&this.state.cancel===r&&(this.state={tag:"idle"}),ee(()=>e.stop()),ee(()=>e.release());let u=us(a);h.error(`[voice-mic] read loop failed (${u}): ${b(a)}`),this.disposed||this.events.submit({type:"internal:micError",sessionId:n,subreason:u});return}if(r.stopped)return;let s=new Uint8Array(i.byteLength);if(s.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),this.events.onPcmFrame(n,s),r.commitDrain)return}}};function us(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 ls(t){return new Promise(e=>setTimeout(e,t))}function ee(t){try{t()}catch{}}function Ka(t){return{state:t.state,enabled:t.enabled,selectedTarget:t.selectedTarget,models:t.models.map(e=>({...e})),catalogStatus:t.catalogStatus,inFlightDownloads:t.inFlightDownloads.map(e=>({...e})),session:t.session?{...t.session}:null,lastOperationError:t.lastOperationError?{...t.lastOperationError}:null}}function Ja(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 $t(t,e){t.enabled=e.clientEnabled}function Ue(t,e){return t.models.find(n=>n.variantId===e)}function ps(t,e){let n=Ue(t,e);return!!n&&(n.inCatalog||n.cached)}function fs(t,e){let n=Ue(t,e);return!!n&&n.cached}function yr(t){return t.currentSession!==null}function Ya(t,e){t.session=e.currentSession?{id:e.currentSession.id,status:e.currentSession.status}:null}function Er(t,e){let r=(t.generations.downloadByVariant.get(e)??0)+1;return t.generations.downloadByVariant.set(e,r),r}function qt(t,e){return t.generations.downloadByVariant.get(e)??0}function Za(t,e,n){t.pendingFinishReply&&(n.push({type:"replyResolve",connectionId:t.pendingFinishReply.connectionId,requestId:t.pendingFinishReply.requestId,result:e}),t.pendingFinishReply=void 0)}function te(t,e,n,r){let i=e.currentSession;i&&(r.push({type:"cancelSession",sessionId:i.id}),Za(i,n,r),e.currentSession=null,t.session=null)}function Qa(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 l=ss(t.models);l?.cached&&(t.selectedTarget=l.variantId)}let i=t.selectedTarget,s=t.enabled&&i!==null&&ps(t,i)?i:null,a=e.modelLoad;if(a.kind==="loading"||a.kind==="unloading")return;if(s===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===s){(t.state.kind!=="ready"||t.state.variantId!==s)&&(t.state={kind:"ready",variantId:s});return}n.push({type:"unloadModel",variantId:a.variantId}),e.modelLoad={kind:"unloading",variantId:a.variantId};return}if(fs(t,s)){let l=++e.nextLoadGeneration;e.modelLoad={kind:"loading",variantId:s,generation:l},t.state={kind:"loading",variantId:s},n.push({type:"loadModel",variantId:s,generation:l});return}if((t.state.kind!=="downloading"||t.state.variantId!==s)&&(t.state={kind:"downloading",variantId:s}),!t.inFlightDownloads.some(l=>l.variantId===s)){let l=Er(e,s);t.inFlightDownloads.push({variantId:s}),n.push({type:"downloadModel",variantId:s,generation:l})}}function gs(t){return t.kind==="starting"||t.kind==="runtime-missing"||t.kind==="installing-runtime"||t.kind==="fetching-catalog"||t.kind==="failed"}function hs(t,e,n){let r=Ka(t),i=Ja(e),a=Xa(r,i,n,[]);return Qa(a.snapshot,a.internal,a.effects),Ya(a.snapshot,a.internal),a}function Xa(t,e,n,r){switch(n.type){case"boot":return ec(t,e,n,r);case"shutdown":return tc(t,e,r);case"rpc:setEnabled":return nc(t,e,n,r);case"rpc:selectModel":return rc(t,e,n,r);case"rpc:downloadModel":return ic(t,e,n,r);case"rpc:cancelDownload":return sc(t,e,n,r);case"rpc:deleteModel":return oc(t,e,n,r);case"rpc:installRuntime":return ac(t,e,n,r);case"rpc:refreshCatalog":return cc(t,e,n,r);case"rpc:openSession":return dc(t,e,n,r);case"rpc:finishSession":return uc(t,e,n,r);case"rpc:acknowledgeOperationError":return lc(t,e,n,r);case"internal:catalogFetched":return pc(t,e,n,r);case"internal:catalogFetchFailed":return fc(t,e,n,r);case"internal:runtimeChecked":return gc(t,e,n,r);case"internal:runtimeInstalled":return hc(t,e,n,r);case"internal:runtimeInstallFailed":return mc(t,e,n,r);case"internal:modelDownloadProgress":return vc(t,e,n,r);case"internal:modelDownloaded":return yc(t,e,n,r);case"internal:modelDownloadCancelled":return Ec(t,e,n,r);case"internal:modelDownloadFailed":return bc(t,e,n,r);case"internal:modelLoaded":return Sc(t,e,n,r);case"internal:modelLoadFailed":return _c(t,e,n,r);case"internal:modelUnloaded":return Ic(t,e,n,r);case"internal:modelUnloadFailed":return wc(t,e,n,r);case"internal:micError":return Oc(t,e,n,r);case"internal:sessionWarmed":return Rc(t,e,n,r);case"internal:sessionWarmupFailed":return Tc(t,e,n,r);case"internal:sttFinal":return Cc(t,e,n,r);case"internal:sttError":return kc(t,e,n,r);case"client:disconnected":return Ac(t,e,n,r)}}function f(t,e,n){return{snapshot:t,internal:e,effects:n}}function ec(t,e,n,r){e.clientEnabled=n.bootEnabled,$t(t,e),t.selectedTarget=n.bootSelectedModel,t.state={kind:"starting"};let i=++e.generations.runtimeCheck;return r.push({type:"checkRuntime",generation:i}),f(t,e,r)}function tc(t,e,n){te(t,e,{kind:"lost",reason:"engine-disabled"},n);for(let r of t.inFlightDownloads)Er(e,r.variantId);return t.inFlightDownloads=[],e.generations.runtimeInstall++,e.generations.runtimeCheck++,e.generations.catalogFetch++,t.state={kind:"failed",reason:"shutdown"},f(t,e,n)}function nc(t,e,n,r){let i=e.clientEnabled;e.clientEnabled=n.enabled,$t(t,e);let s=t.enabled;return i&&!s&&(te(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&&s&&t.state.kind==="model-failed"&&(t.state={kind:"no-model"},t.lastOperationError=null),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)}function rc(t,e,n,r){return gs(t.state)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),f(t,e,r)):yr(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),f(t,e,r)):ps(t,n.variantId)?(e.clientEnabled=!0,$t(t,e),t.state.kind==="model-failed"&&(t.state={kind:"no-model"}),n.variantId===t.selectedTarget&&t.enabled?(r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)):(t.selectedTarget=n.variantId,t.lastOperationError=null,t.state.kind==="downloading"&&t.state.variantId!==n.variantId&&(t.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r))):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-not-found",variantId:n.variantId}}),f(t,e,r))}function ic(t,e,n,r){if(gs(t.state))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),f(t,e,r);if(!Ue(t,n.variantId))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-not-found",variantId:n.variantId}}),f(t,e,r);if(fs(t,n.variantId))return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r);if(!t.inFlightDownloads.some(s=>s.variantId===n.variantId)){let s=Er(e,n.variantId);t.inFlightDownloads.push({variantId:n.variantId}),r.push({type:"downloadModel",variantId:n.variantId,generation:s})}return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)}function sc(t,e,n,r){return t.inFlightDownloads.some(s=>s.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(s=>s.variantId!==n.variantId),t.selectedTarget===n.variantId&&(t.selectedTarget=null,t.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)}function oc(t,e,n,r){if(t.inFlightDownloads.some(w=>w.variantId===n.variantId))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-in-use"}}),f(t,e,r);if(n.variantId===t.selectedTarget&&yr(e))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),f(t,e,r);let s=e.modelLoad;if((s.kind==="loading"||s.kind==="unloading")&&s.variantId===n.variantId)return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-in-use"}}),f(t,e,r);let a=Ue(t,n.variantId),u=s.kind==="loaded"&&s.variantId===n.variantId,l=n.variantId===t.selectedTarget,v=t.state.kind==="model-failed"&&t.state.variantId===n.variantId;return u?e.pendingDelete={variantId:n.variantId}:(r.push({type:"deleteModel",variantId:n.variantId}),a&&(a.cached=!1)),(l||v)&&(t.selectedTarget=null,e.clientEnabled=!1,$t(t,e),(t.state.kind==="downloading"||t.state.kind==="loading"||t.state.kind==="ready"||t.state.kind==="model-failed")&&(t.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)}function ac(t,e,n,r){if(t.state.kind!=="runtime-missing")return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"invalid-state"}}),f(t,e,r);let i=++e.generations.runtimeInstall;return t.state={kind:"installing-runtime",cacheState:t.state.cacheState},r.push({type:"installRuntime",generation:i}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)}function 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 s=++e.generations.catalogFetch;t.catalogStatus="fetching",r.push({type:"fetchCatalog",generation:s})}return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)}function dc(t,e,n,r){return t.enabled?yr(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),f(t,e,r)):t.selectedTarget?t.state.kind!=="ready"?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),f(t,e,r)):(e.currentSession={id:n.sessionId,ownerConnectionId:n.connectionId,status:"opening"},r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),r.push({type:"warmupSession",sessionId:n.sessionId,variantId:t.selectedTarget}),f(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"invalid-state"}}),f(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"engine-disabled"}}),f(t,e,r))}function uc(t,e,n,r){let i=e.currentSession;if(!(i!==null&&i.id===n.sessionId&&i.ownerConnectionId===n.connectionId)){let a=n.commit?{kind:"lost",reason:"unknown-session"}:{kind:"discarded"};return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:a}),f(t,e,r)}return n.commit?i!==null&&i.status==="opening"?(te(t,e,{kind:"lost",reason:"not-ready"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"lost",reason:"not-ready"}}),f(t,e,r)):i!==null&&i.pendingFinishReply?(r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"lost",reason:"not-ready"}}),f(t,e,r)):(i!==null&&(i.pendingFinishReply={connectionId:n.connectionId,requestId:n.requestId}),r.push({type:"commitSession",sessionId:n.sessionId}),f(t,e,r)):(te(t,e,{kind:"discarded"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"discarded"}}),f(t,e,r))}function lc(t,e,n,r){return t.lastOperationError=null,t.state.kind==="model-failed"&&(t.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(t,e,r)}function pc(t,e,n,r){return n.generation!==e.generations.catalogFetch||(t.models=n.models.map(i=>({...i})),t.catalogStatus="ok",(t.state.kind==="starting"||t.state.kind==="fetching-catalog")&&(t.state={kind:"no-model"})),f(t,e,r)}function fc(t,e,n,r){return n.generation!==e.generations.catalogFetch||(t.catalogStatus="failed",(t.state.kind==="starting"||t.state.kind==="fetching-catalog")&&(t.state={kind:"no-model"})),f(t,e,r)}function gc(t,e,n,r){if(n.generation!==e.generations.runtimeCheck||t.state.kind!=="starting")return f(t,e,r);if(n.cacheState!=="installed")return t.state={kind:"runtime-missing",cacheState:n.cacheState},f(t,e,r);t.state={kind:"fetching-catalog"},t.catalogStatus="fetching";let i=++e.generations.catalogFetch;return r.push({type:"fetchCatalog",generation:i}),f(t,e,r)}function hc(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return f(t,e,r);if(t.state.kind==="installing-runtime"){t.state={kind:"fetching-catalog"},t.catalogStatus="fetching";let i=++e.generations.catalogFetch;r.push({type:"fetchCatalog",generation:i})}return f(t,e,r)}function mc(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return f(t,e,r);t.state.kind==="installing-runtime"&&(t.state={kind:"runtime-missing",cacheState:t.state.cacheState});let i={operation:"installRuntime",reason:n.reason};t.lastOperationError=i;let s={type:"operationError",error:i};return r.push({type:"broadcast",event:s}),f(t,e,r)}function vc(t,e,n,r){if(n.generation!==qt(e,n.variantId))return f(t,e,r);let i={type:"modelDownloadProgress",variantId:n.variantId,percent:n.percent};return r.push({type:"broadcast",event:i}),f(t,e,r)}function yc(t,e,n,r){if(n.generation!==qt(e,n.variantId))return f(t,e,r);t.inFlightDownloads=t.inFlightDownloads.filter(s=>s.variantId!==n.variantId);let i=Ue(t,n.variantId);return i?i.cached=!0:t.models.push({variantId:n.variantId,displayName:n.variantId,cached:!0,inCatalog:!1}),f(t,e,r)}function Ec(t,e,n,r){return n.generation!==qt(e,n.variantId)||(t.inFlightDownloads=t.inFlightDownloads.filter(i=>i.variantId!==n.variantId),t.state.kind==="downloading"&&t.state.variantId===n.variantId&&(t.selectedTarget=null,t.state={kind:"no-model"})),f(t,e,r)}function bc(t,e,n,r){if(n.generation!==qt(e,n.variantId))return f(t,e,r);t.inFlightDownloads=t.inFlightDownloads.filter(a=>a.variantId!==n.variantId),t.state.kind==="downloading"&&t.state.variantId===n.variantId&&(t.selectedTarget=null,t.state={kind:"model-failed",variantId:n.variantId,reason:n.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelDownloadFailed (sessionId=${e.currentSession.id}, variantId=${n.variantId})`}),te(t,e,{kind:"lost",reason:"engine-disabled"},r)));let i={operation:"downloadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=i;let s={type:"operationError",error:i};return r.push({type:"broadcast",event:s}),f(t,e,r)}function Sc(t,e,n,r){let i=e.modelLoad;return i.kind!=="loading"||i.generation!==n.generation||i.variantId!==n.variantId?(r.push({type:"unloadModel",variantId:n.variantId}),f(t,e,r)):(e.modelLoad={kind:"loaded",variantId:n.variantId},t.enabled&&t.selectedTarget===n.variantId&&(t.state={kind:"ready",variantId:n.variantId},t.lastOperationError=null),f(t,e,r))}function _c(t,e,n,r){let i=e.modelLoad;if(i.kind!=="loading"||i.generation!==n.generation||i.variantId!==n.variantId)return f(t,e,r);e.modelLoad={kind:"unloaded"},t.selectedTarget=null,t.state={kind:"model-failed",variantId:n.variantId,reason:n.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelLoadFailed (sessionId=${e.currentSession.id}, variantId=${n.variantId})`}),te(t,e,{kind:"lost",reason:"engine-disabled"},r));let s={operation:"loadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=s;let a={type:"operationError",error:s};return r.push({type:"broadcast",event:a}),f(t,e,r)}function Ic(t,e,n,r){let i=e.modelLoad;if(i.kind!=="unloading"||i.variantId!==n.variantId)return f(t,e,r);if(e.modelLoad={kind:"unloaded"},e.pendingDelete&&e.pendingDelete.variantId===n.variantId){r.push({type:"deleteModel",variantId:n.variantId});let s=Ue(t,n.variantId);s&&(s.cached=!1),(t.state.kind==="ready"||t.state.kind==="loading"||t.state.kind==="downloading")&&t.state.variantId===n.variantId&&(t.state={kind:"no-model"}),e.pendingDelete=null}return f(t,e,r)}function wc(t,e,n,r){let i={operation:"loadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=i;let s={type:"operationError",error:i};return r.push({type:"broadcast",event:s}),f(t,e,r)}function Rc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||i.status==="opening"&&(i.status="active"),f(t,e,r)}function Tc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||(Pc(i.ownerConnectionId,n.sessionId,n.failure,r),te(t,e,{kind:"lost",reason:n.failure.side==="mic"?"mic-error":"stt-error"},r)),f(t,e,r)}function Pc(t,e,n,r){let i=n.side==="mic"?{type:"micError",sessionId:e,subreason:n.subreason}:{type:"sttError",sessionId:e,subreason:n.subreason};r.push({type:"sendTo",connectionId:t,event:i})}function Oc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return f(t,e,r);let s={type:"micError",sessionId:n.sessionId,subreason:n.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:s}),te(t,e,{kind:"lost",reason:"mic-error"},r),f(t,e,r)}function Cc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return f(t,e,r);let s=i.pendingFinishReply?{kind:"committed",text:n.text}:{kind:"discarded"};return te(t,e,s,r),f(t,e,r)}function kc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return f(t,e,r);let s={type:"sttError",sessionId:n.sessionId,subreason:n.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:s}),te(t,e,{kind:"lost",reason:"stt-error"},r),f(t,e,r)}function Ac(t,e,n,r){let i=e.currentSession;return i&&i.ownerConnectionId===n.connectionId&&te(t,e,{kind:"lost",reason:"engine-disabled"},r),f(t,e,r)}function ms(){return{state:{kind:"starting"},enabled:!1,selectedTarget:null,models:[],catalogStatus:"ok",inFlightDownloads:[],session:null,lastOperationError:null}}function vs(){return{generations:{runtimeInstall:0,runtimeCheck:0,downloadByVariant:new Map,catalogFetch:0},nextLoadGeneration:0,modelLoad:{kind:"unloaded"},currentSession:null,clientEnabled:!1,pendingDelete:null}}function ys(t={}){let e=t.attackMs??12,n=t.releaseMs??100,r=Math.max(1,Math.round(8/1e3*16e3)),i=0;return{feed(s){let a=s.byteLength/2|0;if(a!==0)for(let u=0;u<a;u+=r){let l=Math.min(a,u+r),v=0;for(let W=u;W<l;W++){let z=s[W*2],J=(s[W*2+1]<<8|z)<<16>>16,T=J<0?-J:J;T>v&&(v=T)}let w=v/32768,O=Math.min(1,Math.sqrt(w)),j=(l-u)/16e3*1e3,G=O>i?e:n,C=1-Math.exp(-j/Math.max(.001,G));i=i+(O-i)*C}},current(){return i},reset(){i=0}}}function Mc(t){throw new Error(`Unhandled EngineEffect type: ${t.type}`)}var Es=64,Ht=class{snapshot;internal;host;foundry;mic;unsubscribeConnected;unsubscribeDisconnected;disposed=!1;dispatchDepth=0;levelMeter;constructor(e){this.snapshot=ms(),this.internal=vs(),this.host=e.host,this.levelMeter=ys(),this.foundry=e.foundryFactory(this.buildFoundryEvents()),this.mic=e.micFactory(this.buildMicEvents()),this.submit({type:"boot",bootEnabled:e.bootSettings.voice?.enabled===!0,bootSelectedModel:e.bootSettings.voice?.selectedModel??null}),this.unsubscribeConnected=e.host.onClientConnected(n=>{e.host.sendTo(n,{type:"initialize",snapshot:this.snapshot})}),this.unsubscribeDisconnected=e.host.onClientDisconnected(n=>{this.submit({type:"client:disconnected",connectionId:n})})}buildFoundryEvents(){return{submit:e=>{this.submit(e)},onSttPartial:(e,n)=>{if(!this.disposed)try{let r=this.internal.currentSession;if(!r||r.id!==e||r.status!=="active"||r.pendingFinishReply)return;this.host.sendTo(r.ownerConnectionId,{type:"sessionPreview",sessionId:e,partialTranscript:n})}catch(r){h.error(`[VoiceEngine] onSttPartial threw: ${b(r)}`)}}}}buildMicEvents(){return{submit:e=>{this.submit(e)},onPcmFrame:(e,n)=>{if(!this.disposed)try{let r=this.internal.currentSession;if(!r||r.id!==e||r.status!=="active")return;this.levelMeter.feed(n),this.foundry.appendSttPcm(e,n),r.pendingFinishReply||this.emitEnvelope(r.id,r.ownerConnectionId)}catch(r){h.error(`[VoiceEngine] onPcmFrame threw: ${b(r)}`)}}}}submit(e){if(!this.disposed){if(this.dispatchDepth>=Es){h.error(`[VoiceEngine] dispatch depth exceeded ${Es} 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:s,effects:a}=hs(this.snapshot,this.internal,e);this.snapshot=i,this.internal=s;for(let l of a)try{this.dispatch(l)}catch(v){h.error(`[VoiceEngine] dispatching effect '${l.type}' threw: ${b(v)}`)}let u=this.snapshot.session?.status==="active"?this.snapshot.session.id:null;r===null&&u!==null&&this.levelMeter.reset(),n!==this.snapshot&&this.host.broadcast({type:"state",snapshot:this.snapshot})}finally{this.dispatchDepth--}}}getSnapshot(){return this.snapshot}async dispose(){if(this.disposed)return;this.disposed=!0,this.unsubscribeConnected(),this.unsubscribeDisconnected();let e=await Promise.allSettled([this.foundry.dispose(),this.mic.dispose()]);for(let n of e)n.status==="rejected"&&h.error(`[VoiceEngine] adapter dispose rejected: ${b(n.reason)}`)}emitEnvelope(e,n){try{this.host.sendTo(n,{type:"sessionAudio",sessionId:e,envelope:this.levelMeter.current()})}catch(r){h.error(`[VoiceEngine] emitEnvelope threw: ${b(r)}`)}}dispatch(e){switch(e.type){case"checkRuntime":this.foundry.checkRuntime(e.generation);break;case"fetchCatalog":this.foundry.fetchCatalog(e.generation);break;case"installRuntime":this.foundry.installRuntime(e.generation);break;case"downloadModel":this.foundry.downloadModel(e.variantId,e.generation);break;case"cancelDownload":this.foundry.cancelDownload(e.variantId);break;case"loadModel":this.foundry.loadModel(e.variantId,e.generation);break;case"unloadModel":this.foundry.unloadModel(e.variantId);break;case"deleteModel":this.foundry.deleteModel(e.variantId);break;case"warmupSession":{let{sessionId:n,variantId:r}=e,i;try{i=this.mic.openForSession(n)}catch(l){i=Promise.reject(l instanceof Error?l:new Error(String(l)))}let s=i.then(l=>(l.ok||this.foundry.cancelSttSession(n),l)),a;try{a=this.foundry.openSttSession(n,r)}catch(l){a=Promise.reject(l instanceof Error?l:new Error(String(l)))}let u=a.then(l=>(l.ok||this.mic.closeSession("discard").catch(()=>{}),l));Promise.all([s,u]).then(([l,v])=>{this.disposed||(l.ok&&v.ok?this.submit({type:"internal:sessionWarmed",sessionId:n}):l.ok?v.ok||this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"stt",subreason:v.subreason}}):this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"mic",subreason:l.subreason}}))},l=>{h.error(`[VoiceEngine] warmupSession(${n}) rejected: ${b(l)}`),!this.disposed&&this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"stt",subreason:"session-open-failed"}})});break}case"cancelSession":this.mic.closeSession("discard").catch(()=>{}),this.foundry.cancelSttSession(e.sessionId);break;case"commitSession":{let n=e.sessionId;this.mic.closeSession("commit").then(()=>{this.disposed||this.foundry.endSttSession(n)},r=>{h.error(`[VoiceEngine] commitSession(${n}) drain rejected: ${b(r)}`),!this.disposed&&this.foundry.endSttSession(n)});break}case"replyResolve":this.host.resolveRpc(e.connectionId,e.requestId,e.result);break;case"replyReject":this.host.rejectRpc(e.connectionId,e.requestId,e.reason);break;case"broadcast":this.host.broadcast(e.event);break;case"sendTo":this.host.sendTo(e.connectionId,e.event);break;case"logWarning":h.warning(`[VoiceEngine] ${e.message}`);break;default:Mc(e)}}};import{existsSync as br}from"node:fs";import{dirname as bs,join as Sr}from"node:path";import{fileURLToPath as Nc}from"node:url";function Ss(t){let{importMetaUrl:e,filename:n,label:r}=t,i;try{i=bs(Nc(e))}catch(v){throw new Error(`Voice ${r} worker bundle unavailable: cannot resolve module URL (${b(v)}).`)}let s=Sr(i,n);if(br(s))return s;let a=Lc(i),u=a?Sr(a,"dist-cli",n):void 0;if(u&&br(u))return u;let l=u?`${s}, ${u}`:s;throw new Error(`Voice ${r} worker bundle not found. Searched: ${l}`)}function Lc(t){let e=t;for(;;){if(br(Sr(e,"package.json")))return e;let n=bs(e);if(n===e)return;e=n}}function _s(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var _r=16*1024;function Ir(t,e,n=h){let r=xc(t.level)?t.level:"info",i=typeof t.message=="string"?t.message:_s(t.message);n[r](`[${e} worker] ${Fc(i)}`)}function xc(t){return t==="debug"||t==="info"||t==="warning"||t==="error"}function Fc(t){return t.length<=_r?t:`${t.slice(0,_r)}\u2026 [truncated, ${t.length-_r} more chars]`}import{Worker as Dc}from"node:worker_threads";var Is=(t,e)=>new Dc(t,e);import{createRequire as Uc}from"node:module";import*as ve from"node:fs/promises";import*as Q from"node:path";import{createHash as jc}from"node:crypto";import{join as Xe,basename as Rl}from"node:path";import{homedir as wr}from"node:os";function Vc(){return process.env.XDG_CACHE_HOME||Xe(wr(),".cache")}function ws(){if(process.platform==="darwin")return Xe(wr(),"Library","Caches","copilot");if(process.platform==="win32"){let t=process.env.LOCALAPPDATA||Xe(wr(),".cache");return Xe(t,"copilot")}return Xe(Vc(),"copilot")}var $c=1,qc=".complete";var Ps={"win32-x64":"win-x64","win32-arm64":"win-arm64","linux-x64":"linux-x64","darwin-arm64":"osx-arm64"};function Hc(){return typeof __foundryRequire<"u"&&__foundryRequire||Uc(import.meta.url)}var Gt;function Gc(){if(Gt)return Gt;try{let t=Hc()("foundry-local-sdk/deps_versions.json");if(typeof t["foundry-local-core"]?.nuget!="string"||typeof t.onnxruntime?.version!="string"||typeof t["onnxruntime-genai"]?.version!="string")throw new Error('deps_versions.json is missing one of the expected version keys: ["foundry-local-core"].nuget, .onnxruntime.version, ["onnxruntime-genai"].version');return Gt=t,Gt}catch(t){throw new Error(`Failed to load foundry-local-sdk/deps_versions.json: ${b(t)}. The upstream foundry-local-sdk installer may have changed shape \u2014 re-run the audit checklist in src/cli/voice/foundry/installer/nativeLoader.ts and update accordingly.`)}}function Bc(t=process.platform){let e=Gc();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 Os(t){return t==="win32"?".dll":t==="darwin"?".dylib":".so"}function Wc(t,e){return Q.join(t,`Microsoft.AI.Foundry.Local.Core${Os(e)}`)}function zc(t){let e=Os(t),n=t==="win32"?"":"lib";return[`Microsoft.AI.Foundry.Local.Core${e}`,`${n}onnxruntime${e}`,`${n}onnxruntime-genai${e}`]}function Kc(t,e=process.platform,n=process.arch){let r=Ps[`${e}-${n}`];if(!r)throw new Error(`Voice mode not supported on ${e}-${n}`);let i=t??process.env.COPILOT_CACHE_HOME??ws(),s=Bc(e),a=jc("sha256").update(JSON.stringify({schema:$c,artifacts:s})).digest("hex").slice(0,12);return Q.join(i,"foundry",a,r)}async function Cs(t={}){let e=t.platform??process.platform,n=t.arch??process.arch,r=`${e}-${n}`,i=Ps[r];if(!i)return{kind:"unsupported-platform",platformKey:r};let s=Kc(t.cacheRoot,e,n),a=zc(e);if(await Rs(s,a))return{kind:"downloaded",location:{corePath:Wc(s,e)}};let u=Q.dirname(Q.dirname(s)),l;try{l=await ve.readdir(u)}catch{return{kind:"not-downloaded"}}let v=Q.basename(Q.dirname(s));for(let w of l){if(w===v)continue;let O=Q.join(u,w,i);if(await Rs(O,a))return{kind:"update-available"}}return{kind:"not-downloaded"}}async function Rs(t,e){return await Ts(Q.join(t,qc))?(await Promise.all(e.map(r=>Ts(Q.join(t,r))))).every(Boolean):!1}async function Ts(t){try{return await ve.access(t),!0}catch{return!1}}var ks=5e3;function As(t={}){let{cacheRoot:e,workerFactory:n=Is,workerScriptPath:r,inspectImpl:i=Cs}=t,s,a;return{async inspect(){if(a&&Date.now()<a.expiry)return a.result;let u=await i({cacheRoot:e});return a={result:u,expiry:Date.now()+ks},u},install(u){if(s)return s;a=void 0;let l=Jc({cacheRoot:e,workerFactory:n,workerScriptPath:r??Ss({importMetaUrl:import.meta.url,filename:"voice-installer.worker.js",label:"installer"}),onProgress:u}).then(v=>(a={result:{kind:"downloaded",location:v},expiry:Date.now()+ks},v)).catch(v=>{throw s=void 0,a=void 0,v});return s=l,l}}}function Jc(t){return new Promise((e,n)=>{let r;try{r=t.workerFactory(t.workerScriptPath,{workerData:{cacheRoot:t.cacheRoot}})}catch(a){n(Vt(a));return}let i=!1,s=a=>{i||(i=!0,r.terminate().catch(u=>{h.warning(`[voice-runtime] installer worker terminate failed: ${b(u)}`)}),a())};r.on("message",a=>{if(a==null||typeof a!="object"){h.warning("[voice-runtime] installer worker posted a malformed message; ignoring");return}let u=a;if(u.kind==="log"){Ir(u,"Installer");return}if(u.kind==="download-started"){if(!t.onProgress)return;try{t.onProgress({kind:"indeterminate"})}catch(l){h.warning(`[voice-runtime] installer onProgress threw: ${b(l)}`)}return}if(u.kind==="ok"){s(()=>e(u.location));return}if(u.kind==="error"){s(()=>n(mr(u.error)));return}}),r.on("error",a=>{s(()=>n(Vt(a)))}),r.on("exit",a=>{s(()=>n(new Error(`Voice installer worker exited unexpectedly with code ${a}.`)))})})}import{readFileSync as Yc,unlinkSync as Zc,writeFileSync as Qc}from"node:fs";function Ms(t,e){Qc(t,`${e}
`,{encoding:"utf8"})}function Ns(t){let e;try{e=Yc(t,"utf8")}catch{return null}let n=Number(e.trim());return!Number.isSafeInteger(n)||n<=0?null:n}function Ls(t){try{Zc(t)}catch{}}var zt=nt(xt(),1);import{unlinkSync as Xc}from"node:fs";import{createConnection as ed,createServer as td}from"node:net";var xs=nt(xt(),1),Bt=class extends xs.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"),s=Buffer.concat([i,r],i.byteLength+r.byteLength);return this.socket.write(s),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 Wt=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 nd(this.address,n=>this.handleSocket(n));return e===null?"lost":(this.server=e,"bound")}async stop(){if(this.stopped)return;this.stopped=!0,h.info(`voice server: server stopping (clients=${this.host.connectionCount})`);let e=this.server;this.server=null,e&&await new Promise(n=>{e.close(()=>n())})}handleSocket(e){if(this.stopped){e.destroy();return}let n=(0,zt.createMessageConnection)(new zt.SocketMessageReader(e),new Bt(e));try{let r=this.host.registerConnection({connection:n});h.info(`voice server: client connected id=${r.connectionId} (clients=${this.host.connectionCount})`)}catch(r){h.error(`voice server: registerConnection failed: ${r.message}`);try{n.dispose()}catch{}e.destroy()}}};function nd(t,e){return new Promise((n,r)=>{let i=s=>{let a=td(e),u=l=>{if(a.removeAllListeners(),l.code==="EADDRINUSE"&&s&&process.platform!=="win32"){let v=ed(t);v.once("connect",()=>{v.destroy(),n(null)}),v.once("error",w=>{let O=w.code;if(O==="ECONNREFUSED"||O==="ENOENT"){try{Xc(t)}catch{}i(!1)}else n(null)});return}if(l.code==="EADDRINUSE"||l.code==="EEXIST"){n(null);return}r(l)};a.once("error",u),a.listen(t,()=>{a.removeListener("error",u),n(a)})};i(!0)})}import{createHash as ad}from"node:crypto";import{mkdirSync as Ds}from"node:fs";import{homedir as Vs,tmpdir as cd}from"node:os";import{join as je}from"node:path";import{readFileSync as rd}from"fs";import{dirname as id,join as Rr}from"path";import{fileURLToPath as sd}from"url";var et=null;function Fs(){return od().version}function od(){if(et!==null)return et;try{let t=sd(import.meta.url),e=id(t),n=[Rr(e,"package.json"),Rr(e,"../package.json"),Rr(e,"../../package.json")];for(let i of n)try{let s=JSON.parse(rd(i,"utf8")),a={name:s.name||"unknown",version:s.version||"unknown",buildMetadata:s.buildMetadata};return et=a,a}catch{continue}let r={name:"unknown",version:"unknown"};return et=r,r}catch{let e={name:"unknown",version:"unknown"};return et=e,e}}var dd=8,Kt="copilot-voice",ud=100;function Us(t={}){let e=t.platform??process.platform,n=t.env??process.env,r=t.tmpDir??cd(),i=t.cliVersion??Fs();if(e==="win32"){let w=Jt(n.USERPROFILE??n.HOMEPATH??n.USERNAME??t.homeDir??Vs()??"anon"),O=Jt(`${i}|${w}`),j=`\\\\.\\pipe\\${Kt}-${O}`,G=je(r,Kt);return Ds(G,{recursive:!0}),{address:j,pidFile:je(G,`${O}.pid`),endpointHash:O}}let s=Jt(i),a=n.XDG_RUNTIME_DIR,u=Jt(n.HOME??t.homeDir??Vs()??n.USER??"anon"),l=a?je(a,Kt):je(r,`${Kt}-${u}`);Ds(l,{recursive:!0,mode:448});let v=je(l,`${s}.sock`);return v.length>ud&&h.warning(`voice server: Unix socket path is ${v.length} bytes (macOS limit is 104): ${v}`),{address:v,pidFile:je(l,`${s}.pid`),endpointHash:s}}function Jt(t){return ad("sha256").update(t).digest("hex").slice(0,dd)}var $s="COPILOT_VOICE_SERVER_BOOT";function qs(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}if(!js(e))return{};let n=e.voice;if(!js(n))return{};let r={};return typeof n.enabled=="boolean"&&(r.enabled=n.enabled),typeof n.selectedModel=="string"&&n.selectedModel.length>0&&(r.selectedModel=n.selectedModel),Object.keys(r).length>0?{voice:r}:{}}function js(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pd=10,Hs=1,Gs=6e4;async function bp(){let t=Us(),e=fd(t.endpointHash),n=new ft(e);h.setLogWriter(n),h.info(`voice server: boot pid=${process.pid} endpoint=${t.address}`);let r=As(),i=new Dt,s=new Ht({host:i,foundryFactory:C=>new Ut({events:C,installer:r}),micFactory:C=>new jt({events:C}),bootSettings:qs(process.env[$s])});i.setSubmit(C=>s.submit(C));let a=!1,u=null,l=()=>{u===null&&(u=setTimeout(()=>{u=null,h.info("voice server: idle timeout, shutting down"),G("idle timeout").catch(()=>{})},Gs))},v=()=>{u!==null&&(clearTimeout(u),u=null)};i.onClientConnected(()=>v()),i.onClientDisconnected(()=>{a||i.connectionCount===0&&l()}),l();let w=new Wt({host:i,address:t.address}),O;try{O=await w.start()}catch(C){h.error(`voice server: bind threw: ${C.stack??String(C)}`),await n.writeQueue,process.exit(Hs)}O==="lost"&&(h.info(`voice server: bind-loser, another voice server owns ${t.address}`),await s.dispose().catch(()=>{}),await n.writeQueue,process.exit(pd));try{Ms(t.pidFile,process.pid)}catch(C){h.error(`voice server: writeServerPidFile failed: ${C.message}`),await w.stop(),await s.dispose().catch(()=>{}),await n.writeQueue,process.exit(Hs)}let j=()=>{Ns(t.pidFile)===process.pid&&Ls(t.pidFile)},G=async C=>{if(a)return;a=!0,v(),h.info(`voice server: shutdown (${C})`);let W=w.stop().catch(z=>{h.error(`voice server: server.stop failed: ${z.message}`)});i.dispose(),await W,await s.dispose().catch(z=>{h.error(`voice server: engine.dispose failed: ${z.message}`)}),j(),await n.writeQueue.catch(()=>{}),process.exit(0)};for(let C of["SIGINT","SIGTERM","SIGHUP"])process.on(C,()=>{G(`signal ${C}`).catch(()=>{})});process.on("uncaughtException",C=>{h.error(`voice server: uncaughtException: ${C.stack??String(C)}`),G("uncaughtException").catch(()=>{})}),process.on("unhandledRejection",C=>{h.error(`voice server: unhandledRejection: ${String(C)}`)}),process.on("exit",()=>{j()}),h.info(`voice server: ready (idle timer armed ${Gs}ms)`)}function fd(t){return ld(jr(void 0,"state"),"logs",`voice-server-${t}.log`)}export{bp as runVoiceServer};