@github/copilot
Version:
GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.
84 lines • 109 kB
JavaScript
(()=>{const stack=new Error().stack;stack&&(globalThis._sentryDebugIds=globalThis._sentryDebugIds||{},globalThis._sentryDebugIds[stack]="ff40227c-080a-5481-a366-a80c0818a87f",globalThis._sentryDebugIdIdentifier="sentry-dbid-ff40227c-080a-5481-a366-a80c0818a87f");})();
/*---------------------------------------------------------------------------------------------
* 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 Ui=Object.create;var sr=Object.defineProperty;var Hi=Object.getOwnPropertyDescriptor;var Bi=Object.getOwnPropertyNames;var zi=Object.getPrototypeOf,Ji=Object.prototype.hasOwnProperty;var pe=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var A=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Gi=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bi(e))!Ji.call(n,i)&&i!==t&&sr(n,i,{get:()=>e[i],enumerable:!(r=Hi(e,i))||r.enumerable});return n};var ar=(n,e,t)=>(t=n!=null?Ui(zi(n)):{},Gi(e||!n||!n.__esModule?sr(t,"default",{value:n,enumerable:!0}):t,n));var Ee=A(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 Ki(n){return n===!0||n===!1}q.boolean=Ki;function dr(n){return typeof n=="string"||n instanceof String}q.string=dr;function Qi(n){return typeof n=="number"||n instanceof Number}q.number=Qi;function Yi(n){return n instanceof Error}q.error=Yi;function Xi(n){return typeof n=="function"}q.func=Xi;function cr(n){return Array.isArray(n)}q.array=cr;function Zi(n){return cr(n)&&n.every(e=>dr(e))}q.stringArray=Zi});var Jt=A(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.Message=g.NotificationType9=g.NotificationType8=g.NotificationType7=g.NotificationType6=g.NotificationType5=g.NotificationType4=g.NotificationType3=g.NotificationType2=g.NotificationType1=g.NotificationType0=g.NotificationType=g.RequestType9=g.RequestType8=g.RequestType7=g.RequestType6=g.RequestType5=g.RequestType4=g.RequestType3=g.RequestType2=g.RequestType1=g.RequestType=g.RequestType0=g.AbstractMessageSignature=g.ParameterStructures=g.ResponseError=g.ErrorCodes=void 0;var fe=Ee(),kt;(function(n){n.ParseError=-32700,n.InvalidRequest=-32600,n.MethodNotFound=-32601,n.InvalidParams=-32602,n.InternalError=-32603,n.jsonrpcReservedErrorRangeStart=-32099,n.serverErrorStart=-32099,n.MessageWriteError=-32099,n.MessageReadError=-32098,n.PendingResponseRejected=-32097,n.ConnectionInactive=-32096,n.ServerNotInitialized=-32002,n.UnknownErrorCode=-32001,n.jsonrpcReservedErrorRangeEnd=-32e3,n.serverErrorEnd=-32e3})(kt||(g.ErrorCodes=kt={}));var It=class n extends Error{constructor(e,t,r){super(t),this.code=fe.number(e)?e:kt.UnknownErrorCode,this.data=r,Object.setPrototypeOf(this,n.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};g.ResponseError=It;var U=class n{constructor(e){this.kind=e}static is(e){return e===n.auto||e===n.byName||e===n.byPosition}toString(){return this.kind}};g.ParameterStructures=U;U.auto=new U("auto");U.byPosition=new U("byPosition");U.byName=new U("byName");var _=class{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return U.auto}};g.AbstractMessageSignature=_;var Rt=class extends _{constructor(e){super(e,0)}};g.RequestType0=Rt;var Mt=class extends _{constructor(e,t=U.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};g.RequestType=Mt;var Ct=class extends _{constructor(e,t=U.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};g.RequestType1=Ct;var Pt=class extends _{constructor(e){super(e,2)}};g.RequestType2=Pt;var _t=class extends _{constructor(e){super(e,3)}};g.RequestType3=_t;var Tt=class extends _{constructor(e){super(e,4)}};g.RequestType4=Tt;var xt=class extends _{constructor(e){super(e,5)}};g.RequestType5=xt;var Ot=class extends _{constructor(e){super(e,6)}};g.RequestType6=Ot;var Lt=class extends _{constructor(e){super(e,7)}};g.RequestType7=Lt;var Nt=class extends _{constructor(e){super(e,8)}};g.RequestType8=Nt;var Ft=class extends _{constructor(e){super(e,9)}};g.RequestType9=Ft;var Dt=class extends _{constructor(e,t=U.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};g.NotificationType=Dt;var At=class extends _{constructor(e){super(e,0)}};g.NotificationType0=At;var jt=class extends _{constructor(e,t=U.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};g.NotificationType1=jt;var qt=class extends _{constructor(e){super(e,2)}};g.NotificationType2=qt;var $t=class extends _{constructor(e){super(e,3)}};g.NotificationType3=$t;var Vt=class extends _{constructor(e){super(e,4)}};g.NotificationType4=Vt;var Wt=class extends _{constructor(e){super(e,5)}};g.NotificationType5=Wt;var Ut=class extends _{constructor(e){super(e,6)}};g.NotificationType6=Ut;var Ht=class extends _{constructor(e){super(e,7)}};g.NotificationType7=Ht;var Bt=class extends _{constructor(e){super(e,8)}};g.NotificationType8=Bt;var zt=class extends _{constructor(e){super(e,9)}};g.NotificationType9=zt;var lr;(function(n){function e(i){let s=i;return s&&fe.string(s.method)&&(fe.string(s.id)||fe.number(s.id))}n.isRequest=e;function t(i){let s=i;return s&&fe.string(s.method)&&i.id===void 0}n.isNotification=t;function r(i){let s=i;return s&&(s.result!==void 0||!!s.error)&&(fe.string(s.id)||fe.number(s.id)||s.id===null)}n.isResponse=r})(lr||(g.Message=lr={}))});var Kt=A(se=>{"use strict";var ur;Object.defineProperty(se,"__esModule",{value:!0});se.LRUCache=se.LinkedMap=se.Touch=void 0;var $;(function(n){n.None=0,n.First=1,n.AsOld=n.First,n.Last=2,n.AsNew=n.Last})($||(se.Touch=$={}));var Ue=class{constructor(){this[ur]="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,t=$.None){let r=this._map.get(e);if(r)return t!==$.None&&this.touch(r,t),r.value}set(e,t,r=$.None){let i=this._map.get(e);if(i)i.value=t,r!==$.None&&this.touch(i,r);else{switch(i={key:e,value:t,next:void 0,previous:void 0},r){case $.None:this.addItemLast(i);break;case $.First:this.addItemFirst(i);break;case $.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 t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.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,t){let r=this._state,i=this._head;for(;i;){if(t?e.bind(t)(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,t=this._head,r={[Symbol.iterator]:()=>r,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:t.key,done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return r}values(){let e=this._state,t=this._head,r={[Symbol.iterator]:()=>r,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:t.value,done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return r}entries(){let e=this._state,t=this._head,r={[Symbol.iterator]:()=>r,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:[t.key,t.value],done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return r}[(ur=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,r=this.size;for(;t&&r>e;)this._map.delete(t.key),t=t.next,r--;this._head=t,this._size=r,t&&(t.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 t=e.next,r=e.previous;if(!t||!r)throw new Error("Invalid list");t.previous=r,r.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(t!==$.First&&t!==$.Last)){if(t===$.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(t===$.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((t,r)=>{e.push([r,t])}),e}fromJSON(e){this.clear();for(let[t,r]of e)this.set(t,r)}};se.LinkedMap=Ue;var Gt=class extends Ue{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),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,t=$.AsNew){return super.get(e,t)}peek(e){return super.get(e,$.None)}set(e,t){return super.set(e,t,$.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};se.LRUCache=Gt});var fr=A(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Disposable=void 0;var pr;(function(n){function e(t){return{dispose:t}}n.create=e})(pr||(He.Disposable=pr={}))});var ae=A(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});var Qt;function Yt(){if(Qt===void 0)throw new Error("No runtime abstraction layer installed");return Qt}(function(n){function e(t){if(t===void 0)throw new Error("No runtime abstraction layer provided");Qt=t}n.install=e})(Yt||(Yt={}));Xt.default=Yt});var be=A(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.Emitter=we.Event=void 0;var eo=ae(),hr;(function(n){let e={dispose(){}};n.None=function(){return e}})(hr||(we.Event=hr={}));var Zt=class{add(e,t=null,r){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(r)&&r.push({dispose:()=>this.remove(e,t)})}remove(e,t=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]===t){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 t=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let s=0,a=r.length;s<a;s++)try{t.push(r[s].apply(i[s],e))}catch(u){(0,eo.default)().console.error(u)}return t}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},Be=class n{constructor(e){this._options=e}get event(){return this._event||(this._event=(e,t,r)=>{this._callbacks||(this._callbacks=new Zt),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);let i={dispose:()=>{this._callbacks&&(this._callbacks.remove(e,t),i.dispose=n._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)}};we.Emitter=Be;Be._noop=function(){}});var Ge=A(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.CancellationTokenSource=Se.CancellationToken=void 0;var to=ae(),no=Ee(),en=be(),ze;(function(n){n.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:en.Event.None}),n.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:en.Event.None});function e(t){let r=t;return r&&(r===n.None||r===n.Cancelled||no.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}n.is=e})(ze||(Se.CancellationToken=ze={}));var ro=Object.freeze(function(n,e){let t=(0,to.default)().timer.setTimeout(n.bind(e),0);return{dispose(){t.dispose()}}}),Je=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?ro:(this._emitter||(this._emitter=new en.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},tn=class{get token(){return this._token||(this._token=new Je),this._token}cancel(){this._token?this._token.cancel():this._token=ze.Cancelled}dispose(){this._token?this._token instanceof Je&&this._token.dispose():this._token=ze.None}};Se.CancellationTokenSource=tn});var gr=A(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.SharedArrayReceiverStrategy=ke.SharedArraySenderStrategy=void 0;var io=Ge(),Ne;(function(n){n.Continue=0,n.Cancelled=1})(Ne||(Ne={}));var nn=class{constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let t=new SharedArrayBuffer(4),r=new Int32Array(t,0,1);r[0]=Ne.Continue,this.buffers.set(e.id,t),e.$cancellationData=t}async sendCancellation(e,t){let r=this.buffers.get(t);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,Ne.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};ke.SharedArraySenderStrategy=nn;var rn=class{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===Ne.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}},on=class{constructor(e){this.token=new rn(e)}cancel(){}dispose(){}},sn=class{constructor(){this.kind="request"}createCancellationTokenSource(e){let t=e.$cancellationData;return t===void 0?new io.CancellationTokenSource:new on(t)}};ke.SharedArrayReceiverStrategy=sn});var dn=A(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.Semaphore=void 0;var oo=ae(),an=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((t,r)=>{this._waiting.push({thunk:e,resolve:t,reject:r}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,oo.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 t=e.thunk();t instanceof Promise?t.then(r=>{this._active--,e.resolve(r),this.runNext()},r=>{this._active--,e.reject(r),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}};Ke.Semaphore=an});var yr=A(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.ReadableStreamMessageReader=de.AbstractMessageReader=de.MessageReader=void 0;var ln=ae(),Ie=Ee(),cn=be(),so=dn(),mr;(function(n){function e(t){let r=t;return r&&Ie.func(r.listen)&&Ie.func(r.dispose)&&Ie.func(r.onError)&&Ie.func(r.onClose)&&Ie.func(r.onPartialMessage)}n.is=e})(mr||(de.MessageReader=mr={}));var Qe=class{constructor(){this.errorEmitter=new cn.Emitter,this.closeEmitter=new cn.Emitter,this.partialMessageEmitter=new cn.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: ${Ie.string(e.message)?e.message:"unknown"}`)}};de.AbstractMessageReader=Qe;var un;(function(n){function e(t){let r,i,s,a=new Map,u,f=new Map;if(t===void 0||typeof t=="string")r=t??"utf-8";else{if(r=t.charset??"utf-8",t.contentDecoder!==void 0&&(s=t.contentDecoder,a.set(s.name,s)),t.contentDecoders!==void 0)for(let E of t.contentDecoders)a.set(E.name,E);if(t.contentTypeDecoder!==void 0&&(u=t.contentTypeDecoder,f.set(u.name,u)),t.contentTypeDecoders!==void 0)for(let E of t.contentTypeDecoders)f.set(E.name,E)}return u===void 0&&(u=(0,ln.default)().applicationJson.decoder,f.set(u.name,u)),{charset:r,contentDecoder:s,contentDecoders:a,contentTypeDecoder:u,contentTypeDecoders:f}}n.fromOptions=e})(un||(un={}));var pn=class extends Qe{constructor(e,t){super(),this.readable=e,this.options=un.fromOptions(t),this.buffer=(0,ln.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new so.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 t=this.readable.onData(r=>{this.onData(r)});return this.readable.onError(r=>this.fireError(r)),this.readable.onClose(()=>this.fireClose()),t}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 t=this.buffer.tryReadBody(this.nextMessageLength);if(t===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(t):t,i=await this.options.contentTypeDecoder.decode(r,this.options);this.callback(i)}).catch(r=>{this.fireError(r)})}}catch(t){this.fireError(t)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,ln.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};de.ReadableStreamMessageReader=pn});var Sr=A(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.WriteableStreamMessageWriter=ce.AbstractMessageWriter=ce.MessageWriter=void 0;var vr=ae(),Fe=Ee(),ao=dn(),Er=be(),co="Content-Length: ",wr=`\r
`,br;(function(n){function e(t){let r=t;return r&&Fe.func(r.dispose)&&Fe.func(r.onClose)&&Fe.func(r.onError)&&Fe.func(r.write)}n.is=e})(br||(ce.MessageWriter=br={}));var Ye=class{constructor(){this.errorEmitter=new Er.Emitter,this.closeEmitter=new Er.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,r){this.errorEmitter.fire([this.asError(e),t,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: ${Fe.string(e.message)?e.message:"unknown"}`)}};ce.AbstractMessageWriter=Ye;var fn;(function(n){function e(t){return t===void 0||typeof t=="string"?{charset:t??"utf-8",contentTypeEncoder:(0,vr.default)().applicationJson.encoder}:{charset:t.charset??"utf-8",contentEncoder:t.contentEncoder,contentTypeEncoder:t.contentTypeEncoder??(0,vr.default)().applicationJson.encoder}}n.fromOptions=e})(fn||(fn={}));var hn=class extends Ye{constructor(e,t){super(),this.writable=e,this.options=fn.fromOptions(t),this.errorCount=0,this.writeSemaphore=new ao.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(co,r.byteLength.toString(),wr),i.push(wr),this.doWrite(e,i,r)},r=>{throw this.fireError(r),r}))}async doWrite(e,t,r){try{return await this.writable.write(t.join(""),"ascii"),this.writable.write(r)}catch(i){return this.handleError(i,e),Promise.reject(i)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}};ce.WriteableStreamMessageWriter=hn});var kr=A(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.AbstractMessageBuffer=void 0;var lo=13,uo=10,po=`\r
`,gn=class{constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let t=typeof e=="string"?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(e=!1){if(this._chunks.length===0)return;let t=0,r=0,i=0,s=0;e:for(;r<this._chunks.length;){let E=this._chunks[r];for(i=0;i<E.length;){switch(E[i]){case lo:switch(t){case 0:t=1;break;case 2:t=3;break;default:t=0}break;case uo:switch(t){case 1:t=2;break;case 3:t=4,i++;break e;default:t=0}break;default:t=0}i++}s+=E.byteLength,r++}if(t!==4)return;let a=this._read(s+i),u=new Map,f=this.toString(a,"ascii").split(po);if(f.length<2)return u;for(let E=0;E<f.length-2;E++){let D=f[E],W=D.indexOf(":");if(W===-1)throw new Error(`Message header must separate key and value using ':'
${D}`);let ee=D.substr(0,W),ne=D.substr(W+1).trim();u.set(e?ee.toLowerCase():ee,ne)}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 t=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);t.set(a,r),r+=e,this._chunks[i]=s.slice(e),this._totalLength-=e,e-=e}else t.set(s,r),r+=s.byteLength,this._chunks.shift(),this._totalLength-=s.byteLength,e-=s.byteLength}return t}};Xe.AbstractMessageBuffer=gn});var Pr=A(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.createMessageConnection=y.ConnectionOptions=y.MessageStrategy=y.CancellationStrategy=y.CancellationSenderStrategy=y.CancellationReceiverStrategy=y.RequestCancellationReceiverStrategy=y.IdCancellationReceiverStrategy=y.ConnectionStrategy=y.ConnectionError=y.ConnectionErrors=y.LogTraceNotification=y.SetTraceNotification=y.TraceFormat=y.TraceValues=y.Trace=y.NullLogger=y.ProgressType=y.ProgressToken=void 0;var Ir=ae(),x=Ee(),m=Jt(),Rr=Kt(),De=be(),mn=Ge(),qe;(function(n){n.type=new m.NotificationType("$/cancelRequest")})(qe||(qe={}));var yn;(function(n){function e(t){return typeof t=="string"||typeof t=="number"}n.is=e})(yn||(y.ProgressToken=yn={}));var Ae;(function(n){n.type=new m.NotificationType("$/progress")})(Ae||(Ae={}));var vn=class{constructor(){}};y.ProgressType=vn;var En;(function(n){function e(t){return x.func(t)}n.is=e})(En||(En={}));y.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var k;(function(n){n[n.Off=0]="Off",n[n.Messages=1]="Messages",n[n.Compact=2]="Compact",n[n.Verbose=3]="Verbose"})(k||(y.Trace=k={}));var Mr;(function(n){n.Off="off",n.Messages="messages",n.Compact="compact",n.Verbose="verbose"})(Mr||(y.TraceValues=Mr={}));(function(n){function e(r){if(!x.string(r))return n.Off;switch(r=r.toLowerCase(),r){case"off":return n.Off;case"messages":return n.Messages;case"compact":return n.Compact;case"verbose":return n.Verbose;default:return n.Off}}n.fromString=e;function t(r){switch(r){case n.Off:return"off";case n.Messages:return"messages";case n.Compact:return"compact";case n.Verbose:return"verbose";default:return"off"}}n.toString=t})(k||(y.Trace=k={}));var B;(function(n){n.Text="text",n.JSON="json"})(B||(y.TraceFormat=B={}));(function(n){function e(t){return x.string(t)?(t=t.toLowerCase(),t==="json"?n.JSON:n.Text):n.Text}n.fromString=e})(B||(y.TraceFormat=B={}));var wn;(function(n){n.type=new m.NotificationType("$/setTrace")})(wn||(y.SetTraceNotification=wn={}));var Ze;(function(n){n.type=new m.NotificationType("$/logTrace")})(Ze||(y.LogTraceNotification=Ze={}));var je;(function(n){n[n.Closed=1]="Closed",n[n.Disposed=2]="Disposed",n[n.AlreadyListening=3]="AlreadyListening"})(je||(y.ConnectionErrors=je={}));var Re=class n extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,n.prototype)}};y.ConnectionError=Re;var bn;(function(n){function e(t){let r=t;return r&&x.func(r.cancelUndispatched)}n.is=e})(bn||(y.ConnectionStrategy=bn={}));var et;(function(n){function e(t){let r=t;return r&&(r.kind===void 0||r.kind==="id")&&x.func(r.createCancellationTokenSource)&&(r.dispose===void 0||x.func(r.dispose))}n.is=e})(et||(y.IdCancellationReceiverStrategy=et={}));var Sn;(function(n){function e(t){let r=t;return r&&r.kind==="request"&&x.func(r.createCancellationTokenSource)&&(r.dispose===void 0||x.func(r.dispose))}n.is=e})(Sn||(y.RequestCancellationReceiverStrategy=Sn={}));var tt;(function(n){n.Message=Object.freeze({createCancellationTokenSource(t){return new mn.CancellationTokenSource}});function e(t){return et.is(t)||Sn.is(t)}n.is=e})(tt||(y.CancellationReceiverStrategy=tt={}));var nt;(function(n){n.Message=Object.freeze({sendCancellation(t,r){return t.sendNotification(qe.type,{id:r})},cleanup(t){}});function e(t){let r=t;return r&&x.func(r.sendCancellation)&&x.func(r.cleanup)}n.is=e})(nt||(y.CancellationSenderStrategy=nt={}));var rt;(function(n){n.Message=Object.freeze({receiver:tt.Message,sender:nt.Message});function e(t){let r=t;return r&&tt.is(r.receiver)&&nt.is(r.sender)}n.is=e})(rt||(y.CancellationStrategy=rt={}));var it;(function(n){function e(t){let r=t;return r&&x.func(r.handleMessage)}n.is=e})(it||(y.MessageStrategy=it={}));var Cr;(function(n){function e(t){let r=t;return r&&(rt.is(r.cancellationStrategy)||bn.is(r.connectionStrategy)||it.is(r.messageStrategy))}n.is=e})(Cr||(y.ConnectionOptions=Cr={}));var K;(function(n){n[n.New=1]="New",n[n.Listening=2]="Listening",n[n.Closed=3]="Closed",n[n.Disposed=4]="Disposed"})(K||(K={}));function fo(n,e,t,r){let i=t!==void 0?t:y.NullLogger,s=0,a=0,u=0,f="2.0",E,D=new Map,W,ee=new Map,ne=new Map,Te,J=new Rr.LinkedMap,X=new Map,xe=new Set,H=new Map,R=k.Off,ue=B.Text,N,re=K.New,wt=new De.Emitter,Jn=new De.Emitter,Gn=new De.Emitter,Kn=new De.Emitter,Qn=new De.Emitter,ie=r&&r.cancellationStrategy?r.cancellationStrategy:rt.Message;function Yn(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 Ii(o){return o===null?"res-unknown-"+(++u).toString():"res-"+o.toString()}function Ri(){return"not-"+(++a).toString()}function Mi(o,c){m.Message.isRequest(c)?o.set(Yn(c.id),c):m.Message.isResponse(c)?o.set(Ii(c.id),c):o.set(Ri(),c)}function Ci(o){}function Xn(){return re===K.Listening}function Zn(){return re===K.Closed}function me(){return re===K.Disposed}function er(){(re===K.New||re===K.Listening)&&(re=K.Closed,Jn.fire(void 0))}function Pi(o){wt.fire([o,void 0,void 0])}function _i(o){wt.fire(o)}n.onClose(er),n.onError(Pi),e.onClose(er),e.onError(_i);function tr(){Te||J.size===0||(Te=(0,Ir.default)().timer.setImmediate(()=>{Te=void 0,Ti()}))}function nr(o){m.Message.isRequest(o)?Oi(o):m.Message.isNotification(o)?Ni(o):m.Message.isResponse(o)?Li(o):Fi(o)}function Ti(){if(J.size===0)return;let o=J.shift();try{let c=r?.messageStrategy;it.is(c)?c.handleMessage(o,nr):nr(o)}finally{tr()}}let xi=o=>{try{if(m.Message.isNotification(o)&&o.method===qe.type.method){let c=o.params.id,l=Yn(c),h=J.get(l);if(m.Message.isRequest(h)){let M=r?.connectionStrategy,O=M&&M.cancelUndispatched?M.cancelUndispatched(h,Ci):void 0;if(O&&(O.error!==void 0||O.result!==void 0)){J.delete(l),H.delete(c),O.id=h.id,We(O,o.method,Date.now()),e.write(O).catch(()=>i.error("Sending response for canceled message failed."));return}}let P=H.get(c);if(P!==void 0){P.cancel(),bt(o);return}else xe.add(c)}Mi(J,o)}finally{tr()}};function Oi(o){if(me())return;function c(S,T,I){let F={jsonrpc:f,id:o.id};S instanceof m.ResponseError?F.error=S.toJson():F.result=S===void 0?null:S,We(F,T,I),e.write(F).catch(()=>i.error("Sending response failed."))}function l(S,T,I){let F={jsonrpc:f,id:o.id,error:S.toJson()};We(F,T,I),e.write(F).catch(()=>i.error("Sending response failed."))}function h(S,T,I){S===void 0&&(S=null);let F={jsonrpc:f,id:o.id,result:S};We(F,T,I),e.write(F).catch(()=>i.error("Sending response failed."))}ji(o);let P=D.get(o.method),M,O;P&&(M=P.type,O=P.handler);let L=Date.now();if(O||E){let S=o.id??String(Date.now()),T=et.is(ie.receiver)?ie.receiver.createCancellationTokenSource(S):ie.receiver.createCancellationTokenSource(o);o.id!==null&&xe.has(o.id)&&T.cancel(),o.id!==null&&H.set(S,T);try{let I;if(O)if(o.params===void 0){if(M!==void 0&&M.numberOfParams!==0){l(new m.ResponseError(m.ErrorCodes.InvalidParams,`Request ${o.method} defines ${M.numberOfParams} params but received none.`),o.method,L);return}I=O(T.token)}else if(Array.isArray(o.params)){if(M!==void 0&&M.parameterStructures===m.ParameterStructures.byName){l(new m.ResponseError(m.ErrorCodes.InvalidParams,`Request ${o.method} defines parameters by name but received parameters by position`),o.method,L);return}I=O(...o.params,T.token)}else{if(M!==void 0&&M.parameterStructures===m.ParameterStructures.byPosition){l(new m.ResponseError(m.ErrorCodes.InvalidParams,`Request ${o.method} defines parameters by position but received parameters by name`),o.method,L);return}I=O(o.params,T.token)}else E&&(I=E(o.method,o.params,T.token));let F=I;I?F.then?F.then(V=>{H.delete(S),c(V,o.method,L)},V=>{H.delete(S),V instanceof m.ResponseError?l(V,o.method,L):V&&x.string(V.message)?l(new m.ResponseError(m.ErrorCodes.InternalError,`Request ${o.method} failed with message: ${V.message}`),o.method,L):l(new m.ResponseError(m.ErrorCodes.InternalError,`Request ${o.method} failed unexpectedly without providing any details.`),o.method,L)}):(H.delete(S),c(I,o.method,L)):(H.delete(S),h(I,o.method,L))}catch(I){H.delete(S),I instanceof m.ResponseError?c(I,o.method,L):I&&x.string(I.message)?l(new m.ResponseError(m.ErrorCodes.InternalError,`Request ${o.method} failed with message: ${I.message}`),o.method,L):l(new m.ResponseError(m.ErrorCodes.InternalError,`Request ${o.method} failed unexpectedly without providing any details.`),o.method,L)}}else l(new m.ResponseError(m.ErrorCodes.MethodNotFound,`Unhandled method ${o.method}`),o.method,L)}function Li(o){if(!me())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 c=o.id,l=X.get(c);if(qi(o,l),l!==void 0){X.delete(c);try{if(o.error){let h=o.error;l.reject(new m.ResponseError(h.code,h.message,h.data))}else if(o.result!==void 0)l.resolve(o.result);else throw new Error("Should never happen.")}catch(h){h.message?i.error(`Response handler '${l.method}' failed with message: ${h.message}`):i.error(`Response handler '${l.method}' failed unexpectedly.`)}}}}function Ni(o){if(me())return;let c,l;if(o.method===qe.type.method){let h=o.params.id;xe.delete(h),bt(o);return}else{let h=ee.get(o.method);h&&(l=h.handler,c=h.type)}if(l||W)try{if(bt(o),l)if(o.params===void 0)c!==void 0&&c.numberOfParams!==0&&c.parameterStructures!==m.ParameterStructures.byName&&i.error(`Notification ${o.method} defines ${c.numberOfParams} params but received none.`),l();else if(Array.isArray(o.params)){let h=o.params;o.method===Ae.type.method&&h.length===2&&yn.is(h[0])?l({token:h[0],value:h[1]}):(c!==void 0&&(c.parameterStructures===m.ParameterStructures.byName&&i.error(`Notification ${o.method} defines parameters by name but received parameters by position`),c.numberOfParams!==o.params.length&&i.error(`Notification ${o.method} defines ${c.numberOfParams} params but received ${h.length} arguments`)),l(...h))}else c!==void 0&&c.parameterStructures===m.ParameterStructures.byPosition&&i.error(`Notification ${o.method} defines parameters by position but received parameters by name`),l(o.params);else W&&W(o.method,o.params)}catch(h){h.message?i.error(`Notification handler '${o.method}' failed with message: ${h.message}`):i.error(`Notification handler '${o.method}' failed unexpectedly.`)}else Gn.fire(o)}function Fi(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 c=o;if(x.string(c.id)||x.number(c.id)){let l=c.id,h=X.get(l);h&&h.reject(new Error("The received response has neither a result nor an error property."))}}function oe(o){if(o!=null)switch(R){case k.Verbose:return JSON.stringify(o,null,4);case k.Compact:return JSON.stringify(o);default:return}}function Di(o){if(!(R===k.Off||!N))if(ue===B.Text){let c;(R===k.Verbose||R===k.Compact)&&o.params&&(c=`Params: ${oe(o.params)}
`),N.log(`Sending request '${o.method} - (${o.id})'.`,c)}else ye("send-request",o)}function Ai(o){if(!(R===k.Off||!N))if(ue===B.Text){let c;(R===k.Verbose||R===k.Compact)&&(o.params?c=`Params: ${oe(o.params)}
`:c=`No parameters provided.
`),N.log(`Sending notification '${o.method}'.`,c)}else ye("send-notification",o)}function We(o,c,l){if(!(R===k.Off||!N))if(ue===B.Text){let h;(R===k.Verbose||R===k.Compact)&&(o.error&&o.error.data?h=`Error data: ${oe(o.error.data)}
`:o.result?h=`Result: ${oe(o.result)}
`:o.error===void 0&&(h=`No result returned.
`)),N.log(`Sending response '${c} - (${o.id})'. Processing request took ${Date.now()-l}ms`,h)}else ye("send-response",o)}function ji(o){if(!(R===k.Off||!N))if(ue===B.Text){let c;(R===k.Verbose||R===k.Compact)&&o.params&&(c=`Params: ${oe(o.params)}
`),N.log(`Received request '${o.method} - (${o.id})'.`,c)}else ye("receive-request",o)}function bt(o){if(!(R===k.Off||!N||o.method===Ze.type.method))if(ue===B.Text){let c;(R===k.Verbose||R===k.Compact)&&(o.params?c=`Params: ${oe(o.params)}
`:c=`No parameters provided.
`),N.log(`Received notification '${o.method}'.`,c)}else ye("receive-notification",o)}function qi(o,c){if(!(R===k.Off||!N))if(ue===B.Text){let l;if((R===k.Verbose||R===k.Compact)&&(o.error&&o.error.data?l=`Error data: ${oe(o.error.data)}
`:o.result?l=`Result: ${oe(o.result)}
`:o.error===void 0&&(l=`No result returned.
`)),c){let h=o.error?` Request failed: ${o.error.message} (${o.error.code}).`:"";N.log(`Received response '${c.method} - (${o.id})' in ${Date.now()-c.timerStart}ms.${h}`,l)}else N.log(`Received response ${o.id} without active response promise.`,l)}else ye("receive-response",o)}function ye(o,c){if(!N||R===k.Off)return;let l={isLSPMessage:!0,type:o,message:c,timestamp:Date.now()};N.log(l)}function Oe(){if(Zn())throw new Re(je.Closed,"Connection is closed.");if(me())throw new Re(je.Disposed,"Connection is disposed.")}function $i(){if(Xn())throw new Re(je.AlreadyListening,"Connection is already listening")}function Vi(){if(!Xn())throw new Error("Call listen() first.")}function Le(o){return o===void 0?null:o}function rr(o){if(o!==null)return o}function ir(o){return o!=null&&!Array.isArray(o)&&typeof o=="object"}function St(o,c){switch(o){case m.ParameterStructures.auto:return ir(c)?rr(c):[Le(c)];case m.ParameterStructures.byName:if(!ir(c))throw new Error("Received parameters by name but param is not an object literal.");return rr(c);case m.ParameterStructures.byPosition:return[Le(c)];default:throw new Error(`Unknown parameter structure ${o.toString()}`)}}function or(o,c){let l,h=o.numberOfParams;switch(h){case 0:l=void 0;break;case 1:l=St(o.parameterStructures,c[0]);break;default:l=[];for(let P=0;P<c.length&&P<h;P++)l.push(Le(c[P]));if(c.length<h)for(let P=c.length;P<h;P++)l.push(null);break}return l}let ve={sendNotification:(o,...c)=>{Oe();let l,h;if(x.string(o)){l=o;let M=c[0],O=0,L=m.ParameterStructures.auto;m.ParameterStructures.is(M)&&(O=1,L=M);let S=c.length,T=S-O;switch(T){case 0:h=void 0;break;case 1:h=St(L,c[O]);break;default:if(L===m.ParameterStructures.byName)throw new Error(`Received ${T} parameters for 'by Name' notification parameter structure.`);h=c.slice(O,S).map(I=>Le(I));break}}else{let M=c;l=o.method,h=or(o,M)}let P={jsonrpc:f,method:l,params:h};return Ai(P),e.write(P).catch(M=>{throw i.error("Sending notification failed."),M})},onNotification:(o,c)=>{Oe();let l;return x.func(o)?W=o:c&&(x.string(o)?(l=o,ee.set(o,{type:void 0,handler:c})):(l=o.method,ee.set(o.method,{type:o,handler:c}))),{dispose:()=>{l!==void 0?ee.delete(l):W=void 0}}},onProgress:(o,c,l)=>{if(ne.has(c))throw new Error(`Progress handler for token ${c} already registered`);return ne.set(c,l),{dispose:()=>{ne.delete(c)}}},sendProgress:(o,c,l)=>ve.sendNotification(Ae.type,{token:c,value:l}),onUnhandledProgress:Kn.event,sendRequest:(o,...c)=>{Oe(),Vi();let l,h,P;if(x.string(o)){l=o;let S=c[0],T=c[c.length-1],I=0,F=m.ParameterStructures.auto;m.ParameterStructures.is(S)&&(I=1,F=S);let V=c.length;mn.CancellationToken.is(T)&&(V=V-1,P=T);let Z=V-I;switch(Z){case 0:h=void 0;break;case 1:h=St(F,c[I]);break;default:if(F===m.ParameterStructures.byName)throw new Error(`Received ${Z} parameters for 'by Name' request parameter structure.`);h=c.slice(I,V).map(Wi=>Le(Wi));break}}else{let S=c;l=o.method,h=or(o,S);let T=o.numberOfParams;P=mn.CancellationToken.is(S[T])?S[T]:void 0}let M=s++,O;P&&(O=P.onCancellationRequested(()=>{let S=ie.sender.sendCancellation(ve,M);return S===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${M}`),Promise.resolve()):S.catch(()=>{i.log(`Sending cancellation messages for id ${M} failed`)})}));let L={jsonrpc:f,id:M,method:l,params:h};return Di(L),typeof ie.sender.enableCancellation=="function"&&ie.sender.enableCancellation(L),new Promise(async(S,T)=>{let I=Z=>{S(Z),ie.sender.cleanup(M),O?.dispose()},F=Z=>{T(Z),ie.sender.cleanup(M),O?.dispose()},V={method:l,timerStart:Date.now(),resolve:I,reject:F};try{X.set(M,V),await e.write(L)}catch(Z){throw X.delete(M),V.reject(new m.ResponseError(m.ErrorCodes.MessageWriteError,Z.message?Z.message:"Unknown reason")),i.error("Sending request failed."),Z}})},onRequest:(o,c)=>{Oe();let l=null;return En.is(o)?(l=void 0,E=o):x.string(o)?(l=null,c!==void 0&&(l=o,D.set(o,{handler:c,type:void 0}))):c!==void 0&&(l=o.method,D.set(o.method,{type:o,handler:c})),{dispose:()=>{l!==null&&(l!==void 0?D.delete(l):E=void 0)}}},hasPendingResponse:()=>X.size>0,trace:async(o,c,l)=>{let h=!1,P=B.Text;l!==void 0&&(x.boolean(l)?h=l:(h=l.sendNotification||!1,P=l.traceFormat||B.Text)),R=o,ue=P,R===k.Off?N=void 0:N=c,h&&!Zn()&&!me()&&await ve.sendNotification(wn.type,{value:k.toString(o)})},onError:wt.event,onClose:Jn.event,onUnhandledNotification:Gn.event,onDispose:Qn.event,end:()=>{e.end()},dispose:()=>{if(me())return;re=K.Disposed,Qn.fire(void 0);let o=new m.ResponseError(m.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let c of X.values())c.reject(o);X=new Map,H=new Map,xe=new Set,J=new Rr.LinkedMap,x.func(e.dispose)&&e.dispose(),x.func(n.dispose)&&n.dispose()},listen:()=>{Oe(),$i(),re=K.Listening,n.listen(xi)},inspect:()=>{(0,Ir.default)().console.log("inspect")}};return ve.onNotification(Ze.type,o=>{if(R===k.Off||!N)return;let c=R===k.Verbose||R===k.Compact;N.log(o.message,c?o.verbose:void 0)}),ve.onNotification(Ae.type,o=>{let c=ne.get(o.token);c?c(o.value):Kn.fire(o)}),ve}y.createMessageConnection=fo});var ot=A(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.ProgressType=d.ProgressToken=d.createMessageConnection=d.NullLogger=d.ConnectionOptions=d.ConnectionStrategy=d.AbstractMessageBuffer=d.WriteableStreamMessageWriter=d.AbstractMessageWriter=d.MessageWriter=d.ReadableStreamMessageReader=d.AbstractMessageReader=d.MessageReader=d.SharedArrayReceiverStrategy=d.SharedArraySenderStrategy=d.CancellationToken=d.CancellationTokenSource=d.Emitter=d.Event=d.Disposable=d.LRUCache=d.Touch=d.LinkedMap=d.ParameterStructures=d.NotificationType9=d.NotificationType8=d.NotificationType7=d.NotificationType6=d.NotificationType5=d.NotificationType4=d.NotificationType3=d.NotificationType2=d.NotificationType1=d.NotificationType0=d.NotificationType=d.ErrorCodes=d.ResponseError=d.RequestType9=d.RequestType8=d.RequestType7=d.RequestType6=d.RequestType5=d.RequestType4=d.RequestType3=d.RequestType2=d.RequestType1=d.RequestType0=d.RequestType=d.Message=d.RAL=void 0;d.MessageStrategy=d.CancellationStrategy=d.CancellationSenderStrategy=d.CancellationReceiverStrategy=d.ConnectionError=d.ConnectionErrors=d.LogTraceNotification=d.SetTraceNotification=d.TraceFormat=d.TraceValues=d.Trace=void 0;var C=Jt();Object.defineProperty(d,"Message",{enumerable:!0,get:function(){return C.Message}});Object.defineProperty(d,"RequestType",{enumerable:!0,get:function(){return C.RequestType}});Object.defineProperty(d,"RequestType0",{enumerable:!0,get:function(){return C.RequestType0}});Object.defineProperty(d,"RequestType1",{enumerable:!0,get:function(){return C.RequestType1}});Object.defineProperty(d,"RequestType2",{enumerable:!0,get:function(){return C.RequestType2}});Object.defineProperty(d,"RequestType3",{enumerable:!0,get:function(){return C.RequestType3}});Object.defineProperty(d,"RequestType4",{enumerable:!0,get:function(){return C.RequestType4}});Object.defineProperty(d,"RequestType5",{enumerable:!0,get:function(){return C.RequestType5}});Object.defineProperty(d,"RequestType6",{enumerable:!0,get:function(){return C.RequestType6}});Object.defineProperty(d,"RequestType7",{enumerable:!0,get:function(){return C.RequestType7}});Object.defineProperty(d,"RequestType8",{enumerable:!0,get:function(){return C.RequestType8}});Object.defineProperty(d,"RequestType9",{enumerable:!0,get:function(){return C.RequestType9}});Object.defineProperty(d,"ResponseError",{enumerable:!0,get:function(){return C.ResponseError}});Object.defineProperty(d,"ErrorCodes",{enumerable:!0,get:function(){return C.ErrorCodes}});Object.defineProperty(d,"NotificationType",{enumerable:!0,get:function(){return C.NotificationType}});Object.defineProperty(d,"NotificationType0",{enumerable:!0,get:function(){return C.NotificationType0}});Object.defineProperty(d,"NotificationType1",{enumerable:!0,get:function(){return C.NotificationType1}});Object.defineProperty(d,"NotificationType2",{enumerable:!0,get:function(){return C.NotificationType2}});Object.defineProperty(d,"NotificationType3",{enumerable:!0,get:function(){return C.NotificationType3}});Object.defineProperty(d,"NotificationType4",{enumerable:!0,get:function(){return C.NotificationType4}});Object.defineProperty(d,"NotificationType5",{enumerable:!0,get:function(){return C.NotificationType5}});Object.defineProperty(d,"NotificationType6",{enumerable:!0,get:function(){return C.NotificationType6}});Object.defineProperty(d,"NotificationType7",{enumerable:!0,get:function(){return C.NotificationType7}});Object.defineProperty(d,"NotificationType8",{enumerable:!0,get:function(){return C.NotificationType8}});Object.defineProperty(d,"NotificationType9",{enumerable:!0,get:function(){return C.NotificationType9}});Object.defineProperty(d,"ParameterStructures",{enumerable:!0,get:function(){return C.ParameterStructures}});var kn=Kt();Object.defineProperty(d,"LinkedMap",{enumerable:!0,get:function(){return kn.LinkedMap}});Object.defineProperty(d,"LRUCache",{enumerable:!0,get:function(){return kn.LRUCache}});Object.defineProperty(d,"Touch",{enumerable:!0,get:function(){return kn.Touch}});var ho=fr();Object.defineProperty(d,"Disposable",{enumerable:!0,get:function(){return ho.Disposable}});var _r=be();Object.defineProperty(d,"Event",{enumerable:!0,get:function(){return _r.Event}});Object.defineProperty(d,"Emitter",{enumerable:!0,get:function(){return _r.Emitter}});var Tr=Ge();Object.defineProperty(d,"CancellationTokenSource",{enumerable:!0,get:function(){return Tr.CancellationTokenSource}});Object.defineProperty(d,"CancellationToken",{enumerable:!0,get:function(){return Tr.CancellationToken}});var xr=gr();Object.defineProperty(d,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return xr.SharedArraySenderStrategy}});Object.defineProperty(d,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return xr.SharedArrayReceiverStrategy}});var In=yr();Object.defineProperty(d,"MessageReader",{enumerable:!0,get:function(){return In.MessageReader}});Object.defineProperty(d,"AbstractMessageReader",{enumerable:!0,get:function(){return In.AbstractMessageReader}});Object.defineProperty(d,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return In.ReadableStreamMessageReader}});var Rn=Sr();Object.defineProperty(d,"MessageWriter",{enumerable:!0,get:function(){return Rn.MessageWriter}});Object.defineProperty(d,"AbstractMessageWriter",{enumerable:!0,get:function(){return Rn.AbstractMessageWriter}});Object.defineProperty(d,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return Rn.WriteableStreamMessageWriter}});var go=kr();Object.defineProperty(d,"AbstractMessageBuffer",{enumerable:!0,get:function(){return go.AbstractMessageBuffer}});var j=Pr();Object.defineProperty(d,"ConnectionStrategy",{enumerable:!0,get:function(){return j.ConnectionStrategy}});Object.defineProperty(d,"ConnectionOptions",{enumerable:!0,get:function(){return j.ConnectionOptions}});Object.defineProperty(d,"NullLogger",{enumerable:!0,get:function(){return j.NullLogger}});Object.defineProperty(d,"createMessageConnection",{enumerable:!0,get:function(){return j.createMessageConnection}});Object.defineProperty(d,"ProgressToken",{enumerable:!0,get:function(){return j.ProgressToken}});Object.defineProperty(d,"ProgressType",{enumerable:!0,get:function(){return j.ProgressType}});Object.defineProperty(d,"Trace",{enumerable:!0,get:function(){return j.Trace}});Object.defineProperty(d,"TraceValues",{enumerable:!0,get:function(){return j.TraceValues}});Object.defineProperty(d,"TraceFormat",{enumerable:!0,get:function(){return j.TraceFormat}});Object.defineProperty(d,"SetTraceNotification",{enumerable:!0,get:function(){return j.SetTraceNotification}});Object.defineProperty(d,"LogTraceNotification",{enumerable:!0,get:function(){return j.LogTraceNotification}});Object.defineProperty(d,"ConnectionErrors",{enumerable:!0,get:function(){return j.ConnectionErrors}});Object.defineProperty(d,"ConnectionError",{enumerable:!0,get:function(){return j.ConnectionError}});Object.defineProperty(d,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return j.CancellationReceiverStrategy}});Object.defineProperty(d,"CancellationSenderStrategy",{enumerable:!0,get:function(){return j.CancellationSenderStrategy}});Object.defineProperty(d,"CancellationStrategy",{enumerable:!0,get:function(){return j.CancellationStrategy}});Object.defineProperty(d,"MessageStrategy",{enumerable:!0,get:function(){return j.MessageStrategy}});var mo=ae();d.RAL=mo.default});var Nr=A(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});var Or=pe("util"),te=ot(),st=class n extends te.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return n.emptyBuffer}fromString(e,t){return Buffer.from(e,t)}toString(e,t){return e instanceof Buffer?e.toString(t):new Or.TextDecoder(t).decode(e)}asNative(e,t){return t===void 0?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,t):Buffer.from(e,0,t)}allocNative(e){return Buffer.allocUnsafe(e)}};st.emptyBuffer=Buffer.allocUnsafe(0);var Mn=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),te.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),te.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),te.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),te.Disposable.create(()=>this.stream.off("data",e))}},Cn=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),te.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),te.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),te.Disposable.create(()=>this.stream.off("end",e))}write(e,t){return new Promise((r,i)=>{let s=a=>{a==null?r():i(a)};typeof e=="string"?this.stream.write(e,t,s):this.stream.write(e,s)})}end(){this.stream.end()}},Lr=Object.freeze({messageBuffer:Object.freeze({create:n=>new st(n)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(n,e)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(n,void 0,0),e.charset))}catch(t){return Promise.reject(t)}}}),decoder:Object.freeze({name:"application/json",decode:(n,e)=>{try{return n instanceof Buffer?Promise.resolve(JSON.parse(n.toString(e.charset))):Promise.resolve(JSON.parse(new Or.TextDecoder(e.charset).decode(n)))}catch(t){return Promise.reject(t)}}})}),stream:Object.freeze({asReadableStream:n=>new Mn(n),asWritableStream:n=>new Cn(n)}),console,timer:Object.freeze({setTimeout(n,e,...t){let r=setTimeout(n,e,...t);return{dispose:()=>clearTimeout(r)}},setImmediate(n,...e){let t=setImmediate(n,...e);return{dispose:()=>clearImmediate(t)}},setInterval(n,e,...t){let r=setInterval(n,e,...t);return{dispose:()=>clearInterval(r)}}})});function Pn(){return Lr}(function(n){function e(){te.RAL.install(Lr)}n.install=e})(Pn||(Pn={}));_n.default=Pn});var Ar=A(b=>{"use strict";var yo=b&&b.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,i)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),vo=b&&b.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&yo(e,n,t)};Object.defineProperty(b,"__esModule",{value:!0});b.createMessageConnection=b.createServerSocketTransport=b.createClientSocketTransport=b.createServerPipeTransport=b.createClientPipeTransport=b.generateRandomPipeName=b.StreamMessageWriter=b.StreamMessageReader=b.SocketMessageWriter=b.SocketMessageReader=b.PortMessageWriter=b.PortMessageReader=b.IPCMessageWriter=b.IPCMessageReader=void 0;var Me=Nr();Me.default.install();var Fr=pe("path"),Eo=pe("os"),wo=pe("crypto"),ct=pe("net"),z=ot();vo(ot(),b);var Tn=class extends z.AbstractMessageReader{constructor(e){super(),this.process=e;let t=this.process;t.on("error",r=>this.fireError(r)),t.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),z.Disposable.create(()=>this.process.off("message",e))}};b.IPCMessageReader=Tn;var xn=class extends z.AbstractMessageWriter{constructor(e){super(),this.process=e,this.errorCount=0;let t=this.process;t.on("error",r=>this.fireError(r)),t.on("close",()=>this.fireClose)}write(e){try{return typeof this.process.send=="function"&&this.process.send(e,void 0,void 0,t=>{t?(this.errorCount++,this.handleError(t,e)):this.errorCount=0}),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}};b.IPCMessageWriter=xn;var On=class extends z.AbstractMessageReader{constructor(e){super(),this.onData=new z.Emitter,e.on("close",()=>this.fireClose),e.on("error",t=>this.fireError(t)),e.on("message",t=>{this.onData.fire(t)})}listen(e){return this.onData.event(e)}};b.PortMessageReader=On;var Ln=class extends z.AbstractMessageWriter{constructor(e){super(),this.port=e,this.errorCount=0,e.on("close",()=>this.fireClose()),e.on("error",t=>this.fireError(t))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}};b.PortMessageWriter=Ln;var he=class extends z.ReadableStreamMessageReader{constructor(e,t="utf-8"){super((0,Me.default)().stream.asReadableStream(e),t)}};b.SocketMessageReader=he;var ge=class extends z.WriteableStreamMessageWriter{constructor(e,t){super((0,Me.default)().stream.asWritableStream(e),t),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};b.SocketMessageWriter=ge;var at=class extends z.ReadableStreamMessageReader{constructor(e,t){super((0,Me.default)().stream.asReadableStream(e),t)}};b.StreamMessageReader=at;var dt=class extends z.WriteableStreamMessageWriter{constructor(e,t){super((0,Me.default)().stream.asWritableStream(e),t)}};b.StreamMessageWriter=dt;var Dr=process.env.XDG_RUNTIME_DIR,bo=new Map([["linux",107],["darwin",103]]);function So(){let n=(0,wo.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${n}-sock`;let e;Dr?e=Fr.join(Dr,`vscode-ipc-${n}.sock`):e=Fr.join(Eo.tmpdir(),`vscode-${n}.sock`);let t=bo.get(process.platform);return t!==void 0&&e.length>t&&(0,Me.default)().console.warn(`WARNING: IPC handle "${e}" is longer than ${t} characters.`),e}b.generateRandomPipeName=So;function ko(n,e="utf-8"){let t,r=new Promise((i,s)=>{t=i});return new Promise((i,s)=>{let a=(0,ct.createServer)(u=>{a.close(),t([new he(u,e),new ge(u,e)])});a.on("error",s),a.listen(n,()=>{a.removeListener("error",s),i({onConnected:()=>r})})})}b.createClientPipeTransport=ko;function Io(n,e="utf-8"){let t=(0,ct.createConnection)(n);return[new he(t,e),new ge(t,e)]}b.createServerPipeTransport=Io;function Ro(n,e="utf-8"){let t,r=new Promise((i,s)=>{t=i});return new Promise((i,s)=>{let a=(0,ct.createServer)(u=>{a.close(),t([new he(u,e),new ge(u,e)])});a.on("error",s),a.listen(n,"127.0.0.1",()=>{a.removeListener("error",s),i({onConnected:()=>r})})})}b.createClientSocketTransport=Ro;function Mo(n,e="utf-8"){let t=(0,ct.createConnection)(n,"127.0.0.1");return[new he(t,e),new ge(t,e)]}b.createServerSocketTransport=Mo;function Co(n){let e=n;return e.read!==void 0&&e.addListener!==void 0}function Po(n){let e=n;return e.write!==void 0&&e.addListener!==void 0}function _o(n,e,t,r){t||(t=z.NullLogger);let i=Co(n)?new at(n):n,s=Po(e)?new dt(e):e;return z.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,z.createMessageConnection)(i,s,t,r)}b.createMessageConnection=_o});var Nn=A((pa,jr)=>{"use strict";jr.exports=Ar()});var _e=ar(Nn(),1);import{parentPort as wi,workerData as Hs}from"node:worker_threads";var Fn=class{initialQueue=[];initialQueueResolvers=Promise.withResolvers();logWriter=null;writePromise=this.initialQueueResolvers.promise;setLogWriter(e){this.logWriter=e;for(let t of this.initialQueue)this.writePromise=this.logWriter.writeLog(t.method,t.message);this.initialQueue=[],this.initialQueueResolvers.resolve()}async flush(){await this.writePromise}async dispose(){await this.flush()}outputPath(){return this.logWriter?.outputPath()}logToLevel(e,t){this.logWriter?this.writePromise=this.logWriter.writeLog(e,t):this.initialQueue.push({method:e,message:t})}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,t){this.info(`--- Start of group: ${e} ---`)}endGroup(e){this.info("--- End of group ---")}},v=new Fn;function To(n){if(n.includes("<!DOCTYPE")||n.includes("<html")){let e=Math.min(n.indexOf("<!DOCTYPE")!==-1?n.indexOf("<!DOCTYPE"):1/0,n.indexOf("<html")!==-1?n.indexOf("<html"):1/0),t=n.substring(0,e).trim();return t?`${t} [HTML error page omitted]`:"[HTML error page omitted]"}return n}function w(n){let e;if(n instanceof Error)e=String(n);else if(typeof n=="object"&&n!==null)try{e=JSON.stringify(n)??"[object]"}catch{return"[object with circular reference]"}else e=String(n);return To(e)}var Ce=class extends Error{constructor(t,r,i){super(t,i);this.code=r;this.name="VoiceBackendError"}};function Dn(n){return n.code!==void 0?new Ce(n.message,n.code):new Error(n.message)}function lt(n){return n instanceof Error?n:new Error(String(n))}import{existsSync as An}from"node:fs";import{dirname as qr,join as jn}from"node:path";import{fileURLToPath as xo}from"node:url";function $r(n){let{importMetaUrl:e,filename:t,label:r}=n,i;try{i=qr(xo(e))}catch(E){throw new Error(`Voice ${r} worker bundle unavailable: cannot resolve module URL (${w(E)}).`)}let s=jn(i,t);if(An(s))return s;let a=Oo(i),u=a?jn(a,"dist-cli",t):void 0;if(u&&An(u))return u;let f=u?`${s}, ${u}`:s;throw new Error(`Voice ${r} worker bundle not found. Searched: ${f}`)}function Oo(n){let e=n;for(;;){if(An(jn(e,"package.json")))return e;let t=qr(e);if(t===e)return;e=t}}function Vr(n){if(typeof n=="string")return n;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}var qn=16*1024;function $n(n,e,t=v){let r=Lo(n.level)?n.level:"info",i=typeof n.message=="string"?n.message:Vr(n.message);t[r](`[${e} worker] ${No(i)}`)}function Lo(n){return n==="debug"||n==="info"||n==="warning"||n==="error"}function No(n){return n.length<=qn?n:`${n.slice(0,qn)}\u2026 [truncated, ${n.length-qn} more chars]`}import{Worker as Fo}from"node:worker_threads";var Wr=(n,e)=>new Fo(n,e);import{createRequire as Ao}from"node:module";import*as le from"node:fs/promises";import*as G from"node:path";import{createHash as jo}from"node:crypto";import{join as $e,basename as Na}from"node:path";import{homedir as Vn}from"node:os";function Do(){return process.env.XDG_CACHE_HOME||$e(Vn(),".cache")}function Ur(){if(process.platform==="darwin")return $e(Vn(),"Library","Caches","copilot");if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||$e(Vn(),".cache");return $e(n,"copilot")}return $e(Do(),"copilot")}var qo=1,$o=".complete";var zr={"win32-x64":"win-x64","win32-arm64":"win-arm64","linux-x64":"linux-x64","darwin-arm64":"osx-arm64"};function Vo(){return typeof __foundryRequire<"u"&&__foundryRequire||Ao(import.meta.url)}var ut;function Wo(){if(ut)return ut;try{let n=Vo()("foundry-local-sdk/deps_versions.json");if(typeof n["foundry-local-core"]?.nuget!="string"||typeof n.onnxruntime?.version!="string"||typeof n["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 ut=n,ut}catch(n){throw new Error(`Failed to load foundry-local-sdk/deps_versions.json: ${w(n)}. 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 Uo(n=process.platform){let e=Wo();return[{name:"Microsoft.AI.Foundry.Local.Core",version:e["foundry-local-core"].nuget},{name:n==="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 Jr(n){return n==="win32"?".dll":n==="darwin"?".dylib":".so"}function Ho(n,e){return G.join(n,`Microsoft.AI.Foundry.Local.Core${Jr(e)}`)}function Bo(n){let e=Jr(n),t=n==="win32"?"":"lib";return[`Microsoft.AI.Foundry.Local.Core${e}`,`${t}onnxruntime${e}`,`${t}onnxruntime-genai${e}`]}function zo(n,e=process.platform,t=process.arch){let r=zr[`${e}-${t}`];if(!r)throw new Error(`Voice mode not supported on ${e}-${t}`);let i=n??process.env.COPILOT_CACHE_HOME??Ur(),s=Uo(e),a=jo("sha256").update(JSON.stringify({schema:qo,artifacts:s})).digest("hex").slice(0,12);return G.join(i,"foundry",a,r)}async function Gr(n={}){let e=n.platform??process.platform,t=n.arch??process.arch,r=`${e}-${t}`,i=zr[r];if(!i)return{kind:"unsupported-platform",platformKey:r};let s=zo(n.cacheRoot,e,t),a=Bo(e);if(await Hr(s,a))return{kind:"downloaded",location:{corePath:Ho(s,e)}};let u=G.dirname(G.dirname(s)),f;try{f=await le.readdir(u)}catch{return{kind:"not-downloaded"}}let E=G.basename(G.dirname(s));for(let D of f){if(D===E)continue;let W=G.join(u,D,i);if(await Hr(W,a))return{kind:"update-available"}}return{kind:"not-downloaded"}}async function Hr(n,e){return await Br(G.join(n,$o))?(await Promise.all(e.map(r=>Br(G.join(n,r))))).every(Boolean):!1}async function Br(n){try{return await le.access(n),!0}catch{return!1}}var Kr=5e3;function Qr(n={}){let{cacheRoot:e,workerFactory:t=Wr,workerScriptPath:r,inspectImpl:i=Gr}=n,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()+Kr},u},install(u){if(s)return s;a=void 0;let f=Jo({cacheRoot:e,workerFactory:t,workerScriptPath:r??$r({importMetaUrl:import.meta.url,filename:"voice-installer.worker.js",label:"installer"}),onProgress:u}).then(E=>(a={result:{kind:"downloaded",location:E},expiry:Date.now()+Kr},E)).catch(E=>{throw s=void 0,a=void 0,E});return s=f,f}}}function Jo(n){return new Promise((e,t)=>{let r;try{r=n.workerFactory(n.workerScriptPath,{workerData:{cacheRoot:n.cacheRoot}})}catch(a){t(lt(a));return}let i=!1,s=a=>{i||(i=!0,r.terminate().catch(u=>{v.warning(`[voice-runtime] installer worker terminate failed: ${w(u)}`)}),a())};r.on("message",a=>{if(a==null||typeof a!="object"){v.warning("[voice-runtime] installer worker posted a malformed message; ignoring");return}let u=a;if(u.kind==="log"){$n(u,"Installer");return}if(u.kind==="download-started"){if(!n.onProgress)return;try{n.onProgress({kind:"indeterminate"})}catch(f){v.warning(`[voice-runtime] installer onProgress threw: ${w(f)}`)}return}if(u.kind==="ok"){s(()=>e(u.location));return}if(u.kind==="error"){s(()=>t(Dn(u.error)));return}}),r.on("error",a=>{s(()=>t(lt(a)))}),r.on("exit",a=>{s(()=>t(new Error(`Voice installer worker exited unexpectedly with code ${a}.`)))})})}var Zr=ar(Nn(),1);var Yr="$/shutdown",Xr=["setEnabled","selectModel","downloadModel","cancelDownload","deleteModel","installRuntime","refreshCatalog","openSession","finishSession","acknowledgeOperationError"];function Ko(n,e,t,r){return{...typeof e=="object"&&e!==null?e:{},type:`rpc:${n}`,connectionId:t,requestId:r}}var pt=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 t of Xr)this.connection.onRequest(t,r=>this.dispatchRpc(t,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 t of e)t()}send(e){if(this.disposed)return;let{type:t,...r}=e;this.connection.sendNotification(t,r).catch(()=>{})}resolveRpc(e,t){if(this.disposed)return;let r=this.pending.get(e);r&&(this.pending.delete(e),r.resolve(t))}rejectRpc(e,t){if(this.disposed)return;let r=this.pending.get(e);r&&(this.pending.delete(e),r.reject(new Zr.ResponseError(1,`Engine RPC rejected: ${t.code}`,{reason:t})))}onClose(e){return this.closeHandlers.add(e),()=>{this.closeHandlers.delete(e)}}dispatchRpc(e,t){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(Ko(e,t,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 t=[...this.pending.values()];this.pending.clear();for(let r of t)r.reject(e)}};var ei="main",ft=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 t=e.connectionId??this.generateConnectionId();if(this.peers.has(t))throw new Error(`EngineRpcHost: connection id "${t}" already registered.`);let r=new pt({connection:e.connection,connectionId:t,submit:this.submit});this.peers.set(t,r),r.onClose(()=>{if(this.peers.get(t)===r){this.peers.delete(t);for(let i of this.disconnectedHandlers)i(t)}});try{r.attach();for(let i of this.connectedHandlers)i(t)}catch(i){this.peers.delete(t);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 t of e)try{t.dispose()}catch{}}broadcast(e){if(!this.disposed)for(let t of this.peers.values())t.send(e)}sendTo(e,t){this.disposed||this.peers.get(e)?.send(t)}resolveRpc(e,t,r){this.disposed||this.peers.get(e)?.resolveRpc(t,r)}rejectRpc(e,t,r){this.disposed||this.peers.get(e)?.rejectRpc(t,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++}`}};async function ti(n,e){try{return await n()}catch(t){if((e?.platform??process.platform)!=="win32")throw t;let i=w(t);if(!/Failed to load (?:dependency|core) library/i.test(i))throw t;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 Ce(`Voice mode requires the Microsoft Visual C++ Redistributable (2015-2022). Download and install it, then try again: ${a}`,"windows-runtime-missing",{cause:t})}}var Wn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};function Ve(n,e,t){let r,i=new Promise((s,a)=>{r=setTimeout(()=>a(new Wn(t)),e)});return Promise.race([n,i]).finally(()=>{r&&clearTimeout(r)})}var ni="nemotron-speech-streaming-en-0.6b",ri=new Set([ni,"nemotron-speech-streaming-es-0.6b"]);function ii(n){return n.find(e=>e.inCatalog&&e.alias===ni)}var Qo="github-copilot-cli",Yo="automatic-speech-recognition",Xo={AzureCatalogFilter:"'',test"},oi=1e4,si=2e3,ht=class{events;installer;managerFactory;liveSessionFactory;nativeLocation;managerPromise;downloads=new Map;loaded=null;sessions=new Map;outstandingTeardowns=new Set;disposed=!1;constructor(e){this.events=e.events,this.installer=e.installer,this.managerFactory=e.managerFactory,this.liveSessionFactory=e.liveSessionFactory}checkRuntime(e){this.runCheckRuntime(e)}async runCheckRuntime(e){try{if(this.managerFactory){this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"});return}let t=await this.installer.inspect();t.kind==="downloaded"?(this.nativeLocation=t.location,this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"})):t.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(t){v.error(`[voice-engine] checkRuntime failed: ${w(t)}`),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)Zo(a)&&ri.has(a.alias)&&i.push(ts(a));this.events.submit({type:"internal:catalogFetched",generation:e,models:i})}catch(t){let r=w(t);v.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 t=await this.installer.install();this.nativeLocation=t,this.events.submit({type:"internal:runtimeInstalled",generation:e})}catch(t){let r=w(t);v.error(`[voice-engine] installRuntime failed: ${r}`),this.events.submit({type:"internal:runtimeInstallFailed",generation:e,reason:r})}}downloadModel(e,t){let r=this.downloads.get(e);if(r&&!r.abortController.signal.aborted){r.generations.add(t);return}let i=new Set([t]),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 t=this.downloads.get(e);t&&t.abortController.abort()}async runDownload(e,t,r){try{await(await this.getVariant(e)).download(s=>{for(let a of t)try{this.events.submit({type:"internal:modelDownloadProgress",generation:a,variantId:e,percent:s})}catch(u){v.warning(`[voice-engine] download progress callback threw: ${w(u)}`)}},r);for(let s of t)this.events.submit({type:"internal:modelDownloaded",generation:s,variantId:e})}catch(i){if(r.aborted)for(let s of t)this.events.submit({type:"internal:modelDownloadCancelled",generation:s,variantId:e});else{let s=w(i);v.error(`[voice-engine] downloadModel '${e}' failed: ${s}`);for(let a of t)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,t){this.runLoad(e,t)}async runLoad(e,t){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&&v.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:t,variantId:e})}catch(r){let i=w(r);v.error(`[voice-engine] loadModel '${e}' failed: ${i}`),this.events.submit({type:"internal:modelLoadFailed",generation:t,variantId:e,reason:i})}}unloadModel(e){this.runUnload(e)}async runUnload(e){let t=this.loaded&&this.loaded.variantId===e?this.loaded:null;if(t&&(this.loaded=null),!t){this.events.submit({type:"internal:modelUnloaded",variantId:e});return}try{await t.variant.unload(),this.events.submit({type:"internal:modelUnloaded",variantId:e})}catch(r){let i=w(r);v.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,t){if(this.disposed)return{ok:!1,subreason:"session-open-failed"};if(this.sessions.has(e))return v.warning(`[voice-engine] openSttSession(${e}): sessionId already in use`),{ok:!1,subreason:"session-open-failed"};let r=this.loaded&&this.loaded.variantId===t?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,t,r){let i;try{i=await this.openStreamingSession(e,t.variant)}catch(a){return v.error(`[voice-engine] openSttSession(${e}) failed: ${w(a)}`),this.sessions.get(e)===r&&this.sessions.delete(e),{ok:!1,subreason:r.cancelled?"cancelled":"session-open-failed"}}let s=this.sessions.get(e);return s!==r||r.cancelled?(s===r&&this.sessions.delete(e),this.trackTeardown(this.teardownSession(i).catch(a=>v.warning(`[voice-engine] orphan teardown(${e}) failed: ${w(a)}`))),{ok:!1,subreason:"cancelled"}):(this.sessions.set(e,{phase:"active",session:i}),i.drainTask=this.runStreamingDrain(i),{ok:!0})}appendSttPcm(e,t){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(t);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 t=this.sessions.get(e);if(!t)return;if(t.phase==="opening"){t.cancelled=!0,this.sessions.delete(e);return}let r=t.session;this.sessions.delete(e),this.trackTeardown(this.runEnd(r))}async runEnd(e){let t=e.sessionId;try{if(e.error){this.events.submit({type:"internal:sttError",sessionId:t,subreason:"drain-failed"});return}let r;try{r=await this.stopStreaming(e)}catch(i){v.error(`[voice-engine] runEnd(${t}) failed: ${w(i)}`),this.events.submit({type:"internal:sttError",sessionId:t,subreason:"drain-failed"});return}if(e.error){this.events.submit({type:"internal:sttError",sessionId:t,subreason:"drain-failed"});return}this.events.submit({type:"internal:sttFinal",sessionId:t,text:r})}finally{await this.teardownSession(e).catch(r=>v.warning(`[voice-engine] teardown(${t}) failed: ${w(r)}`))}}cancelSttSession(e){if(this.disposed)return;let t=this.sessions.get(e);if(!t)return;if(t.phase==="opening"){t.cancelled=!0,this.sessions.delete(e);return}let r=t.session;r.cancelled=!0,this.sessions.delete(e),this.trackTeardown(this.runCancel(r))}async runCancel(e){try{await this.disposeSdk(e.sdk)}catch(t){v.warning(`[voice-engine] runCancel(${e.sessionId}) teardown: ${w(t)}`)}}trackTeardown(e){this.outstandingTeardowns.add(e),e.finally(()=>this.outstandingTeardowns.delete(e)).catch(()=>{})}failSession(e,t,r){if(e.error)return;let i=r instanceof Error?r:new Error(String(r));e.error=i,v.error(`[voice-engine] session(${e.sessionId}) failed: ${w(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:t}),this.trackTeardown(this.teardownSession(e).catch(a=>v.warning(`[voice-engine] failSession teardown: ${w(a)}`))))}async openStreamingSession(e,t){let r=this.liveSessionFactory?await this.liveSessionFactory(t):t.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 t of e.sdk.getStream()){if(e.cancelled||e.error)break;let r=es(t);r&&(t.is_final?(e.committed+=r,e.tail=""):e.tail+=r,this.events.onSttPartial(e.sessionId,e.committed+e.tail))}}catch(t){this.failSession(e,"drain-failed",t)}}async stopStreaming(e){return await Ve(e.sdk.stop(),oi,"Streaming session stop timed out."),await Ve(e.drainTask,oi,"Streaming session drain timed out."),e.committed+e.tail}async teardownSession(e){await this.disposeSdk(e.sdk)}async disposeSdk(e){await Ve(e.dispose(),si,"SDK dispose timed out.").catch(()=>{})}async dispose(){if(!this.disposed){this.disposed=!0;for(let[e,t]of this.sessions)if(t.phase==="opening")t.cancelled=!0,this.sessions.delete(e);else{let r=t.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 Ve(e.variant.unload(),si,"variant.unload timed out").catch(t=>{v.error(`[voice-engine] dispose: variant.unload failed: ${w(t)}`)})}}}async runDelete(e){try{(await this.getVariant(e)).removeFromCache()}catch(t){v.error(`[voice-engine] deleteModel '${e}' failed: ${w(t)}`)}}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 ti(async()=>pe("foundry-local-sdk").FoundryLocalManager.createAsync({appName:Qo,libraryPath:e.corePath,additionalSettings:{...Xo}}))}};function Zo(n){return n.info.task===Yo}function es(n){return n.content?.[0]?.text??""}function ts(n){let e=n.info,t=n.info.runtime?.deviceType??e.device,r=t?t.toLowerCase():void 0,i=e.sizeInBytes??(typeof n.info.fileSizeMb=="number"?Math.round(n.info.fileSizeMb*1024*1024):void 0);return{variantId:n.id,displayName:n.info.name??n.id,alias:n.alias,sizeBytes:i,device:r,cached:n.isCached,inCatalog:!0}}var ns=1600,rs=15,ai=-1,di=150,gt=class{events;pvRecorderLoader;state={tag:"idle"};disposed=!1;constructor(e){this.events=e.events,this.pvRecorderLoader=e.pvRecorderLoader??(async()=>pe("@picovoice/pvrecorder-node"))}openForSession(e){if(this.disposed)return Promise.resolve({ok:!1,subreason:"cancelled"});let t=this.state;switch(t.tag){case"idle":return this.beginStart(e,void 0);case"stopping":return this.beginStart(e,t.teardown);case"starting":case"active":return v.error(`[voice-mic] openForSession(${e}) while ${t.tag} for session ${t.sessionId} \u2014 engine contract violation`),Promise.resolve({ok:!1,subreason:"in-use"});default:return t}}beginStart(e,t){let r,i=new Promise(u=>{r=u}),s={stopped:!1,commitDrain:!1,resolveOpen:r},a=(async()=>{t&&await t.catch(()=>{}),await this.runStart(e,ai,s)})();return this.state={tag:"starting",sessionId:e,deviceId:ai,cancel:s,startTask:a},i}closeSession(e){let t=this.state;switch(t.tag){case"idle":case"stopping":return t.tag==="stopping"?t.teardown:Promise.resolve();case"starting":{t.cancel.stopped=!0,t.cancel.resolveOpen({ok:!1,subreason:"cancelled"});let r=t.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=t.cancel,i=t.recorder,s=t.loop;e==="discard"?(r.stopped=!0,Q(()=>i.stop())):r.commitDrain=!0;let a=(async()=>{e==="commit"&&(await Promise.race([s,li(di)]).catch(()=>{}),r.stopped=!0,Q(()=>i.stop())),await Promise.race([s,li(di)]).catch(()=>{}),Q(()=>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 t}}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,Q(()=>e.recorder.stop()),await e.loop.catch(()=>{}),Q(()=>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,t,r){if(r.stopped||this.disposed){this.exitCancelled(r);return}let i;try{i=await this.pvRecorderLoader()}catch(u){v.error(`[voice-mic] pvrecorder-node load failed: ${w(u)}`),this.failOpen(r,"hardware-error");return}if(r.stopped||this.disposed){this.exitCancelled(r);return}let s;try{s=new i.PvRecorder(ns,t,rs),s.start()}catch(u){if(s!==void 0){let f=s;Q(()=>f.stop()),Q(()=>f.release())}this.failOpen(r,ci(u));return}if(r.stopped||this.disposed){Q(()=>s.stop()),Q(()=>s.release()),this.exitCancelled(r);return}let a=this.runReadLoop(s,e,r);this.state={tag:"active",sessionId:e,deviceId:t,cancel:r,recorder:s,loop:a},r.resolveOpen({ok:!0})}failOpen(e,t){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:t})}exitCancelled(e){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:"cancelled"})}async runReadLoop(e,t,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"}),Q(()=>e.stop()),Q(()=>e.release());let u=ci(a);v.error(`[voice-mic] read loop failed (${u}): ${w(a)}`),this.disposed||this.events.submit({type:"internal:micError",sessionId:t,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(t,s),r.commitDrain)return}}};function ci(n){switch(n?.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 li(n){return new Promise(e=>setTimeout(e,n))}function Q(n){try{n()}catch{}}function is(n){return{state:n.state,enabled:n.enabled,selectedTarget:n.selectedTarget,models:n.models.map(e=>({...e})),catalogStatus:n.catalogStatus,inFlightDownloads:n.inFlightDownloads.map(e=>({...e})),session:n.session?{...n.session}:null,lastOperationError:n.lastOperationError?{...n.lastOperationError}:null}}function os(n){return{generations:{runtimeInstall:n.generations.runtimeInstall,runtimeCheck:n.generations.runtimeCheck,downloadByVariant:new Map(n.generations.downloadByVariant),catalogFetch:n.generations.catalogFetch},nextLoadGeneration:n.nextLoadGeneration,modelLoad:{...n.modelLoad},currentSession:n.currentSession?{...n.currentSession}:null,clientEnabled:n.clientEnabled,pendingDelete:n.pendingDelete?{...n.pendingDelete}:null}}function mt(n,e){n.enabled=e.clientEnabled}function Pe(n,e){return n.models.find(t=>t.variantId===e)}function ui(n,e){let t=Pe(n,e);return!!t&&(t.inCatalog||t.cached)}function pi(n,e){let t=Pe(n,e);return!!t&&t.cached}function Un(n){return n.currentSession!==null}function ss(n,e){n.session=e.currentSession?{id:e.currentSession.id,status:e.currentSession.status}:null}function Hn(n,e){let r=(n.generations.downloadByVariant.get(e)??0)+1;return n.generations.downloadByVariant.set(e,r),r}function yt(n,e){return n.generations.downloadByVariant.get(e)??0}function as(n,e,t){n.pendingFinishReply&&(t.push({type:"replyResolve",connectionId:n.pendingFinishReply.connectionId,requestId:n.pendingFinishReply.requestId,result:e}),n.pendingFinishReply=void 0)}function Y(n,e,t,r){let i=e.currentSession;i&&(r.push({type:"cancelSession",sessionId:i.id}),as(i,t,r),e.currentSession=null,n.session=null)}function ds(n,e,t){let r=n.state.kind;if(r!=="no-model"&&r!=="downloading"&&r!=="loading"&&r!=="ready")return;if(r==="no-model"&&n.selectedTarget===null&&n.catalogStatus==="ok"){let f=ii(n.models);f?.cached&&(n.selectedTarget=f.variantId)}let i=n.selectedTarget,s=n.enabled&&i!==null&&ui(n,i)?i:null,a=e.modelLoad;if(a.kind==="loading"||a.kind==="unloading")return;if(s===null){a.kind==="loaded"&&(t.push({type:"unloadModel",variantId:a.variantId}),e.modelLoad={kind:"unloading",variantId:a.variantId});return}if(a.kind==="loaded"){if(a.variantId===s){(n.state.kind!=="ready"||n.state.variantId!==s)&&(n.state={kind:"ready",variantId:s});return}t.push({type:"unloadModel",variantId:a.variantId}),e.modelLoad={kind:"unloading",variantId:a.variantId};return}if(pi(n,s)){let f=++e.nextLoadGeneration;e.modelLoad={kind:"loading",variantId:s,generation:f},n.state={kind:"loading",variantId:s},t.push({type:"loadModel",variantId:s,generation:f});return}if((n.state.kind!=="downloading"||n.state.variantId!==s)&&(n.state={kind:"downloading",variantId:s}),!n.inFlightDownloads.some(f=>f.variantId===s)){let f=Hn(e,s);n.inFlightDownloads.push({variantId:s}),t.push({type:"downloadModel",variantId:s,generation:f})}}function fi(n){return n.kind==="starting"||n.kind==="runtime-missing"||n.kind==="installing-runtime"||n.kind==="fetching-catalog"||n.kind==="failed"}function hi(n,e,t){let r=is(n),i=os(e),a=cs(r,i,t,[]);return ds(a.snapshot,a.internal,a.effects),ss(a.snapshot,a.internal),a}function cs(n,e,t,r){switch(t.type){case"boot":return ls(n,e,t,r);case"shutdown":return us(n,e,r);case"rpc:setEnabled":return ps(n,e,t,r);case"rpc:selectModel":return fs(n,e,t,r);case"rpc:downloadModel":return hs(n,e,t,r);case"rpc:cancelDownload":return gs(n,e,t,r);case"rpc:deleteModel":return ms(n,e,t,r);case"rpc:installRuntime":return ys(n,e,t,r);case"rpc:refreshCatalog":return vs(n,e,t,r);case"rpc:openSession":return Es(n,e,t,r);case"rpc:finishSession":return ws(n,e,t,r);case"rpc:acknowledgeOperationError":return bs(n,e,t,r);case"internal:catalogFetched":return Ss(n,e,t,r);case"internal:catalogFetchFailed":return ks(n,e,t,r);case"internal:runtimeChecked":return Is(n,e,t,r);case"internal:runtimeInstalled":return Rs(n,e,t,r);case"internal:runtimeInstallFailed":return Ms(n,e,t,r);case"internal:modelDownloadProgress":return Cs(n,e,t,r);case"internal:modelDownloaded":return Ps(n,e,t,r);case"internal:modelDownloadCancelled":return _s(n,e,t,r);case"internal:modelDownloadFailed":return Ts(n,e,t,r);case"internal:modelLoaded":return xs(n,e,t,r);case"internal:modelLoadFailed":return Os(n,e,t,r);case"internal:modelUnloaded":return Ls(n,e,t,r);case"internal:modelUnloadFailed":return Ns(n,e,t,r);case"internal:micError":return js(n,e,t,r);case"internal:sessionWarmed":return Fs(n,e,t,r);case"internal:sessionWarmupFailed":return Ds(n,e,t,r);case"internal:sttFinal":return qs(n,e,t,r);case"internal:sttError":return $s(n,e,t,r);case"client:disconnected":return Vs(n,e,t,r)}}function p(n,e,t){return{snapshot:n,internal:e,effects:t}}function ls(n,e,t,r){e.clientEnabled=t.bootEnabled,mt(n,e),n.selectedTarget=t.bootSelectedModel,n.state={kind:"starting"};let i=++e.generations.runtimeCheck;return r.push({type:"checkRuntime",generation:i}),p(n,e,r)}function us(n,e,t){Y(n,e,{kind:"lost",reason:"engine-disabled"},t);for(let r of n.inFlightDownloads)Hn(e,r.variantId);return n.inFlightDownloads=[],e.generations.runtimeInstall++,e.generations.runtimeCheck++,e.generations.catalogFetch++,n.state={kind:"failed",reason:"shutdown"},p(n,e,t)}function ps(n,e,t,r){let i=e.clientEnabled;e.clientEnabled=t.enabled,mt(n,e);let s=n.enabled;return i&&!s&&(Y(n,e,{kind:"lost",reason:"engine-disabled"},r),(n.state.kind==="downloading"||n.state.kind==="loading"||n.state.kind==="ready")&&(n.state={kind:"no-model"})),!i&&s&&n.state.kind==="model-failed"&&(n.state={kind:"no-model"},n.lastOperationError=null),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)}function fs(n,e,t,r){return fi(n.state)?(r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"runtime-not-ready"}}),p(n,e,r)):Un(e)?(r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"session-in-use"}}),p(n,e,r)):ui(n,t.variantId)?(e.clientEnabled=!0,mt(n,e),n.state.kind==="model-failed"&&(n.state={kind:"no-model"}),t.variantId===n.selectedTarget&&n.enabled?(r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)):(n.selectedTarget=t.variantId,n.lastOperationError=null,n.state.kind==="downloading"&&n.state.variantId!==t.variantId&&(n.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r))):(r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"model-not-found",variantId:t.variantId}}),p(n,e,r))}function hs(n,e,t,r){if(fi(n.state))return r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"runtime-not-ready"}}),p(n,e,r);if(!Pe(n,t.variantId))return r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"model-not-found",variantId:t.variantId}}),p(n,e,r);if(pi(n,t.variantId))return r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r);if(!n.inFlightDownloads.some(s=>s.variantId===t.variantId)){let s=Hn(e,t.variantId);n.inFlightDownloads.push({variantId:t.variantId}),r.push({type:"downloadModel",variantId:t.variantId,generation:s})}return r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)}function gs(n,e,t,r){return n.inFlightDownloads.some(s=>s.variantId===t.variantId)&&(r.push({type:"cancelDownload",variantId:t.variantId}),e.generations.downloadByVariant.set(t.variantId,(e.generations.downloadByVariant.get(t.variantId)??0)+1),n.inFlightDownloads=n.inFlightDownloads.filter(s=>s.variantId!==t.variantId),n.selectedTarget===t.variantId&&(n.selectedTarget=null,n.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)}function ms(n,e,t,r){if(n.inFlightDownloads.some(D=>D.variantId===t.variantId))return r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"model-in-use"}}),p(n,e,r);if(t.variantId===n.selectedTarget&&Un(e))return r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"session-in-use"}}),p(n,e,r);let s=e.modelLoad;if((s.kind==="loading"||s.kind==="unloading")&&s.variantId===t.variantId)return r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"model-in-use"}}),p(n,e,r);let a=Pe(n,t.variantId),u=s.kind==="loaded"&&s.variantId===t.variantId,f=t.variantId===n.selectedTarget,E=n.state.kind==="model-failed"&&n.state.variantId===t.variantId;return u?e.pendingDelete={variantId:t.variantId}:(r.push({type:"deleteModel",variantId:t.variantId}),a&&(a.cached=!1)),(f||E)&&(n.selectedTarget=null,e.clientEnabled=!1,mt(n,e),(n.state.kind==="downloading"||n.state.kind==="loading"||n.state.kind==="ready"||n.state.kind==="model-failed")&&(n.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)}function ys(n,e,t,r){if(n.state.kind!=="runtime-missing")return r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"invalid-state"}}),p(n,e,r);let i=++e.generations.runtimeInstall;return n.state={kind:"installing-runtime",cacheState:n.state.cacheState},r.push({type:"installRuntime",generation:i}),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)}function vs(n,e,t,r){if((n.state.kind==="no-model"||n.state.kind==="downloading"||n.state.kind==="loading"||n.state.kind==="ready"||n.state.kind==="model-failed")&&n.catalogStatus!=="fetching"){let s=++e.generations.catalogFetch;n.catalogStatus="fetching",r.push({type:"fetchCatalog",generation:s})}return r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)}function Es(n,e,t,r){return n.enabled?Un(e)?(r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"session-in-use"}}),p(n,e,r)):n.selectedTarget?n.state.kind!=="ready"?(r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"runtime-not-ready"}}),p(n,e,r)):(e.currentSession={id:t.sessionId,ownerConnectionId:t.connectionId,status:"opening"},r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),r.push({type:"warmupSession",sessionId:t.sessionId,variantId:n.selectedTarget}),p(n,e,r)):(r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"invalid-state"}}),p(n,e,r)):(r.push({type:"replyReject",connectionId:t.connectionId,requestId:t.requestId,reason:{code:"engine-disabled"}}),p(n,e,r))}function ws(n,e,t,r){let i=e.currentSession;if(!(i!==null&&i.id===t.sessionId&&i.ownerConnectionId===t.connectionId)){let a=t.commit?{kind:"lost",reason:"unknown-session"}:{kind:"discarded"};return r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:a}),p(n,e,r)}return t.commit?i!==null&&i.status==="opening"?(Y(n,e,{kind:"lost",reason:"not-ready"},r),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:{kind:"lost",reason:"not-ready"}}),p(n,e,r)):i!==null&&i.pendingFinishReply?(r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:{kind:"lost",reason:"not-ready"}}),p(n,e,r)):(i!==null&&(i.pendingFinishReply={connectionId:t.connectionId,requestId:t.requestId}),r.push({type:"commitSession",sessionId:t.sessionId}),p(n,e,r)):(Y(n,e,{kind:"discarded"},r),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:{kind:"discarded"}}),p(n,e,r))}function bs(n,e,t,r){return n.lastOperationError=null,n.state.kind==="model-failed"&&(n.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:t.connectionId,requestId:t.requestId,result:void 0}),p(n,e,r)}function Ss(n,e,t,r){return t.generation!==e.generations.catalogFetch||(n.models=t.models.map(i=>({...i})),n.catalogStatus="ok",(n.state.kind==="starting"||n.state.kind==="fetching-catalog")&&(n.state={kind:"no-model"})),p(n,e,r)}function ks(n,e,t,r){return t.generation!==e.generations.catalogFetch||(n.catalogStatus="failed",(n.state.kind==="starting"||n.state.kind==="fetching-catalog")&&(n.state={kind:"no-model"})),p(n,e,r)}function Is(n,e,t,r){if(t.generation!==e.generations.runtimeCheck||n.state.kind!=="starting")return p(n,e,r);if(t.cacheState!=="installed")return n.state={kind:"runtime-missing",cacheState:t.cacheState},p(n,e,r);n.state={kind:"fetching-catalog"},n.catalogStatus="fetching";let i=++e.generations.catalogFetch;return r.push({type:"fetchCatalog",generation:i}),p(n,e,r)}function Rs(n,e,t,r){if(t.generation!==e.generations.runtimeInstall)return p(n,e,r);if(n.state.kind==="installing-runtime"){n.state={kind:"fetching-catalog"},n.catalogStatus="fetching";let i=++e.generations.catalogFetch;r.push({type:"fetchCatalog",generation:i})}return p(n,e,r)}function Ms(n,e,t,r){if(t.generation!==e.generations.runtimeInstall)return p(n,e,r);n.state.kind==="installing-runtime"&&(n.state={kind:"runtime-missing",cacheState:n.state.cacheState});let i={operation:"installRuntime",reason:t.reason};n.lastOperationError=i;let s={type:"operationError",error:i};return r.push({type:"broadcast",event:s}),p(n,e,r)}function Cs(n,e,t,r){if(t.generation!==yt(e,t.variantId))return p(n,e,r);let i={type:"modelDownloadProgress",variantId:t.variantId,percent:t.percent};return r.push({type:"broadcast",event:i}),p(n,e,r)}function Ps(n,e,t,r){if(t.generation!==yt(e,t.variantId))return p(n,e,r);n.inFlightDownloads=n.inFlightDownloads.filter(s=>s.variantId!==t.variantId);let i=Pe(n,t.variantId);return i?i.cached=!0:n.models.push({variantId:t.variantId,displayName:t.variantId,cached:!0,inCatalog:!1}),p(n,e,r)}function _s(n,e,t,r){return t.generation!==yt(e,t.variantId)||(n.inFlightDownloads=n.inFlightDownloads.filter(i=>i.variantId!==t.variantId),n.state.kind==="downloading"&&n.state.variantId===t.variantId&&(n.selectedTarget=null,n.state={kind:"no-model"})),p(n,e,r)}function Ts(n,e,t,r){if(t.generation!==yt(e,t.variantId))return p(n,e,r);n.inFlightDownloads=n.inFlightDownloads.filter(a=>a.variantId!==t.variantId),n.state.kind==="downloading"&&n.state.variantId===t.variantId&&(n.selectedTarget=null,n.state={kind:"model-failed",variantId:t.variantId,reason:t.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelDownloadFailed (sessionId=${e.currentSession.id}, variantId=${t.variantId})`}),Y(n,e,{kind:"lost",reason:"engine-disabled"},r)));let i={operation:"downloadModel",reason:t.reason,variantId:t.variantId};n.lastOperationError=i;let s={type:"operationError",error:i};return r.push({type:"broadcast",event:s}),p(n,e,r)}function xs(n,e,t,r){let i=e.modelLoad;return i.kind!=="loading"||i.generation!==t.generation||i.variantId!==t.variantId?(r.push({type:"unloadModel",variantId:t.variantId}),p(n,e,r)):(e.modelLoad={kind:"loaded",variantId:t.variantId},n.enabled&&n.selectedTarget===t.variantId&&(n.state={kind:"ready",variantId:t.variantId},n.lastOperationError=null),p(n,e,r))}function Os(n,e,t,r){let i=e.modelLoad;if(i.kind!=="loading"||i.generation!==t.generation||i.variantId!==t.variantId)return p(n,e,r);e.modelLoad={kind:"unloaded"},n.selectedTarget=null,n.state={kind:"model-failed",variantId:t.variantId,reason:t.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelLoadFailed (sessionId=${e.currentSession.id}, variantId=${t.variantId})`}),Y(n,e,{kind:"lost",reason:"engine-disabled"},r));let s={operation:"loadModel",reason:t.reason,variantId:t.variantId};n.lastOperationError=s;let a={type:"operationError",error:s};return r.push({type:"broadcast",event:a}),p(n,e,r)}function Ls(n,e,t,r){let i=e.modelLoad;if(i.kind!=="unloading"||i.variantId!==t.variantId)return p(n,e,r);if(e.modelLoad={kind:"unloaded"},e.pendingDelete&&e.pendingDelete.variantId===t.variantId){r.push({type:"deleteModel",variantId:t.variantId});let s=Pe(n,t.variantId);s&&(s.cached=!1),(n.state.kind==="ready"||n.state.kind==="loading"||n.state.kind==="downloading")&&n.state.variantId===t.variantId&&(n.state={kind:"no-model"}),e.pendingDelete=null}return p(n,e,r)}function Ns(n,e,t,r){let i={operation:"loadModel",reason:t.reason,variantId:t.variantId};n.lastOperationError=i;let s={type:"operationError",error:i};return r.push({type:"broadcast",event:s}),p(n,e,r)}function Fs(n,e,t,r){let i=e.currentSession;return!i||i.id!==t.sessionId||i.status==="opening"&&(i.status="active"),p(n,e,r)}function Ds(n,e,t,r){let i=e.currentSession;return!i||i.id!==t.sessionId||(As(i.ownerConnectionId,t.sessionId,t.failure,r),Y(n,e,{kind:"lost",reason:t.failure.side==="mic"?"mic-error":"stt-error"},r)),p(n,e,r)}function As(n,e,t,r){let i=t.side==="mic"?{type:"micError",sessionId:e,subreason:t.subreason}:{type:"sttError",sessionId:e,subreason:t.subreason};r.push({type:"sendTo",connectionId:n,event:i})}function js(n,e,t,r){let i=e.currentSession;if(!i||i.id!==t.sessionId)return p(n,e,r);let s={type:"micError",sessionId:t.sessionId,subreason:t.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:s}),Y(n,e,{kind:"lost",reason:"mic-error"},r),p(n,e,r)}function qs(n,e,t,r){let i=e.currentSession;if(!i||i.id!==t.sessionId)return p(n,e,r);let s=i.pendingFinishReply?{kind:"committed",text:t.text}:{kind:"discarded"};return Y(n,e,s,r),p(n,e,r)}function $s(n,e,t,r){let i=e.currentSession;if(!i||i.id!==t.sessionId)return p(n,e,r);let s={type:"sttError",sessionId:t.sessionId,subreason:t.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:s}),Y(n,e,{kind:"lost",reason:"stt-error"},r),p(n,e,r)}function Vs(n,e,t,r){let i=e.currentSession;return i&&i.ownerConnectionId===t.connectionId&&Y(n,e,{kind:"lost",reason:"engine-disabled"},r),p(n,e,r)}function gi(){return{state:{kind:"starting"},enabled:!1,selectedTarget:null,models:[],catalogStatus:"ok",inFlightDownloads:[],session:null,lastOperationError:null}}function mi(){return{generations:{runtimeInstall:0,runtimeCheck:0,downloadByVariant:new Map,catalogFetch:0},nextLoadGeneration:0,modelLoad:{kind:"unloaded"},currentSession:null,clientEnabled:!1,pendingDelete:null}}function yi(n={}){let e=n.attackMs??12,t=n.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 f=Math.min(a,u+r),E=0;for(let J=u;J<f;J++){let X=s[J*2],H=(s[J*2+1]<<8|X)<<16>>16,R=H<0?-H:H;R>E&&(E=R)}let D=E/32768,W=Math.min(1,Math.sqrt(D)),ee=(f-u)/16e3*1e3,ne=W>i?e:t,Te=1-Math.exp(-ee/Math.max(.001,ne));i=i+(W-i)*Te}},current(){return i},reset(){i=0}}}function Ws(n){throw new Error(`Unhandled EngineEffect type: ${n.type}`)}var vi=64,vt=class{snapshot;internal;host;foundry;mic;unsubscribeConnected;unsubscribeDisconnected;disposed=!1;dispatchDepth=0;levelMeter;constructor(e){this.snapshot=gi(),this.internal=mi(),this.host=e.host,this.levelMeter=yi(),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(t=>{e.host.sendTo(t,{type:"initialize",snapshot:this.snapshot})}),this.unsubscribeDisconnected=e.host.onClientDisconnected(t=>{this.submit({type:"client:disconnected",connectionId:t})})}buildFoundryEvents(){return{submit:e=>{this.submit(e)},onSttPartial:(e,t)=>{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:t})}catch(r){v.error(`[VoiceEngine] onSttPartial threw: ${w(r)}`)}}}}buildMicEvents(){return{submit:e=>{this.submit(e)},onPcmFrame:(e,t)=>{if(!this.disposed)try{let r=this.internal.currentSession;if(!r||r.id!==e||r.status!=="active")return;this.levelMeter.feed(t),this.foundry.appendSttPcm(e,t),r.pendingFinishReply||this.emitEnvelope(r.id,r.ownerConnectionId)}catch(r){v.error(`[VoiceEngine] onPcmFrame threw: ${w(r)}`)}}}}submit(e){if(!this.disposed){if(this.dispatchDepth>=vi){v.error(`[VoiceEngine] dispatch depth exceeded ${vi} for command '${e.type}'; dropping to avoid runaway recursion.`);return}this.dispatchDepth++;try{let t=this.snapshot,r=t.session?.status==="active"?t.session.id:null,{snapshot:i,internal:s,effects:a}=hi(this.snapshot,this.internal,e);this.snapshot=i,this.internal=s;for(let f of a)try{this.dispatch(f)}catch(E){v.error(`[VoiceEngine] dispatching effect '${f.type}' threw: ${w(E)}`)}let u=this.snapshot.session?.status==="active"?this.snapshot.session.id:null;r===null&&u!==null&&this.levelMeter.reset(),t!==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 t of e)t.status==="rejected"&&v.error(`[VoiceEngine] adapter dispose rejected: ${w(t.reason)}`)}emitEnvelope(e,t){try{this.host.sendTo(t,{type:"sessionAudio",sessionId:e,envelope:this.levelMeter.current()})}catch(r){v.error(`[VoiceEngine] emitEnvelope threw: ${w(r)}`)}}dispatch(e){switch(e.type){case"checkRuntime":this.foundry.checkRuntime(e.generation);break;case"fetchCatalog":this.foundry.fetchCatalog(e.generation);break;case"installRuntime":this.foundry.installRuntime(e.generation);break;case"downloadModel":this.foundry.downloadModel(e.variantId,e.generation);break;case"cancelDownload":this.foundry.cancelDownload(e.variantId);break;case"loadModel":this.foundry.loadModel(e.variantId,e.generation);break;case"unloadModel":this.foundry.unloadModel(e.variantId);break;case"deleteModel":this.foundry.deleteModel(e.variantId);break;case"warmupSession":{let{sessionId:t,variantId:r}=e,i;try{i=this.mic.openForSession(t)}catch(f){i=Promise.reject(f instanceof Error?f:new Error(String(f)))}let s=i.then(f=>(f.ok||this.foundry.cancelSttSession(t),f)),a;try{a=this.foundry.openSttSession(t,r)}catch(f){a=Promise.reject(f instanceof Error?f:new Error(String(f)))}let u=a.then(f=>(f.ok||this.mic.closeSession("discard").catch(()=>{}),f));Promise.all([s,u]).then(([f,E])=>{this.disposed||(f.ok&&E.ok?this.submit({type:"internal:sessionWarmed",sessionId:t}):f.ok?E.ok||this.submit({type:"internal:sessionWarmupFailed",sessionId:t,failure:{side:"stt",subreason:E.subreason}}):this.submit({type:"internal:sessionWarmupFailed",sessionId:t,failure:{side:"mic",subreason:f.subreason}}))},f=>{v.error(`[VoiceEngine] warmupSession(${t}) rejected: ${w(f)}`),!this.disposed&&this.submit({type:"internal:sessionWarmupFailed",sessionId:t,failure:{side:"stt",subreason:"session-open-failed"}})});break}case"cancelSession":this.mic.closeSession("discard").catch(()=>{}),this.foundry.cancelSttSession(e.sessionId);break;case"commitSession":{let t=e.sessionId;this.mic.closeSession("commit").then(()=>{this.disposed||this.foundry.endSttSession(t)},r=>{v.error(`[VoiceEngine] commitSession(${t}) drain rejected: ${w(r)}`),!this.disposed&&this.foundry.endSttSession(t)});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":v.warning(`[VoiceEngine] ${e.message}`);break;default:Ws(e)}}};if(!wi)throw new Error("voice-engine.worker.js must be loaded as a worker thread.");var bi=wi,Bs=Hs??{},Bn=class{constructor(e){this.connection=e}writeLog(e,t){return this.connection.sendNotification("log",{level:e,message:t}).catch(()=>{}),Promise.resolve()}outputPath(){return"<voice-engine-worker>"}},zs=new _e.PortMessageReader(bi),Js=new _e.PortMessageWriter(bi),zn=(0,_e.createMessageConnection)(zs,Js);v.setLogWriter(new Bn(zn));var Gs=Qr(),Et=new ft,Si=new vt({host:Et,foundryFactory:n=>new ht({events:n,installer:Gs}),micFactory:n=>new gt({events:n}),bootSettings:Bs});Et.setSubmit(n=>Si.submit(n));var Ei=!1,ki=()=>{Ei||(Ei=!0,Si.dispose().catch(n=>v.error(`[voice-worker] engine.dispose failed: ${n.message}`)).finally(()=>setImmediate(()=>process.exit(0))))};Et.onClientDisconnected(ki);zn.onNotification(Yr,ki);Et.registerConnection({connection:zn,connectionId:ei});