@neuvybe/jarvis 0.22.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +42 -42
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -178,25 +178,25 @@ Rules:
178
178
  Output exactly one line of strict JSON and nothing else:
179
179
  {"verdict":"done"|"mid_thought"|"hold_floor","confidence":<number 0..1>}
180
180
  confidence is your certainty in the verdict.
181
- `,Yt=class extends Error{status;constructor(e,n){super(e),this.status=n,this.name="TurnEvaluatorError"}},bn=class{key;fetchImpl;timeoutMs;constructor(e,n=fetch,i=2e3){this.key=e,this.fetchImpl=n,this.timeoutMs=i}async evaluate(e,n){let i={model:RO,max_tokens:64,temperature:0,stop_sequences:LO,system:jO,messages:[{role:"user",content:MO(e)},{role:"assistant",content:jx}]},r=await this.fetchImpl(NO,{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":DO,"content-type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.any([n,AbortSignal.timeout(this.timeoutMs)])});if(!r.ok)throw new Yt(`turn evaluator request failed (HTTP ${r.status})`,r.status);let o;try{o=await r.json()}catch{throw new Yt("turn evaluator response body was not JSON")}return FO(o)}}});var Mx,Qp,em=v(()=>{"use strict";Mx="21m00Tcm4TlvDq8ikWAM",Qp={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:Mx}}}});var wa,Fx=v(()=>{"use strict";Ae();wa=class{turnId;openedAtMs;log;terminal=!1;heldOpen=!1;asideCommit=!1;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,n,i=B){this.turnId=e,this.openedAtMs=n,this.log=i}endpointerCommitted(e,n){this.decider===null&&(this.decider=e,this.silenceOnsetAtMs=n)}smartTurnResolved(e,n,i){this.log.debug("smart-turn P(complete)",{turnId:this.turnId,probability:e,inferenceMs:n,outcome:i})}smartTurnDegraded(e,n){this.log.debug("smart-turn DEGRADED to baseline - inference failed; this turn endpoints on baseline timers only",{turnId:this.turnId,inferenceMs:e,error:n instanceof Error?n.message:String(n)})}strongHoldRecognized(e){this.log.debug("lexical STRONG hold recognized - completeness vetoed, silence budget biases long",{turnId:this.turnId,cue:e})}heldEntered(e){this.heldOpen=!0,this.log.debug("floor-held mode entered - silence budgets escalate, stop cap suspended",{turnId:this.turnId,cue:e})}heldLadderRearmed(e){this.log.debug("held silence budget re-armed at the next ladder step",{turnId:this.turnId,budgetMs:e})}heldExited(e){this.heldOpen=!1,this.log.debug("floor-held mode exited",{turnId:this.turnId,reason:e})}evaluatorFired(e){this.log.debug("semantic evaluator fired - smart-turn resolved in a gated band during a live silence episode",{turnId:this.turnId,band:e})}evaluatorResolved(e,n,i,r){this.log.debug("semantic evaluator resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}evaluatorFailed(e,n){this.log.debug("semantic evaluator failed - no signal; this episode endpoints as armed",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}committed(e,n){this.commitAtMs===null&&(n==="ptt"&&this.heldOpen&&this.heldExited("ptt"),this.commitAtMs=e,n==="ptt"&&(this.decider??="ptt"))}asrFinalResolved(e,n){this.asrFinalAtMs===null&&(this.asrFinalAtMs=e,this.transcriptLength=n)}firstReasonerDelta(e){this.firstDeltaAtMs??=e}firstTtsAudio(e){this.firstAudioAtMs??=e}addresseeFired(){this.log.debug("addressee evaluator fired - racing the reply for the pre-audio veto",{turnId:this.turnId})}addresseeResolved(e,n,i,r){this.log.debug("addressee evaluator resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}addresseeFailed(e,n){this.log.debug("addressee evaluator failed - no signal; the reply speaks",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}markAsideCommit(){this.asideCommit=!0}confirmationFired(){this.log.debug("aside confirmation fired - the lexical wakeword opened the gate",{turnId:this.turnId})}confirmationResolved(e,n,i,r){this.log.debug("aside confirmation resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}confirmationFailed(e,n){this.log.debug("aside confirmation failed - torn with the name spoken: resuming",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}completed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn summary",{turnId:this.turnId,decider:this.decider,disposition:"dispatched",...this.asideCommit&&{floor:"aside"},silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),finalToFirstDeltaMs:this.spanMs(this.asrFinalAtMs,this.firstDeltaAtMs),firstDeltaToFirstAudioMs:this.spanMs(this.firstDeltaAtMs,this.firstAudioAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}absorbed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn absorbed - not addressed to Jarvis; no reply spoken",{turnId:this.turnId,decider:this.decider,disposition:"absorbed",silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}asideAbsorbed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn absorbed in the aside - no reply spoken",{turnId:this.turnId,decider:this.decider,disposition:"absorbed",floor:"aside",silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}blank(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn blank - terminated silently (no transcribed speech)",{turnId:this.turnId,decider:this.decider,silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}spanMs(e,n){return e===null||n===null?null:n-e}}});function GO(t){return BO.test(t)}var Vx,Zx,ZO,Sa,BO,ka,Bx=v(()=>{"use strict";aa();Fx();Vx=16e3,Zx="pcm_s16le",ZO="en",Sa=.7,BO=/\bjarvis\b/i;ka=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;pendingDispatch=null;absorbPending=null;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new wa(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),this.asrStream=e.asrEngine.open({sampleRate:Vx,encoding:Zx,language:ZO,emitPartials:!0}),this.asrStream.onTranscript(n=>this.handleTranscript(n)),this.asrStream.onError(n=>this.finishError("turn_failed",n)),e.controller.onCommit(()=>this.finalize(this.lastFrameAtMs,"controller")),e.emit({type:"state",turnId:e.turnId,state:"processing"})}pushFrame(e,n){this.phase!=="capturing"||this.settled||(this.lastFrameAtMs=n,this.asrStream.pushAudio(e),this.deps.controller.onAudioFrame(e))}endAudio(e){this.finalize(e,"ptt")}cancel(){this.settled||(this.settled=!0,this.phase="cancelled",this.deps.controller.dispose(),this.reasonAbort.abort(),this.asrStream.abort(),this.ttsStream?.cancel(),this.deps.onComplete())}handleTranscript(e){this.phase!=="capturing"||this.settled||e.isFinal||(this.deps.emit({type:"transcript.partial",turnId:this.deps.turnId,text:e.text}),this.deps.controller.onPartial(e.text))}finalize(e,n){this.phase!=="capturing"||this.finalizing||this.settled||(this.finalizing=!0,this.timeline.committed(this.deps.clock.now(),n),this.deps.controller.dispose(),this.finalizeAndRespond(e,n))}async finalizeAndRespond(e,n){let i;try{i=await this.asrStream.end()}catch(s){if(this.settled)return;this.finishError("turn_failed",s);return}if(this.settled)return;this.timeline.asrFinalResolved(this.deps.clock.now(),i.text.length);let r=this.deps.addressee;if(n==="ptt"&&r?.floorState()==="aside")try{r.onFloorReleased("explicit")}catch{}if(i.text.trim()===""){this.finishBlank();return}this.phase="responding";let o=this.buildUserTurn(i.text,e);if(r?.floorState()==="aside")return this.runAside(o,r);r?(this.pendingDispatch={turn:o,deltas:[],audio:[]},this.fireAddressee(o)):this.emitDispatch(o);try{await this.respond(o.text)}catch(s){if(this.settled)return;if(this.absorbPending){this.finishAbsorbed();return}this.finishError("turn_failed",s);return}this.settled||this.finishDone()}async runAside(e,n){if(this.timeline.markAsideCommit(),!GO(e.text)){this.finishAsideAbsorbed(e,n);return}let i=this.deps.clock.now();this.timeline.confirmationFired();let r;try{r=await n.evaluator.evaluate({recentTurns:n.recentTurns(),utterance:e.text},this.reasonAbort.signal,{timeoutMs:3e3})}catch(s){if(this.settled)return;this.timeline.confirmationFailed(this.deps.clock.now()-i,s)}if(this.settled)return;let o=!0;if(r&&(o=!((r.verdict==="to_other"||r.verdict==="self_talk")&&r.confidence>=Sa),this.timeline.confirmationResolved(r.verdict,r.confidence,this.deps.clock.now()-i,o?"resumed":"stayed")),!o){this.finishAsideAbsorbed(e,n,r);return}try{n.onFloorReleased("resume")}catch{}this.emitDispatch(e);try{await this.respond(e.text)}catch(s){if(this.settled)return;this.finishError("turn_failed",s);return}this.settled||this.finishDone()}emitDispatch(e){this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:e,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"})}resolveDispatched(){let e=this.pendingDispatch;if(e){this.pendingDispatch=null,this.emitDispatch(e.turn);for(let n of e.deltas)this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:n});for(let n of e.audio)this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:n})}}fireAddressee(e){let n=this.deps.addressee;if(!n)return;let i=this.deps.clock.now();this.timeline.addresseeFired();try{n.evaluator.evaluate({recentTurns:n.recentTurns(),utterance:e.text},this.reasonAbort.signal).then(r=>this.onAddresseeVerdict(r.verdict,r.confidence,this.deps.clock.now()-i),r=>this.onAddresseeFailed(this.deps.clock.now()-i,r))}catch(r){this.onAddresseeFailed(this.deps.clock.now()-i,r)}}onAddresseeVerdict(e,n,i){if(this.settled||this.pendingDispatch===null){this.timeline.addresseeResolved(e,n,i,"late");return}if(!(e==="to_other"||e==="self_talk")||n<Sa){this.timeline.addresseeResolved(e,n,i,"agreed"),this.resolveDispatched();return}this.absorbPending={verdict:e,confidence:n,latencyMs:i},this.reasonAbort.abort()}onAddresseeFailed(e,n){this.settled||(this.timeline.addresseeFailed(e,n),this.resolveDispatched())}async respond(e){let n=!1,i=!1,r=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:Vx,encoding:Zx});this.ttsStream=r,r.onAudio(s=>{if(!this.settled){if(i||(i=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.absorbPending){this.pendingDispatch?.audio.push(s);return}this.resolveDispatched(),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:s})}}),r.onError(s=>this.finishError("turn_failed",s));let o=this.deps.reasoner.run(e,this.reasonAbort.signal,{register:"voice"});for await(let s of o){if(this.settled)return;if(this.absorbPending){this.finishAbsorbed();return}n||(n=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.pendingDispatch?this.pendingDispatch.deltas.push(s.text):this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:s.text});for(let a of this.deps.segmenter.push(s.text))r.pushText(a)}if(!this.settled){if(this.absorbPending){let{verdict:s,confidence:a,latencyMs:u}=this.absorbPending;this.absorbPending=null,this.timeline.addresseeResolved(s,a,u,"late")}this.resolveDispatched();for(let s of this.deps.segmenter.flush())r.pushText(s);await r.end()}}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}finishAbsorbed(){if(this.settled)return;let e=this.pendingDispatch,n=this.absorbPending;if(!e||!n){this.finishError("turn_failed",new Error("absorb arbitration without a live veto"));return}this.settled=!0,this.phase="cancelled",this.pendingDispatch=null,this.absorbPending=null,this.reasonAbort.abort(),this.ttsStream?.cancel(),this.timeline.addresseeResolved(n.verdict,n.confidence,n.latencyMs,"vetoed"),this.timeline.absorbed(this.deps.clock.now()),this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:{...e.turn,disposition:"absorbed"},...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.onComplete();try{this.deps.addressee?.onAbsorbed(e.turn.text,{verdict:n.verdict,confidence:n.confidence})}catch{}}finishAsideAbsorbed(e,n,i){if(!this.settled){this.settled=!0,this.phase="cancelled",this.timeline.asideAbsorbed(this.deps.clock.now()),this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:{...e,disposition:"absorbed"},...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.onComplete();try{n.onAbsorbed(e.text,i)}catch{}}}finishDone(){this.settled||(this.settled=!0,this.timeline.completed(this.deps.clock.now()),this.deps.emit({type:"response.done",turnId:this.deps.turnId}),this.deps.onComplete())}finishError(e,n){this.settled||(this.settled=!0,this.absorbPending=null,this.resolveDispatched(),this.deps.controller.dispose(),this.reasonAbort.abort(),this.ttsStream?.cancel(),this.deps.emit({type:"error",turnId:this.deps.turnId,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId},reason:e,message:n instanceof Error?n.message:String(n)}),this.deps.onComplete())}buildUserTurn(e,n){return{source:"voice",turnId:this.deps.turnId,sessionId:this.deps.sessionId,deviceId:this.deps.deviceId,text:e,startMs:this.deps.startMs,endMs:n,...this.deps.projectId!==void 0&&{projectId:this.deps.projectId}}}}});import{randomUUID as tm}from"node:crypto";var rm,nm,$n,Fi,Ea,Gx=v(()=>{"use strict";Ae();ki();op();Xb();aa();ap();up();Pi();Mp();qp();Kp();Xp();em();Bx();rm=6,nm=45e3,$n=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Fi=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},Ea=class{deps;sessionId;deviceId;projectId;queue=new sa;closed=!1;eventsConsumed=!1;inFlight=!1;reasoner=null;reasonerRoute=null;turnAbort=null;voiceTurn=null;voiceTurnFailed=!1;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newFrameClassifier;newTurnEvaluator;newSegmenter;voiceIdentity;smartTurnInference=null;frameClassifier=null;turnEvaluator=void 0;newAddresseeEvaluator;addresseeEvaluator=void 0;absorbedFinals=[];floorState="engaged";asideDecayTimer=null;lastSpeechAtMs=0;constructor(e,n,i){this.deps=i,this.sessionId=e,this.deviceId=n.deviceId,this.projectId=n.projectId,this.clock=i.clock??new Ti,this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Mi),this.newFrameClassifier=i.createFrameClassifier??(()=>new Ai(new br)),this.newTurnEvaluator=i.createTurnEvaluator??(r=>new bn(r)),this.newAddresseeEvaluator=i.createAddresseeEvaluator??(r=>new hn(r)),this.newTurnController=i.createTurnController??(r=>{let o=this.ensureFrameClassifier();return o.reset?.(),new ji(r,this.ensureSmartTurnInference(),{},this.speechObservingClassifier(o),this.semanticHook())}),this.newSegmenter=i.createSegmenter??(()=>new Ii),this.voiceIdentity=i.voiceIdentity??Qp,this.emit({type:"session.ready"})}async send(e){let{commandId:n}=e;if(this.closed)throw new Le(n,"closed");if(e.sessionId!==this.sessionId)throw new Le(n,"invalid","command sessionId does not match session");switch(e.type){case"input.text":this.acceptTextInput(e);return;case"input.audio.frame":this.acceptAudioFrame(e);return;case"input.audio.end":this.endAudioInput(e);return;case"turn.cancel":this.cancelTurn(e);return;case"session.close":return this.close();case"approval.resolve":throw new Le(n,"unsupported");default:throw new Le(n,"invalid")}}events(){if(this.eventsConsumed)throw new Error("CoreSession.events() supports a single consumer in v0.1");return this.eventsConsumed=!0,this.queue.drain()}close(){if(!this.closed){this.closed=!0,this.turnAbort?.abort(),this.voiceTurn?.cancel(),this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null);let e=this.smartTurnInference;this.smartTurnInference=null;let n=this.frameClassifier;this.frameClassifier=null;let i=this.turnEvaluator;this.turnEvaluator=null;let r=this.addresseeEvaluator;this.addresseeEvaluator=null,this.queue.close();let o=[];if(e&&o.push(e.dispose().catch(()=>{})),n?.dispose&&o.push(n.dispose().catch(()=>{})),i?.dispose&&o.push(i.dispose().catch(()=>{})),r?.dispose&&o.push(r.dispose().catch(()=>{})),o.length>0)return Promise.all(o).then(()=>{})}return Promise.resolve()}acceptTextInput(e){if(e.text.trim().length===0)throw new Le(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0,this.exitAside("explicit");let n=tm();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"text",commandId:e.commandId}),this.emit({type:"turn.final",turnId:n,turn:this.toTextUserTurn(n,e),commandId:e.commandId}),this.runTextTurn(n,e)}async runTextTurn(e,n){let i=new AbortController;this.turnAbort=i;try{let r=this.ensureReasoner();this.emit({type:"state",turnId:e,state:"responding"});for await(let o of r.run(n.text,i.signal))this.emit({type:"response.delta",turnId:e,text:o.text});this.emit({type:"response.done",turnId:e})}catch(r){let o=r instanceof $n?"no_text_route":"turn_failed";this.emit({type:"error",turnId:e,commandId:n.commandId,reason:o,message:r instanceof Error?r.message:String(r)})}finally{this.inFlight=!1,this.turnAbort=null}}acceptAudioFrame(e){if(this.voiceTurn){this.voiceTurn.pushFrame(e.audio,e.atMs);return}if(this.voiceTurnFailed)return;if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=tm();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"voice",commandId:e.commandId});let i=this.resolveVoicePipeline(n,e.commandId);if(!i){this.voiceTurnFailed=!0;return}let r=this.addresseeHook();this.voiceTurn=new ka({turnId:n,sessionId:this.sessionId,deviceId:this.deviceId,...this.projectId!==void 0&&{projectId:this.projectId},commandId:e.commandId,startMs:e.atMs,asrEngine:i.engines.asrEngine,ttsEngine:i.engines.ttsEngine,voice:this.voiceIdentity,reasoner:i.reasoner,controller:this.newTurnController(this.clock),segmenter:this.newSegmenter(),clock:this.clock,emit:o=>this.emit(o),...r!==void 0&&{addressee:r},onComplete:()=>this.completeVoiceTurn()}),this.smartTurnInference?.prewarm?.(),this.frameClassifier?.prewarm?.(),this.voiceTurn.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}if(this.voiceTurn){this.voiceTurn.endAudio(e.atMs);return}this.exitAside("explicit")}cancelTurn(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.cancel()}completeVoiceTurn(){this.voiceTurn=null,this.inFlight=!1}resetVoiceFailure(){this.voiceTurnFailed=!1}resolveVoicePipeline(e,n){let i;try{i=this.ensureVoiceEngines()}catch(o){return this.emitTurnError(e,n,"no_voice_route",o),null}let r;try{r=this.ensureReasoner()}catch(o){let s=o instanceof $n?"no_text_route":"turn_failed";return this.emitTurnError(e,n,s,o),null}return{engines:i,reasoner:r}}ensureVoiceEngines(){if(this.voiceEngines)return this.voiceEngines;if(!this.deps.voiceRegistry)throw new Fi("voice is not available in this core build");let e=this.deps.configService.resolved(),n=e.routes?.stt,i=e.routes?.tts;if(!n||!i)throw new Fi("no voice route configured - run 'jarvis init' to set routes.stt and routes.tts");let r=e.secrets?.[n.provider],o=e.secrets?.[i.provider];if(!r||!o){let u=r?i.provider:n.provider;throw new Fi(`no API key for voice provider '${u}' - run 'jarvis init' to add it`)}let s=this.deps.voiceRegistry.asrEngine({provider:n.provider,model:n.model},r),a=this.deps.voiceRegistry.ttsEngine({provider:i.provider,model:i.model},o);return this.voiceEngines={asrEngine:s,ttsEngine:a},this.voiceEngines}ensureSmartTurnInference(){return this.smartTurnInference??=this.newSmartTurnInference(),this.smartTurnInference}ensureFrameClassifier(){return this.frameClassifier??=this.newFrameClassifier(),this.frameClassifier}semanticHook(){if(this.turnEvaluator===void 0){let n=this.reasonerRoute;this.turnEvaluator=n?.provider==="anthropic"?this.newTurnEvaluator(n.key):null}return this.turnEvaluator===null?void 0:{evaluator:this.turnEvaluator,recentTurns:()=>{let n=[];for(let i of this.reasoner?.historySnapshot()??[])(i.role==="user"||i.role==="assistant")&&n.push({role:i.role,text:i.content});return n.slice(-rm)}}}addresseeHook(){if(this.addresseeEvaluator===void 0){let n=this.reasonerRoute;try{this.addresseeEvaluator=n?.provider==="anthropic"?this.newAddresseeEvaluator(n.key):null}catch(i){this.addresseeEvaluator=null,B.debug("addressee evaluator construction failed - the layer is absent",{error:i instanceof Error?i.message:String(i)})}}return this.addresseeEvaluator===null?void 0:{evaluator:this.addresseeEvaluator,recentTurns:()=>this.addresseeContext(),onAbsorbed:(n,i)=>{this.recordAbsorbedFinal(n),this.noteSpeech(),i?.verdict==="to_other"&&i.confidence>=Sa&&this.enterAside(i.confidence)},floorState:()=>this.floorState,onFloorReleased:n=>this.exitAside(n)}}enterAside(e){this.floorState!=="aside"&&(this.floorState="aside",this.noteSpeech(),this.armAsideDecay(nm),B.debug("aside entered - confident to_other; utterances now absorb by default",{confidence:e}),this.emit({type:"state",state:"aside"}))}exitAside(e){this.floorState==="aside"&&(this.floorState="engaged",this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null),B.debug("aside exited",{reason:e}))}armAsideDecay(e){this.asideDecayTimer!==null&&this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=this.clock.setTimer(e,()=>this.asideDecayElapsed())}asideDecayElapsed(){if(this.asideDecayTimer=null,this.floorState!=="aside")return;let e=this.clock.now()-this.lastSpeechAtMs;e>=nm?this.exitAside("decay"):this.armAsideDecay(nm-e)}noteSpeech(){this.lastSpeechAtMs=this.clock.now()}speechObservingClassifier(e){return{classify:(n,i)=>e.classify(n,r=>{r&&this.noteSpeech(),i(r)})}}addresseeContext(){let e=this.reasoner?.historySnapshot()??[],n=[],i=0;for(let r=0;r<=e.length;r++){for(;i<this.absorbedFinals.length&&this.absorbedFinals[i].afterHistoryLen===r;)n.push({role:"user",text:this.absorbedFinals[i].text}),i+=1;let o=e[r];o&&(o.role==="user"||o.role==="assistant")&&n.push({role:o.role,text:o.content})}return n.slice(-rm)}recordAbsorbedFinal(e){this.absorbedFinals.push({afterHistoryLen:this.reasoner?.historySnapshot().length??0,text:e}),this.absorbedFinals.length>rm&&this.absorbedFinals.shift()}ensureReasoner(){if(this.reasoner)return this.reasoner;let e=this.deps.configService.resolved(),n=e.routes?.text;if(!n)throw new $n("no text model is configured - run 'jarvis init' to set routes.text");let i=e.secrets?.[n.provider];if(!i)throw new $n(`no API key for text provider '${n.provider}' - run 'jarvis init' to add it`);let r=this.deps.registry.textAdapter({provider:n.provider,model:n.model},i);return this.reasoner=new Ei(r,n.model,this.deps.systemPrompt),this.reasonerRoute={provider:n.provider,key:i},this.reasoner}toTextUserTurn(e,n){return{source:"text",turnId:e,sessionId:this.sessionId,deviceId:this.deviceId,text:n.text,atMs:n.atMs,...this.projectId!==void 0&&{projectId:this.projectId}}}emitTurnError(e,n,i,r){this.emit({type:"error",turnId:e,commandId:n,reason:i,message:r instanceof Error?r.message:String(r)}),this.inFlight=!1}emit(e){this.queue.push({...e,sessionId:this.sessionId,eventId:tm(),atMs:Date.now()})}}});function Ia(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function im(t){return typeof t=="string"?t:""}function Ta(t){let e=t.message_type;return typeof e=="string"&&(WO.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function Wx(t){return Buffer.from(t).toString("base64")}function qx(t){return new Uint8Array(Buffer.from(t,"base64"))}function Oa(t,e){return new Error(`${t} connection error: ${e.message}`)}var WO,om=v(()=>{"use strict";WO=new Set(["error","auth_error","quota_exceeded","rate_limited"])});function qO(t,e,n){let i=new URL(t);i.searchParams.set("model_id",e),i.searchParams.set("audio_format",HO(n)),i.searchParams.set("commit_strategy","manual"),n.language&&i.searchParams.set("language_code",n.language);for(let r of n.biasTerms??[])i.searchParams.append("keyterms",r);return i.toString()}function HO(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Hx,Vi,sm,am=v(()=>{"use strict";om();Hx="wss://api.elevenlabs.io/v1/speech-to-text/realtime",Vi=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-scribe";constructor(e,n,i,r=Hx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpoint=r}open(e){return new sm(this.apiKey,this.socketFactory,this.model,this.endpoint,e)}},sm=class{opts;socket;opened=!1;aborted=!1;closed=!1;pending=[];committed=[];transcriptCb;errorCb;endPending=null;commitRequested=!1;constructor(e,n,i,r,o){this.opts=o,this.socket=n(qO(r,i,o),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(s=>this.handleMessage(s)),this.socket.onError(s=>this.handleError(s)),this.socket.onClose(()=>this.handleClose())}pushAudio(e){if(!(this.aborted||this.closed||this.commitRequested)){if(!this.opened){this.pending.push(e);return}this.sendChunk(e,!1)}}onTranscript(e){this.transcriptCb=e}onError(e){this.errorCb=e}end(){return this.aborted?Promise.reject(new Error("ASR stream already aborted")):this.endPending?Promise.reject(new Error("ASR end() already in progress")):new Promise((e,n)=>{this.endPending={resolve:e,reject:n},this.commitRequested=!0,this.opened&&this.sendCommit()})}abort(){if(this.aborted=!0,this.endPending){let{reject:e}=this.endPending;this.endPending=null,e(new Error("ASR stream aborted"))}return this.teardown(),Promise.resolve()}handleOpen(){if(!(this.aborted||this.closed)){this.opened=!0;for(let e of this.pending)this.sendChunk(e,!1);this.pending.length=0,this.commitRequested&&this.sendCommit()}}handleMessage(e){if(this.aborted||this.closed)return;let n=Ia(e);if(!n)return;let i=Ta(n);if(i){this.handleError(new Error(`stream error (${i})`));return}let r=n.message_type;if(r==="partial_transcript"){this.opts.emitPartials&&this.transcriptCb?.({text:im(n.text),isFinal:!1,startMs:0});return}if(r==="committed_transcript"||r==="committed_transcript_with_timestamps"){let o=im(n.text);o.length>0&&this.committed.push(o),this.endPending&&this.resolveEnd()}}handleError(e){if(this.closed)return;let n=Oa("ElevenLabs ASR",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs ASR connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(e)}this.errorCb?.(e)}resolveEnd(){if(!this.endPending)return;let e={text:this.committed.join(" ").trim(),isFinal:!0,startMs:0};this.transcriptCb?.(e);let{resolve:n}=this.endPending;this.endPending=null,this.teardown(),n(e)}sendChunk(e,n){this.socket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:Wx(e),commit:n,sample_rate:this.opts.sampleRate}))}sendCommit(){this.sendChunk(new Uint8Array(0),!0)}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});import{randomUUID as JO}from"node:crypto";function YO(t,e){let n=t.engineVoice[e];if(!n)throw new Error(`voice '${t.id}' has no '${e}' engineVoice mapping`);if(n.kind!=="preset")throw new Error(`the ${e} adapter needs a preset voiceId for '${t.id}', got kind '${n.kind}'`);return n.voiceId}function XO(t,e,n,i){let r=new URL(t.replace("{voice_id}",encodeURIComponent(e)));return r.searchParams.set("model_id",n),r.searchParams.set("output_format",QO(i)),r.searchParams.set("auto_mode","true"),r.toString()}function QO(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Jx,KO,Zi,um,cm=v(()=>{"use strict";om();Jx="wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/multi-stream-input",KO={stability:.5,similarity_boost:.75,use_speaker_boost:!0},Zi=class{apiKey;socketFactory;model;endpointTemplate;id="elevenlabs-flash";constructor(e,n,i,r=Jx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpointTemplate=r}speak(e){return new um(this.apiKey,this.socketFactory,this.model,this.endpointTemplate,this.id,e)}},um=class{socket;contextId=JO();opened=!1;cancelled=!1;closed=!1;endRequested=!1;closeContextSent=!1;pending=[];audioCb;errorCb;endPending=null;constructor(e,n,i,r,o,s){let a=YO(s.voice,o);this.socket=n(XO(r,a,i,s),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(u=>this.handleMessage(u)),this.socket.onError(u=>this.handleError(u)),this.socket.onClose(()=>this.handleClose())}pushText(e){if(!(this.cancelled||this.closed||this.endRequested)){if(!this.opened){this.pending.push(e);return}this.sendText(e)}}onAudio(e){this.audioCb=e}onError(e){this.errorCb=e}end(){return this.cancelled||this.closed?Promise.resolve():this.endPending?Promise.reject(new Error("TTS end() already in progress")):new Promise((e,n)=>{this.endPending={resolve:e,reject:n},this.endRequested=!0,this.opened&&this.sendEndOfContext()})}cancel(){if(this.cancelled||this.closed)return this.cancelled=!0,Promise.resolve();if(this.cancelled=!0,this.endPending){let{resolve:e}=this.endPending;this.endPending=null,e()}return this.opened&&this.sendCloseContext(),this.teardown(),Promise.resolve()}handleOpen(){if(!(this.cancelled||this.closed)){this.opened=!0,this.sendInit();for(let e of this.pending)this.sendText(e);this.pending.length=0,this.endRequested&&this.sendEndOfContext()}}handleMessage(e){if(this.cancelled||this.closed)return;let n=Ia(e);if(!n)return;let i=Ta(n);if(i){this.handleError(new Error(`stream error (${i})`));return}typeof n.audio=="string"&&n.audio.length>0&&this.audioCb?.(qx(n.audio)),(n.isFinal===!0||n.is_final===!0)&&this.resolveEnd()}handleError(e){if(this.closed)return;let n=Oa("ElevenLabs TTS",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs TTS connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(e)}this.errorCb?.(e)}resolveEnd(){if(!this.endPending)return;let{resolve:e}=this.endPending;this.endPending=null,this.teardown(),e()}sendInit(){this.socket.send(JSON.stringify({text:" ",voice_settings:KO,context_id:this.contextId}))}sendText(e){let n=e.endsWith(" ")?e:`${e} `;this.socket.send(JSON.stringify({text:n,context_id:this.contextId}))}sendEndOfContext(){this.sendFlush(),this.sendCloseContext()}sendFlush(){this.socket.send(JSON.stringify({context_id:this.contextId,text:"",flush:!0}))}sendCloseContext(){this.closeContextSent||(this.closeContextSent=!0,this.socket.send(JSON.stringify({context_id:this.contextId,close_context:!0})))}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});var kt=z((k2,Xx)=>{"use strict";var Kx=["nodebuffer","arraybuffer","fragments"],Yx=typeof Blob<"u";Yx&&Kx.push("blob");Xx.exports={BINARY_TYPES:Kx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Yx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Bi=z((E2,Aa)=>{"use strict";var{EMPTY_BUFFER:eA}=kt(),lm=Buffer[Symbol.species];function tA(t,e){if(t.length===0)return eA;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let r=0;r<t.length;r++){let o=t[r];n.set(o,i),i+=o.length}return i<e?new lm(n.buffer,n.byteOffset,i):n}function Qx(t,e,n,i,r){for(let o=0;o<r;o++)n[i+o]=t[o]^e[o&3]}function ew(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function rA(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function dm(t){if(dm.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new lm(t):ArrayBuffer.isView(t)?e=new lm(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),dm.readOnly=!1),e}Aa.exports={concat:tA,mask:Qx,toArrayBuffer:rA,toBuffer:dm,unmask:ew};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ae("bufferutil");Aa.exports.mask=function(e,n,i,r,o){o<48?Qx(e,n,i,r,o):t.mask(e,n,i,r,o)},Aa.exports.unmask=function(e,n){e.length<32?ew(e,n):t.unmask(e,n)}}catch{}});var nw=z((I2,rw)=>{"use strict";var tw=Symbol("kDone"),fm=Symbol("kRun"),hm=class{constructor(e){this[tw]=()=>{this.pending--,this[fm]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[fm]()}[fm](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[tw])}}};rw.exports=hm});var Sn=z((T2,aw)=>{"use strict";var Gi=ae("zlib"),iw=Bi(),nA=nw(),{kStatusCode:ow}=kt(),iA=Buffer[Symbol.species],oA=Buffer.from([0,0,255,255]),Ca=Symbol("permessage-deflate"),Et=Symbol("total-length"),xn=Symbol("callback"),Xt=Symbol("buffers"),wn=Symbol("error"),Pa,pm=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Pa){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Pa=new nA(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[xn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let r=n[i];if(r.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(r=r[0],i==="client_max_window_bits"){if(r!==!0){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else if(i==="server_max_window_bits"){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=r})}),e}decompress(e,n,i){Pa.add(r=>{this._decompress(e,n,(o,s)=>{r(),i(o,s)})})}compress(e,n,i){Pa.add(r=>{this._compress(e,n,(o,s)=>{r(),i(o,s)})})}_decompress(e,n,i){let r=this._isServer?"client":"server";if(!this._inflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Gi.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Gi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ca]=this,this._inflate[Et]=0,this._inflate[Xt]=[],this._inflate.on("error",aA),this._inflate.on("data",sw)}this._inflate[xn]=i,this._inflate.write(e),n&&this._inflate.write(oA),this._inflate.flush(()=>{let o=this._inflate[wn];if(o){this._inflate.close(),this._inflate=null,i(o);return}let s=iw.concat(this._inflate[Xt],this._inflate[Et]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Et]=0,this._inflate[Xt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),i(null,s)})}_compress(e,n,i){let r=this._isServer?"server":"client";if(!this._deflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Gi.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Gi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Et]=0,this._deflate[Xt]=[],this._deflate.on("data",sA)}this._deflate[xn]=i,this._deflate.write(e),this._deflate.flush(Gi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=iw.concat(this._deflate[Xt],this._deflate[Et]);n&&(o=new iA(o.buffer,o.byteOffset,o.length-4)),this._deflate[xn]=null,this._deflate[Et]=0,this._deflate[Xt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),i(null,o)})}};aw.exports=pm;function sA(t){this[Xt].push(t),this[Et]+=t.length}function sw(t){if(this[Et]+=t.length,this[Ca]._maxPayload<1||this[Et]<=this[Ca]._maxPayload){this[Xt].push(t);return}this[wn]=new RangeError("Max payload size exceeded"),this[wn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[wn][ow]=1009,this.removeListener("data",sw),this.reset()}function aA(t){if(this[Ca]._inflate=null,this[wn]){this[xn](this[wn]);return}t[ow]=1007,this[xn](t)}});var kn=z((O2,za)=>{"use strict";var{isUtf8:uw}=ae("buffer"),{hasBlob:uA}=kt(),cA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function lA(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function mm(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function dA(t){return uA&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}za.exports={isBlob:dA,isValidStatusCode:lA,isValidUTF8:mm,tokenChars:cA};if(uw)za.exports.isValidUTF8=function(t){return t.length<24?mm(t):uw(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ae("utf-8-validate");za.exports.isValidUTF8=function(e){return e.length<32?mm(e):t(e)}}catch{}});var bm=z((A2,mw)=>{"use strict";var{Writable:fA}=ae("stream"),cw=Sn(),{BINARY_TYPES:hA,EMPTY_BUFFER:lw,kStatusCode:pA,kWebSocket:mA}=kt(),{concat:gm,toArrayBuffer:gA,unmask:vA}=Bi(),{isValidStatusCode:yA,isValidUTF8:dw}=kn(),Ra=Buffer[Symbol.species],Qe=0,fw=1,hw=2,pw=3,vm=4,ym=5,Na=6,_m=class extends fA{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||hA[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[mA]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Qe}_write(e,n,i){if(this._opcode===8&&this._state==Qe)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Ra(i.buffer,i.byteOffset+e,i.length-e),new Ra(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],r=n.length-e;e>=i.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),r),this._buffers[0]=new Ra(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Qe:this.getInfo(e);break;case fw:this.getPayloadLength16(e);break;case hw:this.getPayloadLength64(e);break;case pw:this.getMask();break;case vm:this.getData(e);break;case ym:case Na:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let i=(n[0]&64)===64;if(i&&!this._extensions[cw.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=fw:this._payloadLength===127?this._state=hw:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=pw:this._state=vm}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vm}getData(e){let n=lw;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&vA(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ym,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[cw.extensionName].decompress(e,this._fin,(r,o)=>{if(r)return n(r);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===Qe&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Qe;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=gm(i,n):this._binaryType==="arraybuffer"?r=gA(gm(i,n)):this._binaryType==="blob"?r=new Blob(i):r=i,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=Qe):(this._state=Na,setImmediate(()=>{this.emit("message",r,!0),this._state=Qe,this.startLoop(e)}))}else{let r=gm(i,n);if(!this._skipUTF8Validation&&!dw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===ym||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=Qe):(this._state=Na,setImmediate(()=>{this.emit("message",r,!1),this._state=Qe,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,lw),this.end();else{let i=e.readUInt16BE(0);if(!yA(i)){let o=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let r=new Ra(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!dw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",i,r),this.end()}this._state=Qe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe):(this._state=Na,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe,this.startLoop(n)}))}createError(e,n,i,r,o){this._loop=!1,this._errored=!0;let s=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[pA]=r,s}};mw.exports=_m});var wm=z((C2,yw)=>{"use strict";var{Duplex:P2}=ae("stream"),{randomFillSync:_A}=ae("crypto"),{types:{isUint8Array:bA}}=ae("util"),gw=Sn(),{EMPTY_BUFFER:$A,kWebSocket:xA,NOOP:wA}=kt(),{isBlob:En,isValidStatusCode:SA}=kn(),{mask:vw,toBuffer:xr}=Bi(),et=Symbol("kByteLength"),kA=Buffer.alloc(4),Da=8*1024,wr,In=Da,ct=0,EA=1,IA=2,$m=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=wA,this[xA]=void 0}static frame(e,n){let i,r=!1,o=2,s=!1;n.mask&&(i=n.maskBuffer||kA,n.generateMask?n.generateMask(i):(In===Da&&(wr===void 0&&(wr=Buffer.alloc(Da)),_A(wr,0,Da),In=0),i[0]=wr[In++],i[1]=wr[In++],i[2]=wr[In++],i[3]=wr[In++]),s=(i[0]|i[1]|i[2]|i[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[et]!==void 0?a=n[et]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!s);let u=a;a>=65536?(o+=8,u=127):a>125&&(o+=2,u=126);let c=Buffer.allocUnsafe(r?a+o:o);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(a,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[o-4]=i[0],c[o-3]=i[1],c[o-2]=i[2],c[o-1]=i[3],s?[c,e]:r?(vw(e,i,c,o,a),[c]):(vw(e,i,e,0,a),[c,e])):[c,e]}close(e,n,i,r){let o;if(e===void 0)o=$A;else{if(typeof e!="number"||!SA(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(bA(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[et]:o.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,o,!1,s,r]):this.sendFrame(t.frame(o,s),r)}ping(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):En(e)?(r=e.size,o=!1):(e=xr(e),r=e.length,o=xr.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};En(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}pong(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):En(e)?(r=e.size,o=!1):(e=xr(e),r=e.length,o=xr.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};En(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}send(e,n,i){let r=this._extensions[gw.extensionName],o=n.binary?2:1,s=n.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):En(e)?(a=e.size,u=!1):(e=xr(e),a=e.length,u=xr.readOnly),this._firstFragment?(this._firstFragment=!1,s&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=r._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let c={[et]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:u,rsv1:s};En(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,c,i]):this.getBlobData(e,this._compress,c,i):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,c,i]):this.dispatch(e,this._compress,c,i)}getBlobData(e,n,i,r){this._bufferedBytes+=i[et],this._state=IA,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(xm,this,a,r);return}this._bufferedBytes-=i[et];let s=xr(o);n?this.dispatch(s,n,i,r):(this._state=ct,this.sendFrame(t.frame(s,i),r),this.dequeue())}).catch(o=>{process.nextTick(TA,this,o,r)})}dispatch(e,n,i,r){if(!n){this.sendFrame(t.frame(e,i),r);return}let o=this._extensions[gw.extensionName];this._bufferedBytes+=i[et],this._state=EA,o.compress(e,i.fin,(s,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");xm(this,u,r);return}this._bufferedBytes-=i[et],this._state=ct,i.readOnly=!1,this.sendFrame(t.frame(a,i),r),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][et],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][et],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};yw.exports=$m;function xm(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let r=t._queue[i],o=r[r.length-1];typeof o=="function"&&o(e)}}function TA(t,e,n){xm(t,e,n),t.onerror(e)}});var Iw=z((z2,Ew)=>{"use strict";var{kForOnEventAttribute:Wi,kListener:Sm}=kt(),_w=Symbol("kCode"),bw=Symbol("kData"),$w=Symbol("kError"),xw=Symbol("kMessage"),ww=Symbol("kReason"),Tn=Symbol("kTarget"),Sw=Symbol("kType"),kw=Symbol("kWasClean"),It=class{constructor(e){this[Tn]=null,this[Sw]=e}get target(){return this[Tn]}get type(){return this[Sw]}};Object.defineProperty(It.prototype,"target",{enumerable:!0});Object.defineProperty(It.prototype,"type",{enumerable:!0});var Sr=class extends It{constructor(e,n={}){super(e),this[_w]=n.code===void 0?0:n.code,this[ww]=n.reason===void 0?"":n.reason,this[kw]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[_w]}get reason(){return this[ww]}get wasClean(){return this[kw]}};Object.defineProperty(Sr.prototype,"code",{enumerable:!0});Object.defineProperty(Sr.prototype,"reason",{enumerable:!0});Object.defineProperty(Sr.prototype,"wasClean",{enumerable:!0});var On=class extends It{constructor(e,n={}){super(e),this[$w]=n.error===void 0?null:n.error,this[xw]=n.message===void 0?"":n.message}get error(){return this[$w]}get message(){return this[xw]}};Object.defineProperty(On.prototype,"error",{enumerable:!0});Object.defineProperty(On.prototype,"message",{enumerable:!0});var qi=class extends It{constructor(e,n={}){super(e),this[bw]=n.data===void 0?null:n.data}get data(){return this[bw]}};Object.defineProperty(qi.prototype,"data",{enumerable:!0});var OA={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Wi]&&r[Sm]===e&&!r[Wi])return;let i;if(t==="message")i=function(o,s){let a=new qi("message",{data:s?o:o.toString()});a[Tn]=this,La(e,this,a)};else if(t==="close")i=function(o,s){let a=new Sr("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Tn]=this,La(e,this,a)};else if(t==="error")i=function(o){let s=new On("error",{error:o,message:o.message});s[Tn]=this,La(e,this,s)};else if(t==="open")i=function(){let o=new It("open");o[Tn]=this,La(e,this,o)};else return;i[Wi]=!!n[Wi],i[Sm]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Sm]===e&&!n[Wi]){this.removeListener(t,n);break}}};Ew.exports={CloseEvent:Sr,ErrorEvent:On,Event:It,EventTarget:OA,MessageEvent:qi};function La(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Ua=z((R2,Tw)=>{"use strict";var{tokenChars:Hi}=kn();function pt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function AA(t){let e=Object.create(null),n=Object.create(null),i=!1,r=!1,o=!1,s,a,u=-1,c=-1,l=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),s===void 0)if(l===-1&&Hi[c]===1)u===-1&&(u=d);else if(d!==0&&(c===32||c===9))l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);c===44?(pt(e,h,n),n=Object.create(null)):s=h,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&Hi[c]===1)u===-1&&(u=d);else if(c===32||c===9)l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),pt(n,t.slice(u,l),!0),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),u=l=-1}else if(c===61&&u!==-1&&l===-1)a=t.slice(u,d),u=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(Hi[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1?u=d:i||(i=!0),r=!1}else if(o)if(Hi[c]===1)u===-1&&(u=d);else if(c===34&&u!==-1)o=!1,l=d;else if(c===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&Hi[c]===1)u===-1&&(u=d);else if(u!==-1&&(c===32||c===9))l===-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);i&&(h=h.replace(/\\/g,""),i=!1),pt(n,a,h),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),a=void 0,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(u===-1||o||c===32||c===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let f=t.slice(u,l);return s===void 0?pt(e,f,n):(a===void 0?pt(n,f,!0):i?pt(n,a,f.replace(/\\/g,"")):pt(n,a,f),pt(e,s,n)),e}function PA(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(r=>{let o=i[r];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?r:`${r}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Tw.exports={format:PA,parse:AA}});var Va=z((L2,Mw)=>{"use strict";var CA=ae("events"),zA=ae("https"),RA=ae("http"),Pw=ae("net"),NA=ae("tls"),{randomBytes:DA,createHash:LA}=ae("crypto"),{Duplex:N2,Readable:D2}=ae("stream"),{URL:km}=ae("url"),Qt=Sn(),UA=bm(),jA=wm(),{isBlob:MA}=kn(),{BINARY_TYPES:Ow,CLOSE_TIMEOUT:FA,EMPTY_BUFFER:ja,GUID:VA,kForOnEventAttribute:Em,kListener:ZA,kStatusCode:BA,kWebSocket:ge,NOOP:Cw}=kt(),{EventTarget:{addEventListener:GA,removeEventListener:WA}}=Iw(),{format:qA,parse:HA}=Ua(),{toBuffer:JA}=Bi(),zw=Symbol("kAborted"),Im=[8,13],Tt=["CONNECTING","OPEN","CLOSING","CLOSED"],KA=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,re=class t extends CA{constructor(e,n,i){super(),this._binaryType=Ow[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ja,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),Rw(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ow.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let r=new UA({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),o=new jA(e,this._extensions,i.generateMask);this._receiver=r,this._sender=o,this._socket=e,r[ge]=this,o[ge]=this,e[ge]=this,r.on("conclude",QA),r.on("drain",eP),r.on("error",tP),r.on("message",rP),r.on("ping",nP),r.on("pong",iP),o.onerror=oP,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Lw),e.on("data",Fa),e.on("end",Uw),e.on("error",jw),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Qt.extensionName]&&this._extensions[Qt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Dw(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ja,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ja,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tm(this,e,i);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Qt.extensionName]||(r.compress=!1),this._sender.send(e||ja,r,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re.prototype,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re.prototype,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re.prototype,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});Object.defineProperty(re.prototype,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(re.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(re.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Em])return e[ZA];return null},set(e){for(let n of this.listeners(t))if(n[Em]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Em]:!0})}})});re.prototype.addEventListener=GA;re.prototype.removeEventListener=WA;Mw.exports=re;function Rw(t,e,n,i){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:FA,protocolVersion:Im[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=r.autoPong,t._closeTimeout=r.closeTimeout,!Im.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${Im.join(", ")})`);let o;if(e instanceof km)o=e;else try{o=new km(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",u;if(o.protocol!=="ws:"&&!s&&!a?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?u="The URL's pathname is empty":o.hash&&(u="The URL contains a fragment identifier"),u){let _=new SyntaxError(u);if(t._redirects===0)throw _;Ma(t,_);return}let c=s?443:80,l=DA(16).toString("base64"),d=s?zA.request:RA.request,f=new Set,h;if(r.createConnection=r.createConnection||(s?XA:YA),r.defaultPort=r.defaultPort||c,r.port=o.port||c,r.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},r.path=o.pathname+o.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(h=new Qt({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=qA({[Qt.extensionName]:h.offer()})),n.length){for(let _ of n){if(typeof _!="string"||!KA.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(_)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(o.username||o.password)&&(r.auth=`${o.username}:${o.password}`),a){let _=r.path.split(":");r.socketPath=_[0],r.path=_[1]}let p;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?r.socketPath:o.host;let _=i&&i.headers;if(i={...i,headers:{}},_)for(let[S,k]of Object.entries(_))i.headers[S.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let _=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!_||t._originalSecure&&!s)&&(delete r.headers.authorization,delete r.headers.cookie,_||delete r.headers.host,r.auth=void 0)}r.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),p=t._req=d(r),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=d(r);r.timeout&&p.on("timeout",()=>{We(t,p,"Opening handshake has timed out")}),p.on("error",_=>{p===null||p[zw]||(p=t._req=null,Ma(t,_))}),p.on("response",_=>{let S=_.headers.location,k=_.statusCode;if(S&&r.followRedirects&&k>=300&&k<400){if(++t._redirects>r.maxRedirects){We(t,p,"Maximum redirects exceeded");return}p.abort();let P;try{P=new km(S,e)}catch{let E=new SyntaxError(`Invalid URL: ${S}`);Ma(t,E);return}Rw(t,P,n,i)}else t.emit("unexpected-response",p,_)||We(t,p,`Unexpected server response: ${_.statusCode}`)}),p.on("upgrade",(_,S,k)=>{if(t.emit("upgrade",_),t.readyState!==re.CONNECTING)return;p=t._req=null;let P=_.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){We(t,S,"Invalid Upgrade header");return}let C=LA("sha1").update(l+VA).digest("base64");if(_.headers["sec-websocket-accept"]!==C){We(t,S,"Invalid Sec-WebSocket-Accept header");return}let E=_.headers["sec-websocket-protocol"],T;if(E!==void 0?f.size?f.has(E)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":f.size&&(T="Server sent no subprotocol"),T){We(t,S,T);return}E&&(t._protocol=E);let Z=_.headers["sec-websocket-extensions"];if(Z!==void 0){if(!h){We(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let F;try{F=HA(Z)}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys(F);if(q.length!==1||q[0]!==Qt.extensionName){We(t,S,"Server indicated an extension that was not requested");return}try{h.accept(F[Qt.extensionName])}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Qt.extensionName]=h}t.setSocket(S,k,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(p,t):p.end()}function Ma(t,e){t._readyState=re.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function YA(t){return t.path=t.socketPath,Pw.connect(t)}function XA(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Pw.isIP(t.host)?"":t.host),NA.connect(t)}function We(t,e,n){t._readyState=re.CLOSING;let i=new Error(n);Error.captureStackTrace(i,We),e.setHeader?(e[zw]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ma,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Tm(t,e,n){if(e){let i=MA(e)?e.size:JA(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Tt[t.readyState]})`);process.nextTick(n,i)}}function QA(t,e){let n=this[ge];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ge]!==void 0&&(n._socket.removeListener("data",Fa),process.nextTick(Nw,n._socket),t===1005?n.close():n.close(t,e))}function eP(){let t=this[ge];t.isPaused||t._socket.resume()}function tP(t){let e=this[ge];e._socket[ge]!==void 0&&(e._socket.removeListener("data",Fa),process.nextTick(Nw,e._socket),e.close(t[BA])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Aw(){this[ge].emitClose()}function rP(t,e){this[ge].emit("message",t,e)}function nP(t){let e=this[ge];e._autoPong&&e.pong(t,!this._isServer,Cw),e.emit("ping",t)}function iP(t){this[ge].emit("pong",t)}function Nw(t){t.resume()}function oP(t){let e=this[ge];e.readyState!==re.CLOSED&&(e.readyState===re.OPEN&&(e._readyState=re.CLOSING,Dw(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Dw(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Lw(){let t=this[ge];if(this.removeListener("close",Lw),this.removeListener("data",Fa),this.removeListener("end",Uw),t._readyState=re.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ge]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Aw),t._receiver.on("finish",Aw))}function Fa(t){this[ge]._receiver.write(t)||this.pause()}function Uw(){let t=this[ge];t._readyState=re.CLOSING,t._receiver.end(),this.end()}function jw(){let t=this[ge];this.removeListener("error",jw),this.on("error",Cw),t&&(t._readyState=re.CLOSING,this.destroy())}});var Bw=z((j2,Zw)=>{"use strict";var U2=Va(),{Duplex:sP}=ae("stream");function Fw(t){t.emit("close")}function aP(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vw(t){this.removeListener("error",Vw),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function uP(t,e){let n=!0,i=new sP({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&i._readableState.objectMode?o.toString():o;i.push(a)||t.pause()}),t.once("error",function(o){i.destroyed||(n=!1,i.destroy(o))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(r,o){if(t.readyState===t.CLOSED){o(r),process.nextTick(Fw,i);return}let s=!1;t.once("error",function(u){s=!0,o(u)}),t.once("close",function(){s||o(r),process.nextTick(Fw,i)}),n&&t.terminate()},i._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(r,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(r,o,s)});return}t.send(r,s)},i.on("end",aP),i.on("error",Vw),i}Zw.exports=uP});var Om=z((M2,Gw)=>{"use strict";var{tokenChars:cP}=kn();function lP(t){let e=new Set,n=-1,i=-1,r=0;for(r;r<t.length;r++){let s=t.charCodeAt(r);if(i===-1&&cP[s]===1)n===-1&&(n=r);else if(r!==0&&(s===32||s===9))i===-1&&n!==-1&&(i=r);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);i===-1&&(i=r);let a=t.slice(n,i);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,r);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Gw.exports={parse:lP}});var Xw=z((V2,Yw)=>{"use strict";var dP=ae("events"),Za=ae("http"),{Duplex:F2}=ae("stream"),{createHash:fP}=ae("crypto"),Ww=Ua(),kr=Sn(),hP=Om(),pP=Va(),{CLOSE_TIMEOUT:mP,GUID:gP,kWebSocket:vP}=kt(),yP=/^[+/0-9A-Za-z]{22}==$/,qw=0,Hw=1,Kw=2,Am=class extends dP{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:mP,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:pP,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Za.createServer((i,r)=>{let o=Za.STATUS_CODES[426];r.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),r.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=_P(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,o,s)=>{this.handleUpgrade(r,o,s,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=qw}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Kw){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ji,this);return}if(e&&this.once("close",e),this._state!==Hw)if(this._state=Hw,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ji,this):process.nextTick(Ji,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ji(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,r){n.on("error",Jw);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Er(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Er(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!yP.test(o)){Er(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Er(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ki(n,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=hP.parse(u)}catch{Er(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let f=new kr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Ww.parse(l);h[kr.extensionName]&&(f.accept(h[kr.extensionName]),d[kr.extensionName]=f)}catch{Er(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,p,_,S)=>{if(!h)return Ki(n,p||401,_,S);this.completeUpgrade(d,o,c,e,n,i,r)});return}if(!this.options.verifyClient(f))return Ki(n,401)}this.completeUpgrade(d,o,c,e,n,i,r)}completeUpgrade(e,n,i,r,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[vP])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>qw)return Ki(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fP("sha1").update(n+gP).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(i.size){let d=this.options.handleProtocols?this.options.handleProtocols(i,r):i.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[kr.extensionName]){let d=e[kr.extensionName].params,f=Ww.format({[kr.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",c,r),o.write(c.concat(`\r
181
+ `,Yt=class extends Error{status;constructor(e,n){super(e),this.status=n,this.name="TurnEvaluatorError"}},bn=class{key;fetchImpl;timeoutMs;constructor(e,n=fetch,i=2e3){this.key=e,this.fetchImpl=n,this.timeoutMs=i}async evaluate(e,n){let i={model:RO,max_tokens:64,temperature:0,stop_sequences:LO,system:jO,messages:[{role:"user",content:MO(e)},{role:"assistant",content:jx}]},r=await this.fetchImpl(NO,{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":DO,"content-type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.any([n,AbortSignal.timeout(this.timeoutMs)])});if(!r.ok)throw new Yt(`turn evaluator request failed (HTTP ${r.status})`,r.status);let o;try{o=await r.json()}catch{throw new Yt("turn evaluator response body was not JSON")}return FO(o)}}});var Mx,Qp,em=v(()=>{"use strict";Mx="21m00Tcm4TlvDq8ikWAM",Qp={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:Mx}}}});var wa,Fx=v(()=>{"use strict";Ae();wa=class{turnId;openedAtMs;log;terminal=!1;heldOpen=!1;asideCommit=!1;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,n,i=B){this.turnId=e,this.openedAtMs=n,this.log=i}endpointerCommitted(e,n){this.decider===null&&(this.decider=e,this.silenceOnsetAtMs=n)}smartTurnResolved(e,n,i){this.log.debug("smart-turn P(complete)",{turnId:this.turnId,probability:e,inferenceMs:n,outcome:i})}smartTurnDegraded(e,n){this.log.debug("smart-turn DEGRADED to baseline - inference failed; this turn endpoints on baseline timers only",{turnId:this.turnId,inferenceMs:e,error:n instanceof Error?n.message:String(n)})}strongHoldRecognized(e){this.log.debug("lexical STRONG hold recognized - completeness vetoed, silence budget biases long",{turnId:this.turnId,cue:e})}heldEntered(e){this.heldOpen=!0,this.log.debug("floor-held mode entered - silence budgets escalate, stop cap suspended",{turnId:this.turnId,cue:e})}heldLadderRearmed(e){this.log.debug("held silence budget re-armed at the next ladder step",{turnId:this.turnId,budgetMs:e})}heldExited(e){this.heldOpen=!1,this.log.debug("floor-held mode exited",{turnId:this.turnId,reason:e})}evaluatorFired(e){this.log.debug("semantic evaluator fired - smart-turn resolved in a gated band during a live silence episode",{turnId:this.turnId,band:e})}evaluatorResolved(e,n,i,r){this.log.debug("semantic evaluator resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}evaluatorFailed(e,n){this.log.debug("semantic evaluator failed - no signal; this episode endpoints as armed",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}committed(e,n){this.commitAtMs===null&&(n==="ptt"&&this.heldOpen&&this.heldExited("ptt"),this.commitAtMs=e,n==="ptt"&&(this.decider??="ptt"))}asrFinalResolved(e,n){this.asrFinalAtMs===null&&(this.asrFinalAtMs=e,this.transcriptLength=n)}firstReasonerDelta(e){this.firstDeltaAtMs??=e}firstTtsAudio(e){this.firstAudioAtMs??=e}addresseeFired(){this.log.debug("addressee evaluator fired - racing the reply for the pre-audio veto",{turnId:this.turnId})}addresseeResolved(e,n,i,r){this.log.debug("addressee evaluator resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}addresseeFailed(e,n){this.log.debug("addressee evaluator failed - no signal; the reply speaks",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}markAsideCommit(){this.asideCommit=!0}confirmationFired(){this.log.debug("aside confirmation fired - the lexical wakeword opened the gate",{turnId:this.turnId})}confirmationResolved(e,n,i,r){this.log.debug("aside confirmation resolved",{turnId:this.turnId,verdict:e,confidence:n,latencyMs:i,outcome:r})}confirmationFailed(e,n){this.log.debug("aside confirmation failed - torn with the name spoken: resuming",{turnId:this.turnId,latencyMs:e,error:n instanceof Error?n.message:String(n)})}completed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn summary",{turnId:this.turnId,decider:this.decider,disposition:"dispatched",...this.asideCommit&&{floor:"aside"},silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),finalToFirstDeltaMs:this.spanMs(this.asrFinalAtMs,this.firstDeltaAtMs),firstDeltaToFirstAudioMs:this.spanMs(this.firstDeltaAtMs,this.firstAudioAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}absorbed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn absorbed - not addressed to Jarvis; no reply spoken",{turnId:this.turnId,decider:this.decider,disposition:"absorbed",silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}asideAbsorbed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn absorbed in the aside - no reply spoken",{turnId:this.turnId,decider:this.decider,disposition:"absorbed",floor:"aside",silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}blank(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn blank - terminated silently (no transcribed speech)",{turnId:this.turnId,decider:this.decider,silenceToCommitMs:this.spanMs(this.silenceOnsetAtMs,this.commitAtMs),commitToFinalMs:this.spanMs(this.commitAtMs,this.asrFinalAtMs),totalMs:e-this.openedAtMs,transcriptLength:this.transcriptLength}))}spanMs(e,n){return e===null||n===null?null:n-e}}});function WO(t){return GO.test(t)}var Vx,Zx,ZO,BO,Sa,GO,ka,Bx=v(()=>{"use strict";aa();Fx();Vx=16e3,Zx="pcm_s16le",ZO="en",BO=["Jarvis"],Sa=.7,GO=/\bjarvis\b/i;ka=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;pendingDispatch=null;absorbPending=null;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new wa(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),this.asrStream=e.asrEngine.open({sampleRate:Vx,encoding:Zx,language:ZO,biasTerms:BO,emitPartials:!0}),this.asrStream.onTranscript(n=>this.handleTranscript(n)),this.asrStream.onError(n=>this.finishError("turn_failed",n)),e.controller.onCommit(()=>this.finalize(this.lastFrameAtMs,"controller")),e.emit({type:"state",turnId:e.turnId,state:"processing"})}pushFrame(e,n){this.phase!=="capturing"||this.settled||(this.lastFrameAtMs=n,this.asrStream.pushAudio(e),this.deps.controller.onAudioFrame(e))}endAudio(e){this.finalize(e,"ptt")}cancel(){this.settled||(this.settled=!0,this.phase="cancelled",this.deps.controller.dispose(),this.reasonAbort.abort(),this.asrStream.abort(),this.ttsStream?.cancel(),this.deps.onComplete())}handleTranscript(e){this.phase!=="capturing"||this.settled||e.isFinal||(this.deps.emit({type:"transcript.partial",turnId:this.deps.turnId,text:e.text}),this.deps.controller.onPartial(e.text))}finalize(e,n){this.phase!=="capturing"||this.finalizing||this.settled||(this.finalizing=!0,this.timeline.committed(this.deps.clock.now(),n),this.deps.controller.dispose(),this.finalizeAndRespond(e,n))}async finalizeAndRespond(e,n){let i;try{i=await this.asrStream.end()}catch(s){if(this.settled)return;this.finishError("turn_failed",s);return}if(this.settled)return;this.timeline.asrFinalResolved(this.deps.clock.now(),i.text.length);let r=this.deps.addressee;if(n==="ptt"&&r?.floorState()==="aside")try{r.onFloorReleased("explicit")}catch{}if(i.text.trim()===""){this.finishBlank();return}this.phase="responding";let o=this.buildUserTurn(i.text,e);if(r?.floorState()==="aside")return this.runAside(o,r);r?(this.pendingDispatch={turn:o,deltas:[],audio:[]},this.fireAddressee(o)):this.emitDispatch(o);try{await this.respond(o.text)}catch(s){if(this.settled)return;if(this.absorbPending){this.finishAbsorbed();return}this.finishError("turn_failed",s);return}this.settled||this.finishDone()}async runAside(e,n){if(this.timeline.markAsideCommit(),!WO(e.text)){this.finishAsideAbsorbed(e,n);return}let i=this.deps.clock.now();this.timeline.confirmationFired();let r;try{r=await n.evaluator.evaluate({recentTurns:n.recentTurns(),utterance:e.text},this.reasonAbort.signal,{timeoutMs:3e3})}catch(s){if(this.settled)return;this.timeline.confirmationFailed(this.deps.clock.now()-i,s)}if(this.settled)return;let o=!0;if(r&&(o=!((r.verdict==="to_other"||r.verdict==="self_talk")&&r.confidence>=Sa),this.timeline.confirmationResolved(r.verdict,r.confidence,this.deps.clock.now()-i,o?"resumed":"stayed")),!o){this.finishAsideAbsorbed(e,n,r);return}try{n.onFloorReleased("resume")}catch{}this.emitDispatch(e);try{await this.respond(e.text)}catch(s){if(this.settled)return;this.finishError("turn_failed",s);return}this.settled||this.finishDone()}emitDispatch(e){this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:e,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"})}resolveDispatched(){let e=this.pendingDispatch;if(e){this.pendingDispatch=null,this.emitDispatch(e.turn);for(let n of e.deltas)this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:n});for(let n of e.audio)this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:n})}}fireAddressee(e){let n=this.deps.addressee;if(!n)return;let i=this.deps.clock.now();this.timeline.addresseeFired();try{n.evaluator.evaluate({recentTurns:n.recentTurns(),utterance:e.text},this.reasonAbort.signal).then(r=>this.onAddresseeVerdict(r.verdict,r.confidence,this.deps.clock.now()-i),r=>this.onAddresseeFailed(this.deps.clock.now()-i,r))}catch(r){this.onAddresseeFailed(this.deps.clock.now()-i,r)}}onAddresseeVerdict(e,n,i){if(this.settled||this.pendingDispatch===null){this.timeline.addresseeResolved(e,n,i,"late");return}if(!(e==="to_other"||e==="self_talk")||n<Sa){this.timeline.addresseeResolved(e,n,i,"agreed"),this.resolveDispatched();return}this.absorbPending={verdict:e,confidence:n,latencyMs:i},this.reasonAbort.abort()}onAddresseeFailed(e,n){this.settled||(this.timeline.addresseeFailed(e,n),this.resolveDispatched())}async respond(e){let n=!1,i=!1,r=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:Vx,encoding:Zx});this.ttsStream=r,r.onAudio(s=>{if(!this.settled){if(i||(i=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.absorbPending){this.pendingDispatch?.audio.push(s);return}this.resolveDispatched(),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:s})}}),r.onError(s=>this.finishError("turn_failed",s));let o=this.deps.reasoner.run(e,this.reasonAbort.signal,{register:"voice"});for await(let s of o){if(this.settled)return;if(this.absorbPending){this.finishAbsorbed();return}n||(n=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.pendingDispatch?this.pendingDispatch.deltas.push(s.text):this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:s.text});for(let a of this.deps.segmenter.push(s.text))r.pushText(a)}if(!this.settled){if(this.absorbPending){let{verdict:s,confidence:a,latencyMs:u}=this.absorbPending;this.absorbPending=null,this.timeline.addresseeResolved(s,a,u,"late")}this.resolveDispatched();for(let s of this.deps.segmenter.flush())r.pushText(s);await r.end()}}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}finishAbsorbed(){if(this.settled)return;let e=this.pendingDispatch,n=this.absorbPending;if(!e||!n){this.finishError("turn_failed",new Error("absorb arbitration without a live veto"));return}this.settled=!0,this.phase="cancelled",this.pendingDispatch=null,this.absorbPending=null,this.reasonAbort.abort(),this.ttsStream?.cancel(),this.timeline.addresseeResolved(n.verdict,n.confidence,n.latencyMs,"vetoed"),this.timeline.absorbed(this.deps.clock.now()),this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:{...e.turn,disposition:"absorbed"},...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.onComplete();try{this.deps.addressee?.onAbsorbed(e.turn.text,{verdict:n.verdict,confidence:n.confidence})}catch{}}finishAsideAbsorbed(e,n,i){if(!this.settled){this.settled=!0,this.phase="cancelled",this.timeline.asideAbsorbed(this.deps.clock.now()),this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:{...e,disposition:"absorbed"},...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.onComplete();try{n.onAbsorbed(e.text,i)}catch{}}}finishDone(){this.settled||(this.settled=!0,this.timeline.completed(this.deps.clock.now()),this.deps.emit({type:"response.done",turnId:this.deps.turnId}),this.deps.onComplete())}finishError(e,n){this.settled||(this.settled=!0,this.absorbPending=null,this.resolveDispatched(),this.deps.controller.dispose(),this.reasonAbort.abort(),this.ttsStream?.cancel(),this.deps.emit({type:"error",turnId:this.deps.turnId,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId},reason:e,message:n instanceof Error?n.message:String(n)}),this.deps.onComplete())}buildUserTurn(e,n){return{source:"voice",turnId:this.deps.turnId,sessionId:this.deps.sessionId,deviceId:this.deps.deviceId,text:e,startMs:this.deps.startMs,endMs:n,...this.deps.projectId!==void 0&&{projectId:this.deps.projectId}}}}});import{randomUUID as tm}from"node:crypto";var rm,nm,$n,Fi,Ea,Gx=v(()=>{"use strict";Ae();ki();op();Xb();aa();ap();up();Pi();Mp();qp();Kp();Xp();em();Bx();rm=6,nm=45e3,$n=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Fi=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},Ea=class{deps;sessionId;deviceId;projectId;queue=new sa;closed=!1;eventsConsumed=!1;inFlight=!1;reasoner=null;reasonerRoute=null;turnAbort=null;voiceTurn=null;voiceTurnFailed=!1;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newFrameClassifier;newTurnEvaluator;newSegmenter;voiceIdentity;smartTurnInference=null;frameClassifier=null;turnEvaluator=void 0;newAddresseeEvaluator;addresseeEvaluator=void 0;absorbedFinals=[];floorState="engaged";asideDecayTimer=null;lastSpeechAtMs=0;constructor(e,n,i){this.deps=i,this.sessionId=e,this.deviceId=n.deviceId,this.projectId=n.projectId,this.clock=i.clock??new Ti,this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Mi),this.newFrameClassifier=i.createFrameClassifier??(()=>new Ai(new br)),this.newTurnEvaluator=i.createTurnEvaluator??(r=>new bn(r)),this.newAddresseeEvaluator=i.createAddresseeEvaluator??(r=>new hn(r)),this.newTurnController=i.createTurnController??(r=>{let o=this.ensureFrameClassifier();return o.reset?.(),new ji(r,this.ensureSmartTurnInference(),{},this.speechObservingClassifier(o),this.semanticHook())}),this.newSegmenter=i.createSegmenter??(()=>new Ii),this.voiceIdentity=i.voiceIdentity??Qp,this.emit({type:"session.ready"})}async send(e){let{commandId:n}=e;if(this.closed)throw new Le(n,"closed");if(e.sessionId!==this.sessionId)throw new Le(n,"invalid","command sessionId does not match session");switch(e.type){case"input.text":this.acceptTextInput(e);return;case"input.audio.frame":this.acceptAudioFrame(e);return;case"input.audio.end":this.endAudioInput(e);return;case"turn.cancel":this.cancelTurn(e);return;case"session.close":return this.close();case"approval.resolve":throw new Le(n,"unsupported");default:throw new Le(n,"invalid")}}events(){if(this.eventsConsumed)throw new Error("CoreSession.events() supports a single consumer in v0.1");return this.eventsConsumed=!0,this.queue.drain()}close(){if(!this.closed){this.closed=!0,this.turnAbort?.abort(),this.voiceTurn?.cancel(),this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null);let e=this.smartTurnInference;this.smartTurnInference=null;let n=this.frameClassifier;this.frameClassifier=null;let i=this.turnEvaluator;this.turnEvaluator=null;let r=this.addresseeEvaluator;this.addresseeEvaluator=null,this.queue.close();let o=[];if(e&&o.push(e.dispose().catch(()=>{})),n?.dispose&&o.push(n.dispose().catch(()=>{})),i?.dispose&&o.push(i.dispose().catch(()=>{})),r?.dispose&&o.push(r.dispose().catch(()=>{})),o.length>0)return Promise.all(o).then(()=>{})}return Promise.resolve()}acceptTextInput(e){if(e.text.trim().length===0)throw new Le(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0,this.exitAside("explicit");let n=tm();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"text",commandId:e.commandId}),this.emit({type:"turn.final",turnId:n,turn:this.toTextUserTurn(n,e),commandId:e.commandId}),this.runTextTurn(n,e)}async runTextTurn(e,n){let i=new AbortController;this.turnAbort=i;try{let r=this.ensureReasoner();this.emit({type:"state",turnId:e,state:"responding"});for await(let o of r.run(n.text,i.signal))this.emit({type:"response.delta",turnId:e,text:o.text});this.emit({type:"response.done",turnId:e})}catch(r){let o=r instanceof $n?"no_text_route":"turn_failed";this.emit({type:"error",turnId:e,commandId:n.commandId,reason:o,message:r instanceof Error?r.message:String(r)})}finally{this.inFlight=!1,this.turnAbort=null}}acceptAudioFrame(e){if(this.voiceTurn){this.voiceTurn.pushFrame(e.audio,e.atMs);return}if(this.voiceTurnFailed)return;if(this.inFlight)throw new Le(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=tm();this.emit({type:"turn.accepted",turnId:n,clientTurnId:e.clientTurnId,source:"voice",commandId:e.commandId});let i=this.resolveVoicePipeline(n,e.commandId);if(!i){this.voiceTurnFailed=!0;return}let r=this.addresseeHook();this.voiceTurn=new ka({turnId:n,sessionId:this.sessionId,deviceId:this.deviceId,...this.projectId!==void 0&&{projectId:this.projectId},commandId:e.commandId,startMs:e.atMs,asrEngine:i.engines.asrEngine,ttsEngine:i.engines.ttsEngine,voice:this.voiceIdentity,reasoner:i.reasoner,controller:this.newTurnController(this.clock),segmenter:this.newSegmenter(),clock:this.clock,emit:o=>this.emit(o),...r!==void 0&&{addressee:r},onComplete:()=>this.completeVoiceTurn()}),this.smartTurnInference?.prewarm?.(),this.frameClassifier?.prewarm?.(),this.voiceTurn.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}if(this.voiceTurn){this.voiceTurn.endAudio(e.atMs);return}this.exitAside("explicit")}cancelTurn(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.cancel()}completeVoiceTurn(){this.voiceTurn=null,this.inFlight=!1}resetVoiceFailure(){this.voiceTurnFailed=!1}resolveVoicePipeline(e,n){let i;try{i=this.ensureVoiceEngines()}catch(o){return this.emitTurnError(e,n,"no_voice_route",o),null}let r;try{r=this.ensureReasoner()}catch(o){let s=o instanceof $n?"no_text_route":"turn_failed";return this.emitTurnError(e,n,s,o),null}return{engines:i,reasoner:r}}ensureVoiceEngines(){if(this.voiceEngines)return this.voiceEngines;if(!this.deps.voiceRegistry)throw new Fi("voice is not available in this core build");let e=this.deps.configService.resolved(),n=e.routes?.stt,i=e.routes?.tts;if(!n||!i)throw new Fi("no voice route configured - run 'jarvis init' to set routes.stt and routes.tts");let r=e.secrets?.[n.provider],o=e.secrets?.[i.provider];if(!r||!o){let u=r?i.provider:n.provider;throw new Fi(`no API key for voice provider '${u}' - run 'jarvis init' to add it`)}let s=this.deps.voiceRegistry.asrEngine({provider:n.provider,model:n.model},r),a=this.deps.voiceRegistry.ttsEngine({provider:i.provider,model:i.model},o);return this.voiceEngines={asrEngine:s,ttsEngine:a},this.voiceEngines}ensureSmartTurnInference(){return this.smartTurnInference??=this.newSmartTurnInference(),this.smartTurnInference}ensureFrameClassifier(){return this.frameClassifier??=this.newFrameClassifier(),this.frameClassifier}semanticHook(){if(this.turnEvaluator===void 0){let n=this.reasonerRoute;this.turnEvaluator=n?.provider==="anthropic"?this.newTurnEvaluator(n.key):null}return this.turnEvaluator===null?void 0:{evaluator:this.turnEvaluator,recentTurns:()=>{let n=[];for(let i of this.reasoner?.historySnapshot()??[])(i.role==="user"||i.role==="assistant")&&n.push({role:i.role,text:i.content});return n.slice(-rm)}}}addresseeHook(){if(this.addresseeEvaluator===void 0){let n=this.reasonerRoute;try{this.addresseeEvaluator=n?.provider==="anthropic"?this.newAddresseeEvaluator(n.key):null}catch(i){this.addresseeEvaluator=null,B.debug("addressee evaluator construction failed - the layer is absent",{error:i instanceof Error?i.message:String(i)})}}return this.addresseeEvaluator===null?void 0:{evaluator:this.addresseeEvaluator,recentTurns:()=>this.addresseeContext(),onAbsorbed:(n,i)=>{this.recordAbsorbedFinal(n),this.noteSpeech(),i?.verdict==="to_other"&&i.confidence>=Sa&&this.enterAside(i.confidence)},floorState:()=>this.floorState,onFloorReleased:n=>this.exitAside(n)}}enterAside(e){this.floorState!=="aside"&&(this.floorState="aside",this.noteSpeech(),this.armAsideDecay(nm),B.debug("aside entered - confident to_other; utterances now absorb by default",{confidence:e}),this.emit({type:"state",state:"aside"}))}exitAside(e){this.floorState==="aside"&&(this.floorState="engaged",this.asideDecayTimer!==null&&(this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=null),B.debug("aside exited",{reason:e}))}armAsideDecay(e){this.asideDecayTimer!==null&&this.clock.clearTimer(this.asideDecayTimer),this.asideDecayTimer=this.clock.setTimer(e,()=>this.asideDecayElapsed())}asideDecayElapsed(){if(this.asideDecayTimer=null,this.floorState!=="aside")return;let e=this.clock.now()-this.lastSpeechAtMs;e>=nm?this.exitAside("decay"):this.armAsideDecay(nm-e)}noteSpeech(){this.lastSpeechAtMs=this.clock.now()}speechObservingClassifier(e){return{classify:(n,i)=>e.classify(n,r=>{r&&this.noteSpeech(),i(r)})}}addresseeContext(){let e=this.reasoner?.historySnapshot()??[],n=[],i=0;for(let r=0;r<=e.length;r++){for(;i<this.absorbedFinals.length&&this.absorbedFinals[i].afterHistoryLen===r;)n.push({role:"user",text:this.absorbedFinals[i].text}),i+=1;let o=e[r];o&&(o.role==="user"||o.role==="assistant")&&n.push({role:o.role,text:o.content})}return n.slice(-rm)}recordAbsorbedFinal(e){this.absorbedFinals.push({afterHistoryLen:this.reasoner?.historySnapshot().length??0,text:e}),this.absorbedFinals.length>rm&&this.absorbedFinals.shift()}ensureReasoner(){if(this.reasoner)return this.reasoner;let e=this.deps.configService.resolved(),n=e.routes?.text;if(!n)throw new $n("no text model is configured - run 'jarvis init' to set routes.text");let i=e.secrets?.[n.provider];if(!i)throw new $n(`no API key for text provider '${n.provider}' - run 'jarvis init' to add it`);let r=this.deps.registry.textAdapter({provider:n.provider,model:n.model},i);return this.reasoner=new Ei(r,n.model,this.deps.systemPrompt),this.reasonerRoute={provider:n.provider,key:i},this.reasoner}toTextUserTurn(e,n){return{source:"text",turnId:e,sessionId:this.sessionId,deviceId:this.deviceId,text:n.text,atMs:n.atMs,...this.projectId!==void 0&&{projectId:this.projectId}}}emitTurnError(e,n,i,r){this.emit({type:"error",turnId:e,commandId:n,reason:i,message:r instanceof Error?r.message:String(r)}),this.inFlight=!1}emit(e){this.queue.push({...e,sessionId:this.sessionId,eventId:tm(),atMs:Date.now()})}}});function Ia(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function im(t){return typeof t=="string"?t:""}function Ta(t){let e=t.message_type;return typeof e=="string"&&(qO.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function Wx(t){return Buffer.from(t).toString("base64")}function qx(t){return new Uint8Array(Buffer.from(t,"base64"))}function Oa(t,e){return new Error(`${t} connection error: ${e.message}`)}var qO,om=v(()=>{"use strict";qO=new Set(["error","auth_error","quota_exceeded","rate_limited"])});function HO(t,e,n){let i=new URL(t);i.searchParams.set("model_id",e),i.searchParams.set("audio_format",JO(n)),i.searchParams.set("commit_strategy","manual"),n.language&&i.searchParams.set("language_code",n.language);for(let r of n.biasTerms??[])i.searchParams.append("keyterms",r);return i.toString()}function JO(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Hx,Vi,sm,am=v(()=>{"use strict";om();Hx="wss://api.elevenlabs.io/v1/speech-to-text/realtime",Vi=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-scribe";constructor(e,n,i,r=Hx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpoint=r}open(e){return new sm(this.apiKey,this.socketFactory,this.model,this.endpoint,e)}},sm=class{opts;socket;opened=!1;aborted=!1;closed=!1;pending=[];committed=[];transcriptCb;errorCb;endPending=null;commitRequested=!1;constructor(e,n,i,r,o){this.opts=o,this.socket=n(HO(r,i,o),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(s=>this.handleMessage(s)),this.socket.onError(s=>this.handleError(s)),this.socket.onClose(()=>this.handleClose())}pushAudio(e){if(!(this.aborted||this.closed||this.commitRequested)){if(!this.opened){this.pending.push(e);return}this.sendChunk(e,!1)}}onTranscript(e){this.transcriptCb=e}onError(e){this.errorCb=e}end(){return this.aborted?Promise.reject(new Error("ASR stream already aborted")):this.endPending?Promise.reject(new Error("ASR end() already in progress")):new Promise((e,n)=>{this.endPending={resolve:e,reject:n},this.commitRequested=!0,this.opened&&this.sendCommit()})}abort(){if(this.aborted=!0,this.endPending){let{reject:e}=this.endPending;this.endPending=null,e(new Error("ASR stream aborted"))}return this.teardown(),Promise.resolve()}handleOpen(){if(!(this.aborted||this.closed)){this.opened=!0;for(let e of this.pending)this.sendChunk(e,!1);this.pending.length=0,this.commitRequested&&this.sendCommit()}}handleMessage(e){if(this.aborted||this.closed)return;let n=Ia(e);if(!n)return;let i=Ta(n);if(i){this.handleError(new Error(`stream error (${i})`));return}let r=n.message_type;if(r==="partial_transcript"){this.opts.emitPartials&&this.transcriptCb?.({text:im(n.text),isFinal:!1,startMs:0});return}if(r==="committed_transcript"||r==="committed_transcript_with_timestamps"){let o=im(n.text);o.length>0&&this.committed.push(o),this.endPending&&this.resolveEnd()}}handleError(e){if(this.closed)return;let n=Oa("ElevenLabs ASR",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs ASR connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(e)}this.errorCb?.(e)}resolveEnd(){if(!this.endPending)return;let e={text:this.committed.join(" ").trim(),isFinal:!0,startMs:0};this.transcriptCb?.(e);let{resolve:n}=this.endPending;this.endPending=null,this.teardown(),n(e)}sendChunk(e,n){this.socket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:Wx(e),commit:n,sample_rate:this.opts.sampleRate}))}sendCommit(){this.sendChunk(new Uint8Array(0),!0)}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});import{randomUUID as KO}from"node:crypto";function XO(t,e){let n=t.engineVoice[e];if(!n)throw new Error(`voice '${t.id}' has no '${e}' engineVoice mapping`);if(n.kind!=="preset")throw new Error(`the ${e} adapter needs a preset voiceId for '${t.id}', got kind '${n.kind}'`);return n.voiceId}function QO(t,e,n,i){let r=new URL(t.replace("{voice_id}",encodeURIComponent(e)));return r.searchParams.set("model_id",n),r.searchParams.set("output_format",eA(i)),r.searchParams.set("auto_mode","true"),r.toString()}function eA(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var Jx,YO,Zi,um,cm=v(()=>{"use strict";om();Jx="wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/multi-stream-input",YO={stability:.5,similarity_boost:.75,use_speaker_boost:!0},Zi=class{apiKey;socketFactory;model;endpointTemplate;id="elevenlabs-flash";constructor(e,n,i,r=Jx){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpointTemplate=r}speak(e){return new um(this.apiKey,this.socketFactory,this.model,this.endpointTemplate,this.id,e)}},um=class{socket;contextId=KO();opened=!1;cancelled=!1;closed=!1;endRequested=!1;closeContextSent=!1;pending=[];audioCb;errorCb;endPending=null;constructor(e,n,i,r,o,s){let a=XO(s.voice,o);this.socket=n(QO(r,a,i,s),{"xi-api-key":e}),this.socket.onOpen(()=>this.handleOpen()),this.socket.onMessage(u=>this.handleMessage(u)),this.socket.onError(u=>this.handleError(u)),this.socket.onClose(()=>this.handleClose())}pushText(e){if(!(this.cancelled||this.closed||this.endRequested)){if(!this.opened){this.pending.push(e);return}this.sendText(e)}}onAudio(e){this.audioCb=e}onError(e){this.errorCb=e}end(){return this.cancelled||this.closed?Promise.resolve():this.endPending?Promise.reject(new Error("TTS end() already in progress")):new Promise((e,n)=>{this.endPending={resolve:e,reject:n},this.endRequested=!0,this.opened&&this.sendEndOfContext()})}cancel(){if(this.cancelled||this.closed)return this.cancelled=!0,Promise.resolve();if(this.cancelled=!0,this.endPending){let{resolve:e}=this.endPending;this.endPending=null,e()}return this.opened&&this.sendCloseContext(),this.teardown(),Promise.resolve()}handleOpen(){if(!(this.cancelled||this.closed)){this.opened=!0,this.sendInit();for(let e of this.pending)this.sendText(e);this.pending.length=0,this.endRequested&&this.sendEndOfContext()}}handleMessage(e){if(this.cancelled||this.closed)return;let n=Ia(e);if(!n)return;let i=Ta(n);if(i){this.handleError(new Error(`stream error (${i})`));return}typeof n.audio=="string"&&n.audio.length>0&&this.audioCb?.(qx(n.audio)),(n.isFinal===!0||n.is_final===!0)&&this.resolveEnd()}handleError(e){if(this.closed)return;let n=Oa("ElevenLabs TTS",e);if(this.endPending){let{reject:i}=this.endPending;this.endPending=null,i(n)}this.errorCb?.(n),this.teardown()}handleClose(){if(this.closed)return;this.closed=!0;let e=new Error("ElevenLabs TTS connection closed unexpectedly");if(this.endPending){let{reject:n}=this.endPending;this.endPending=null,n(e)}this.errorCb?.(e)}resolveEnd(){if(!this.endPending)return;let{resolve:e}=this.endPending;this.endPending=null,this.teardown(),e()}sendInit(){this.socket.send(JSON.stringify({text:" ",voice_settings:YO,context_id:this.contextId}))}sendText(e){let n=e.endsWith(" ")?e:`${e} `;this.socket.send(JSON.stringify({text:n,context_id:this.contextId}))}sendEndOfContext(){this.sendFlush(),this.sendCloseContext()}sendFlush(){this.socket.send(JSON.stringify({context_id:this.contextId,text:"",flush:!0}))}sendCloseContext(){this.closeContextSent||(this.closeContextSent=!0,this.socket.send(JSON.stringify({context_id:this.contextId,close_context:!0})))}teardown(){this.closed||(this.closed=!0,this.socket.close())}}});var kt=z((E2,Xx)=>{"use strict";var Kx=["nodebuffer","arraybuffer","fragments"],Yx=typeof Blob<"u";Yx&&Kx.push("blob");Xx.exports={BINARY_TYPES:Kx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Yx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Bi=z((I2,Aa)=>{"use strict";var{EMPTY_BUFFER:tA}=kt(),lm=Buffer[Symbol.species];function rA(t,e){if(t.length===0)return tA;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let r=0;r<t.length;r++){let o=t[r];n.set(o,i),i+=o.length}return i<e?new lm(n.buffer,n.byteOffset,i):n}function Qx(t,e,n,i,r){for(let o=0;o<r;o++)n[i+o]=t[o]^e[o&3]}function ew(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function nA(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function dm(t){if(dm.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new lm(t):ArrayBuffer.isView(t)?e=new lm(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),dm.readOnly=!1),e}Aa.exports={concat:rA,mask:Qx,toArrayBuffer:nA,toBuffer:dm,unmask:ew};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ae("bufferutil");Aa.exports.mask=function(e,n,i,r,o){o<48?Qx(e,n,i,r,o):t.mask(e,n,i,r,o)},Aa.exports.unmask=function(e,n){e.length<32?ew(e,n):t.unmask(e,n)}}catch{}});var nw=z((T2,rw)=>{"use strict";var tw=Symbol("kDone"),fm=Symbol("kRun"),hm=class{constructor(e){this[tw]=()=>{this.pending--,this[fm]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[fm]()}[fm](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[tw])}}};rw.exports=hm});var Sn=z((O2,aw)=>{"use strict";var Gi=ae("zlib"),iw=Bi(),iA=nw(),{kStatusCode:ow}=kt(),oA=Buffer[Symbol.species],sA=Buffer.from([0,0,255,255]),Ca=Symbol("permessage-deflate"),Et=Symbol("total-length"),xn=Symbol("callback"),Xt=Symbol("buffers"),wn=Symbol("error"),Pa,pm=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Pa){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Pa=new iA(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[xn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let r=n[i];if(r.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(r=r[0],i==="client_max_window_bits"){if(r!==!0){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else if(i==="server_max_window_bits"){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=r})}),e}decompress(e,n,i){Pa.add(r=>{this._decompress(e,n,(o,s)=>{r(),i(o,s)})})}compress(e,n,i){Pa.add(r=>{this._compress(e,n,(o,s)=>{r(),i(o,s)})})}_decompress(e,n,i){let r=this._isServer?"client":"server";if(!this._inflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Gi.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Gi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ca]=this,this._inflate[Et]=0,this._inflate[Xt]=[],this._inflate.on("error",uA),this._inflate.on("data",sw)}this._inflate[xn]=i,this._inflate.write(e),n&&this._inflate.write(sA),this._inflate.flush(()=>{let o=this._inflate[wn];if(o){this._inflate.close(),this._inflate=null,i(o);return}let s=iw.concat(this._inflate[Xt],this._inflate[Et]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Et]=0,this._inflate[Xt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),i(null,s)})}_compress(e,n,i){let r=this._isServer?"server":"client";if(!this._deflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?Gi.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Gi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Et]=0,this._deflate[Xt]=[],this._deflate.on("data",aA)}this._deflate[xn]=i,this._deflate.write(e),this._deflate.flush(Gi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=iw.concat(this._deflate[Xt],this._deflate[Et]);n&&(o=new oA(o.buffer,o.byteOffset,o.length-4)),this._deflate[xn]=null,this._deflate[Et]=0,this._deflate[Xt]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),i(null,o)})}};aw.exports=pm;function aA(t){this[Xt].push(t),this[Et]+=t.length}function sw(t){if(this[Et]+=t.length,this[Ca]._maxPayload<1||this[Et]<=this[Ca]._maxPayload){this[Xt].push(t);return}this[wn]=new RangeError("Max payload size exceeded"),this[wn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[wn][ow]=1009,this.removeListener("data",sw),this.reset()}function uA(t){if(this[Ca]._inflate=null,this[wn]){this[xn](this[wn]);return}t[ow]=1007,this[xn](t)}});var kn=z((A2,za)=>{"use strict";var{isUtf8:uw}=ae("buffer"),{hasBlob:cA}=kt(),lA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function dA(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function mm(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function fA(t){return cA&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}za.exports={isBlob:fA,isValidStatusCode:dA,isValidUTF8:mm,tokenChars:lA};if(uw)za.exports.isValidUTF8=function(t){return t.length<24?mm(t):uw(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ae("utf-8-validate");za.exports.isValidUTF8=function(e){return e.length<32?mm(e):t(e)}}catch{}});var bm=z((P2,mw)=>{"use strict";var{Writable:hA}=ae("stream"),cw=Sn(),{BINARY_TYPES:pA,EMPTY_BUFFER:lw,kStatusCode:mA,kWebSocket:gA}=kt(),{concat:gm,toArrayBuffer:vA,unmask:yA}=Bi(),{isValidStatusCode:_A,isValidUTF8:dw}=kn(),Ra=Buffer[Symbol.species],Qe=0,fw=1,hw=2,pw=3,vm=4,ym=5,Na=6,_m=class extends hA{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pA[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[gA]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Qe}_write(e,n,i){if(this._opcode===8&&this._state==Qe)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Ra(i.buffer,i.byteOffset+e,i.length-e),new Ra(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],r=n.length-e;e>=i.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),r),this._buffers[0]=new Ra(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Qe:this.getInfo(e);break;case fw:this.getPayloadLength16(e);break;case hw:this.getPayloadLength64(e);break;case pw:this.getMask();break;case vm:this.getData(e);break;case ym:case Na:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let i=(n[0]&64)===64;if(i&&!this._extensions[cw.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=fw:this._payloadLength===127?this._state=hw:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=pw:this._state=vm}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vm}getData(e){let n=lw;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&yA(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ym,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[cw.extensionName].decompress(e,this._fin,(r,o)=>{if(r)return n(r);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===Qe&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Qe;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=gm(i,n):this._binaryType==="arraybuffer"?r=vA(gm(i,n)):this._binaryType==="blob"?r=new Blob(i):r=i,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=Qe):(this._state=Na,setImmediate(()=>{this.emit("message",r,!0),this._state=Qe,this.startLoop(e)}))}else{let r=gm(i,n);if(!this._skipUTF8Validation&&!dw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===ym||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=Qe):(this._state=Na,setImmediate(()=>{this.emit("message",r,!1),this._state=Qe,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,lw),this.end();else{let i=e.readUInt16BE(0);if(!_A(i)){let o=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let r=new Ra(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!dw(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",i,r),this.end()}this._state=Qe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe):(this._state=Na,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe,this.startLoop(n)}))}createError(e,n,i,r,o){this._loop=!1,this._errored=!0;let s=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[mA]=r,s}};mw.exports=_m});var wm=z((z2,yw)=>{"use strict";var{Duplex:C2}=ae("stream"),{randomFillSync:bA}=ae("crypto"),{types:{isUint8Array:$A}}=ae("util"),gw=Sn(),{EMPTY_BUFFER:xA,kWebSocket:wA,NOOP:SA}=kt(),{isBlob:En,isValidStatusCode:kA}=kn(),{mask:vw,toBuffer:xr}=Bi(),et=Symbol("kByteLength"),EA=Buffer.alloc(4),Da=8*1024,wr,In=Da,ct=0,IA=1,TA=2,$m=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=SA,this[wA]=void 0}static frame(e,n){let i,r=!1,o=2,s=!1;n.mask&&(i=n.maskBuffer||EA,n.generateMask?n.generateMask(i):(In===Da&&(wr===void 0&&(wr=Buffer.alloc(Da)),bA(wr,0,Da),In=0),i[0]=wr[In++],i[1]=wr[In++],i[2]=wr[In++],i[3]=wr[In++]),s=(i[0]|i[1]|i[2]|i[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[et]!==void 0?a=n[et]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!s);let u=a;a>=65536?(o+=8,u=127):a>125&&(o+=2,u=126);let c=Buffer.allocUnsafe(r?a+o:o);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(a,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[o-4]=i[0],c[o-3]=i[1],c[o-2]=i[2],c[o-1]=i[3],s?[c,e]:r?(vw(e,i,c,o,a),[c]):(vw(e,i,e,0,a),[c,e])):[c,e]}close(e,n,i,r){let o;if(e===void 0)o=xA;else{if(typeof e!="number"||!kA(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if($A(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[et]:o.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,o,!1,s,r]):this.sendFrame(t.frame(o,s),r)}ping(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):En(e)?(r=e.size,o=!1):(e=xr(e),r=e.length,o=xr.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};En(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}pong(e,n,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):En(e)?(r=e.size,o=!1):(e=xr(e),r=e.length,o=xr.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[et]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};En(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==ct?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(t.frame(e,s),i)}send(e,n,i){let r=this._extensions[gw.extensionName],o=n.binary?2:1,s=n.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):En(e)?(a=e.size,u=!1):(e=xr(e),a=e.length,u=xr.readOnly),this._firstFragment?(this._firstFragment=!1,s&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=r._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let c={[et]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:u,rsv1:s};En(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,c,i]):this.getBlobData(e,this._compress,c,i):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,c,i]):this.dispatch(e,this._compress,c,i)}getBlobData(e,n,i,r){this._bufferedBytes+=i[et],this._state=TA,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(xm,this,a,r);return}this._bufferedBytes-=i[et];let s=xr(o);n?this.dispatch(s,n,i,r):(this._state=ct,this.sendFrame(t.frame(s,i),r),this.dequeue())}).catch(o=>{process.nextTick(OA,this,o,r)})}dispatch(e,n,i,r){if(!n){this.sendFrame(t.frame(e,i),r);return}let o=this._extensions[gw.extensionName];this._bufferedBytes+=i[et],this._state=IA,o.compress(e,i.fin,(s,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");xm(this,u,r);return}this._bufferedBytes-=i[et],this._state=ct,i.readOnly=!1,this.sendFrame(t.frame(a,i),r),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][et],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][et],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};yw.exports=$m;function xm(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let r=t._queue[i],o=r[r.length-1];typeof o=="function"&&o(e)}}function OA(t,e,n){xm(t,e,n),t.onerror(e)}});var Iw=z((R2,Ew)=>{"use strict";var{kForOnEventAttribute:Wi,kListener:Sm}=kt(),_w=Symbol("kCode"),bw=Symbol("kData"),$w=Symbol("kError"),xw=Symbol("kMessage"),ww=Symbol("kReason"),Tn=Symbol("kTarget"),Sw=Symbol("kType"),kw=Symbol("kWasClean"),It=class{constructor(e){this[Tn]=null,this[Sw]=e}get target(){return this[Tn]}get type(){return this[Sw]}};Object.defineProperty(It.prototype,"target",{enumerable:!0});Object.defineProperty(It.prototype,"type",{enumerable:!0});var Sr=class extends It{constructor(e,n={}){super(e),this[_w]=n.code===void 0?0:n.code,this[ww]=n.reason===void 0?"":n.reason,this[kw]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[_w]}get reason(){return this[ww]}get wasClean(){return this[kw]}};Object.defineProperty(Sr.prototype,"code",{enumerable:!0});Object.defineProperty(Sr.prototype,"reason",{enumerable:!0});Object.defineProperty(Sr.prototype,"wasClean",{enumerable:!0});var On=class extends It{constructor(e,n={}){super(e),this[$w]=n.error===void 0?null:n.error,this[xw]=n.message===void 0?"":n.message}get error(){return this[$w]}get message(){return this[xw]}};Object.defineProperty(On.prototype,"error",{enumerable:!0});Object.defineProperty(On.prototype,"message",{enumerable:!0});var qi=class extends It{constructor(e,n={}){super(e),this[bw]=n.data===void 0?null:n.data}get data(){return this[bw]}};Object.defineProperty(qi.prototype,"data",{enumerable:!0});var AA={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Wi]&&r[Sm]===e&&!r[Wi])return;let i;if(t==="message")i=function(o,s){let a=new qi("message",{data:s?o:o.toString()});a[Tn]=this,La(e,this,a)};else if(t==="close")i=function(o,s){let a=new Sr("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Tn]=this,La(e,this,a)};else if(t==="error")i=function(o){let s=new On("error",{error:o,message:o.message});s[Tn]=this,La(e,this,s)};else if(t==="open")i=function(){let o=new It("open");o[Tn]=this,La(e,this,o)};else return;i[Wi]=!!n[Wi],i[Sm]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Sm]===e&&!n[Wi]){this.removeListener(t,n);break}}};Ew.exports={CloseEvent:Sr,ErrorEvent:On,Event:It,EventTarget:AA,MessageEvent:qi};function La(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Ua=z((N2,Tw)=>{"use strict";var{tokenChars:Hi}=kn();function pt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function PA(t){let e=Object.create(null),n=Object.create(null),i=!1,r=!1,o=!1,s,a,u=-1,c=-1,l=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),s===void 0)if(l===-1&&Hi[c]===1)u===-1&&(u=d);else if(d!==0&&(c===32||c===9))l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);c===44?(pt(e,h,n),n=Object.create(null)):s=h,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&Hi[c]===1)u===-1&&(u=d);else if(c===32||c===9)l===-1&&u!==-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),pt(n,t.slice(u,l),!0),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),u=l=-1}else if(c===61&&u!==-1&&l===-1)a=t.slice(u,d),u=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(Hi[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1?u=d:i||(i=!0),r=!1}else if(o)if(Hi[c]===1)u===-1&&(u=d);else if(c===34&&u!==-1)o=!1,l=d;else if(c===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&Hi[c]===1)u===-1&&(u=d);else if(u!==-1&&(c===32||c===9))l===-1&&(l=d);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(u,l);i&&(h=h.replace(/\\/g,""),i=!1),pt(n,a,h),c===44&&(pt(e,s,n),n=Object.create(null),s=void 0),a=void 0,u=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(u===-1||o||c===32||c===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let f=t.slice(u,l);return s===void 0?pt(e,f,n):(a===void 0?pt(n,f,!0):i?pt(n,a,f.replace(/\\/g,"")):pt(n,a,f),pt(e,s,n)),e}function CA(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(r=>{let o=i[r];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?r:`${r}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Tw.exports={format:CA,parse:PA}});var Va=z((U2,Mw)=>{"use strict";var zA=ae("events"),RA=ae("https"),NA=ae("http"),Pw=ae("net"),DA=ae("tls"),{randomBytes:LA,createHash:UA}=ae("crypto"),{Duplex:D2,Readable:L2}=ae("stream"),{URL:km}=ae("url"),Qt=Sn(),jA=bm(),MA=wm(),{isBlob:FA}=kn(),{BINARY_TYPES:Ow,CLOSE_TIMEOUT:VA,EMPTY_BUFFER:ja,GUID:ZA,kForOnEventAttribute:Em,kListener:BA,kStatusCode:GA,kWebSocket:ge,NOOP:Cw}=kt(),{EventTarget:{addEventListener:WA,removeEventListener:qA}}=Iw(),{format:HA,parse:JA}=Ua(),{toBuffer:KA}=Bi(),zw=Symbol("kAborted"),Im=[8,13],Tt=["CONNECTING","OPEN","CLOSING","CLOSED"],YA=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,re=class t extends zA{constructor(e,n,i){super(),this._binaryType=Ow[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ja,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),Rw(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ow.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let r=new jA({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),o=new MA(e,this._extensions,i.generateMask);this._receiver=r,this._sender=o,this._socket=e,r[ge]=this,o[ge]=this,e[ge]=this,r.on("conclude",eP),r.on("drain",tP),r.on("error",rP),r.on("message",nP),r.on("ping",iP),r.on("pong",oP),o.onerror=sP,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Lw),e.on("data",Fa),e.on("end",Uw),e.on("error",jw),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Qt.extensionName]&&this._extensions[Qt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Dw(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ja,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tm(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ja,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tm(this,e,i);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Qt.extensionName]||(r.compress=!1),this._sender.send(e||ja,r,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re.prototype,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")});Object.defineProperty(re,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re.prototype,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")});Object.defineProperty(re,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re.prototype,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")});Object.defineProperty(re,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});Object.defineProperty(re.prototype,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(re.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(re.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Em])return e[BA];return null},set(e){for(let n of this.listeners(t))if(n[Em]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Em]:!0})}})});re.prototype.addEventListener=WA;re.prototype.removeEventListener=qA;Mw.exports=re;function Rw(t,e,n,i){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:VA,protocolVersion:Im[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=r.autoPong,t._closeTimeout=r.closeTimeout,!Im.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${Im.join(", ")})`);let o;if(e instanceof km)o=e;else try{o=new km(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",u;if(o.protocol!=="ws:"&&!s&&!a?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?u="The URL's pathname is empty":o.hash&&(u="The URL contains a fragment identifier"),u){let _=new SyntaxError(u);if(t._redirects===0)throw _;Ma(t,_);return}let c=s?443:80,l=LA(16).toString("base64"),d=s?RA.request:NA.request,f=new Set,h;if(r.createConnection=r.createConnection||(s?QA:XA),r.defaultPort=r.defaultPort||c,r.port=o.port||c,r.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},r.path=o.pathname+o.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(h=new Qt({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=HA({[Qt.extensionName]:h.offer()})),n.length){for(let _ of n){if(typeof _!="string"||!YA.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(_)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(o.username||o.password)&&(r.auth=`${o.username}:${o.password}`),a){let _=r.path.split(":");r.socketPath=_[0],r.path=_[1]}let p;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?r.socketPath:o.host;let _=i&&i.headers;if(i={...i,headers:{}},_)for(let[S,k]of Object.entries(_))i.headers[S.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let _=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!_||t._originalSecure&&!s)&&(delete r.headers.authorization,delete r.headers.cookie,_||delete r.headers.host,r.auth=void 0)}r.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),p=t._req=d(r),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=d(r);r.timeout&&p.on("timeout",()=>{We(t,p,"Opening handshake has timed out")}),p.on("error",_=>{p===null||p[zw]||(p=t._req=null,Ma(t,_))}),p.on("response",_=>{let S=_.headers.location,k=_.statusCode;if(S&&r.followRedirects&&k>=300&&k<400){if(++t._redirects>r.maxRedirects){We(t,p,"Maximum redirects exceeded");return}p.abort();let P;try{P=new km(S,e)}catch{let E=new SyntaxError(`Invalid URL: ${S}`);Ma(t,E);return}Rw(t,P,n,i)}else t.emit("unexpected-response",p,_)||We(t,p,`Unexpected server response: ${_.statusCode}`)}),p.on("upgrade",(_,S,k)=>{if(t.emit("upgrade",_),t.readyState!==re.CONNECTING)return;p=t._req=null;let P=_.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){We(t,S,"Invalid Upgrade header");return}let C=UA("sha1").update(l+ZA).digest("base64");if(_.headers["sec-websocket-accept"]!==C){We(t,S,"Invalid Sec-WebSocket-Accept header");return}let E=_.headers["sec-websocket-protocol"],T;if(E!==void 0?f.size?f.has(E)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":f.size&&(T="Server sent no subprotocol"),T){We(t,S,T);return}E&&(t._protocol=E);let Z=_.headers["sec-websocket-extensions"];if(Z!==void 0){if(!h){We(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let F;try{F=JA(Z)}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys(F);if(q.length!==1||q[0]!==Qt.extensionName){We(t,S,"Server indicated an extension that was not requested");return}try{h.accept(F[Qt.extensionName])}catch{We(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Qt.extensionName]=h}t.setSocket(S,k,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(p,t):p.end()}function Ma(t,e){t._readyState=re.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function XA(t){return t.path=t.socketPath,Pw.connect(t)}function QA(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Pw.isIP(t.host)?"":t.host),DA.connect(t)}function We(t,e,n){t._readyState=re.CLOSING;let i=new Error(n);Error.captureStackTrace(i,We),e.setHeader?(e[zw]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ma,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Tm(t,e,n){if(e){let i=FA(e)?e.size:KA(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Tt[t.readyState]})`);process.nextTick(n,i)}}function eP(t,e){let n=this[ge];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ge]!==void 0&&(n._socket.removeListener("data",Fa),process.nextTick(Nw,n._socket),t===1005?n.close():n.close(t,e))}function tP(){let t=this[ge];t.isPaused||t._socket.resume()}function rP(t){let e=this[ge];e._socket[ge]!==void 0&&(e._socket.removeListener("data",Fa),process.nextTick(Nw,e._socket),e.close(t[GA])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Aw(){this[ge].emitClose()}function nP(t,e){this[ge].emit("message",t,e)}function iP(t){let e=this[ge];e._autoPong&&e.pong(t,!this._isServer,Cw),e.emit("ping",t)}function oP(t){this[ge].emit("pong",t)}function Nw(t){t.resume()}function sP(t){let e=this[ge];e.readyState!==re.CLOSED&&(e.readyState===re.OPEN&&(e._readyState=re.CLOSING,Dw(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Dw(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Lw(){let t=this[ge];if(this.removeListener("close",Lw),this.removeListener("data",Fa),this.removeListener("end",Uw),t._readyState=re.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ge]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Aw),t._receiver.on("finish",Aw))}function Fa(t){this[ge]._receiver.write(t)||this.pause()}function Uw(){let t=this[ge];t._readyState=re.CLOSING,t._receiver.end(),this.end()}function jw(){let t=this[ge];this.removeListener("error",jw),this.on("error",Cw),t&&(t._readyState=re.CLOSING,this.destroy())}});var Bw=z((M2,Zw)=>{"use strict";var j2=Va(),{Duplex:aP}=ae("stream");function Fw(t){t.emit("close")}function uP(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vw(t){this.removeListener("error",Vw),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function cP(t,e){let n=!0,i=new aP({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&i._readableState.objectMode?o.toString():o;i.push(a)||t.pause()}),t.once("error",function(o){i.destroyed||(n=!1,i.destroy(o))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(r,o){if(t.readyState===t.CLOSED){o(r),process.nextTick(Fw,i);return}let s=!1;t.once("error",function(u){s=!0,o(u)}),t.once("close",function(){s||o(r),process.nextTick(Fw,i)}),n&&t.terminate()},i._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(r,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(r,o,s)});return}t.send(r,s)},i.on("end",uP),i.on("error",Vw),i}Zw.exports=cP});var Om=z((F2,Gw)=>{"use strict";var{tokenChars:lP}=kn();function dP(t){let e=new Set,n=-1,i=-1,r=0;for(r;r<t.length;r++){let s=t.charCodeAt(r);if(i===-1&&lP[s]===1)n===-1&&(n=r);else if(r!==0&&(s===32||s===9))i===-1&&n!==-1&&(i=r);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);i===-1&&(i=r);let a=t.slice(n,i);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,r);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Gw.exports={parse:dP}});var Xw=z((Z2,Yw)=>{"use strict";var fP=ae("events"),Za=ae("http"),{Duplex:V2}=ae("stream"),{createHash:hP}=ae("crypto"),Ww=Ua(),kr=Sn(),pP=Om(),mP=Va(),{CLOSE_TIMEOUT:gP,GUID:vP,kWebSocket:yP}=kt(),_P=/^[+/0-9A-Za-z]{22}==$/,qw=0,Hw=1,Kw=2,Am=class extends fP{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:gP,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:mP,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Za.createServer((i,r)=>{let o=Za.STATUS_CODES[426];r.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),r.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=bP(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,o,s)=>{this.handleUpgrade(r,o,s,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=qw}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Kw){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ji,this);return}if(e&&this.once("close",e),this._state!==Hw)if(this._state=Hw,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ji,this):process.nextTick(Ji,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ji(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,r){n.on("error",Jw);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Er(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Er(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!_P.test(o)){Er(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Er(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ki(n,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=pP.parse(u)}catch{Er(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let f=new kr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Ww.parse(l);h[kr.extensionName]&&(f.accept(h[kr.extensionName]),d[kr.extensionName]=f)}catch{Er(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,p,_,S)=>{if(!h)return Ki(n,p||401,_,S);this.completeUpgrade(d,o,c,e,n,i,r)});return}if(!this.options.verifyClient(f))return Ki(n,401)}this.completeUpgrade(d,o,c,e,n,i,r)}completeUpgrade(e,n,i,r,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[yP])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>qw)return Ki(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hP("sha1").update(n+vP).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(i.size){let d=this.options.handleProtocols?this.options.handleProtocols(i,r):i.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[kr.extensionName]){let d=e[kr.extensionName].params,f=Ww.format({[kr.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",c,r),o.write(c.concat(`\r
182
182
  `).join(`\r
183
- `)),o.removeListener("error",Jw),l.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ji,this)})),a(l,r)}};Yw.exports=Am;function _P(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Ji(t){t._state=Kw,t.emit("close")}function Jw(){this.destroy()}function Ki(t,e,n,i){n=n||Za.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Za.STATUS_CODES[e]}\r
183
+ `)),o.removeListener("error",Jw),l.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ji,this)})),a(l,r)}};Yw.exports=Am;function bP(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Ji(t){t._state=Kw,t.emit("close")}function Jw(){this.destroy()}function Ki(t,e,n,i){n=n||Za.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Za.STATUS_CODES[e]}\r
184
184
  `+Object.keys(i).map(r=>`${r}: ${i[r]}`).join(`\r
185
185
  `)+`\r
186
186
  \r
187
- `+n)}function Er(t,e,n,i,r,o){if(t.listenerCount("wsClientError")){let s=new Error(r);Error.captureStackTrace(s,Er),t.emit("wsClientError",s,n,e)}else Ki(n,i,r,o)}});var bP,$P,xP,wP,SP,kP,Pm,EP,Qw=v(()=>{bP=Je(Bw(),1),$P=Je(Ua(),1),xP=Je(Sn(),1),wP=Je(bm(),1),SP=Je(wm(),1),kP=Je(Om(),1),Pm=Je(Va(),1),EP=Je(Xw(),1)});function IP(t){return Array.isArray(t)?Buffer.concat(t).toString("utf8"):Buffer.isBuffer(t)?t.toString("utf8"):Buffer.from(t).toString("utf8")}var Cm,zm=v(()=>{"use strict";Qw();Cm=(t,e)=>{let n=new Pm.default(t,{headers:e});return{send:i=>n.send(i),close:()=>n.close(),onOpen:i=>{n.on("open",i)},onMessage:i=>{n.on("message",r=>i(IP(r)))},onError:i=>{n.on("error",i)},onClose:i=>{n.on("close",()=>i())}}}});var Yi,Rm=v(()=>{"use strict";am();cm();zm();Yi=class{socketFactory;constructor(e=Cm){this.socketFactory=e}asrEngine(e,n){if(e.provider==="elevenlabs")return new Vi(n,this.socketFactory,e.model);throw new Error(`no stt adapter for provider '${e.provider}'`)}ttsEngine(e,n){if(e.provider==="elevenlabs")return new Zi(n,this.socketFactory,e.model);throw new Error(`no tts adapter for provider '${e.provider}'`)}}});import{randomUUID as TP}from"node:crypto";function Dm(t={}){let e=new mr;B.setLevel(e.logLevel),B.debug("core created",{logLevel:e.logLevel});let{fetchImpl:n}=t,i={configService:t.configService??new Ge,registry:t.registry??new Si(n),voiceRegistry:t.voiceRegistry??new Yi(t.voiceSocketFactory),createTurnEvaluator:t.createTurnEvaluator??(r=>new bn(r,n)),createAddresseeEvaluator:t.createAddresseeEvaluator??(r=>new hn(r,n)),...t.systemPrompt!==void 0&&{systemPrompt:t.systemPrompt},...t.voiceIdentity!==void 0&&{voiceIdentity:t.voiceIdentity},...t.createTurnController!==void 0&&{createTurnController:t.createTurnController},...t.createSmartTurnInference!==void 0&&{createSmartTurnInference:t.createSmartTurnInference},...t.createFrameClassifier!==void 0&&{createFrameClassifier:t.createFrameClassifier},...t.createSegmenter!==void 0&&{createSegmenter:t.createSegmenter},...t.clock!==void 0&&{clock:t.clock}};return new Nm(i)}var OP,AP,Nm,eS=v(()=>{"use strict";Ae();Qh();ep();ip();Gx();aa();Xp();Rm();OP="jarvis-core",AP="0.1.0-dev",Nm=class{deps;constructor(e){this.deps=e}describe(){return Promise.resolve({name:OP,version:AP})}openSession(e){let n=TP();return B.debug("core opened session",{sessionId:n,capabilities:e.clientCapabilities}),Promise.resolve(new Ea(n,e,this.deps))}}});function Ba(t){return t>=200&&t<300?{ok:!0,status:"valid"}:t===401||t===403?{ok:!1,status:"invalid",detail:`key rejected (HTTP ${t})`}:{ok:!1,status:"unreachable",detail:`unexpected response (HTTP ${t})`}}function tS(t){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":t.message:"network error"}function An(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Lm(t,e,n,i){let r=await n(t,{headers:e,signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}`);try{return await r.json()}catch{throw new Error("invalid JSON response")}}function Um(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&i.length>0&&(e[n]=i);if(Object.keys(e).length===0)throw new Error("catalogue curated to nothing");return e}function LP(t){return!/^gpt-(4\.1|4o|5)/.test(t)&&!/^o\d/.test(t)||DP.test(t)?!1:!/-(audio|realtime|transcribe|tts|image|search|codex|chat-latest|instruct|deep-research|pro)\b/.test(t)}var PP,CP,zP,RP,NP,DP,UP,jP,rS,Pn,jm=v(()=>{"use strict";PP=async(t,e,n)=>{let i=await e("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${t}`},signal:n});return Ba(i.status)},CP=async(t,e,n)=>{let i=await e("https://api.anthropic.com/v1/models",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"},signal:n});return Ba(i.status)},zP=async(t,e,n)=>{let i=await e("https://api.deepgram.com/v1/projects",{headers:{Authorization:`Token ${t}`},signal:n});return Ba(i.status)},RP=async(t,e,n)=>{let i=await e("https://api.elevenlabs.io/v1/user",{headers:{"xi-api-key":t},signal:n});return i.status===401||i.status===403?{ok:!1,status:"unverifiable",detail:"an ElevenLabs key scoped to the voice endpoints cannot reach a free validation endpoint; it will be confirmed at first use"}:Ba(i.status)};NP=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Lm("https://api.anthropic.com/v1/models?limit=100",{"x-api-key":t,"anthropic-version":"2023-06-01"},e,n),r=An(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let s of r){if(!An(s)||typeof s.id!="string")continue;let a=typeof s.display_name=="string"?s.display_name:void 0;o.push(a===void 0?{id:s.id}:{id:s.id,label:a})}return Um({text:o})},DP=/-\d{4}-\d{2}-\d{2}$/;UP=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Lm("https://api.openai.com/v1/models",{Authorization:`Bearer ${t}`},e,n),r=An(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let a of r)An(a)&&typeof a.id=="string"&&o.push(a.id);o.sort();let s=a=>o.filter(a).map(u=>({id:u}));return Um({text:s(LP),stt:s(a=>a==="whisper-1"||a.endsWith("-transcribe")),tts:s(a=>/^tts-1(-hd)?$/.test(a)||a.endsWith("-tts")),embedding:s(a=>a.startsWith("text-embedding-3-"))})},jP=async(t,e,n)=>{let i=await Lm("https://api.deepgram.com/v1/models",{},e,n),r=An(i)&&Array.isArray(i.stt)?i.stt:[],o=new Set,s=[];for(let a of r){if(!An(a)||a.streaming!==!0)continue;let{canonical_name:u,architecture:c}=a;typeof u!="string"||typeof c!="string"||c.startsWith("nova-")&&(o.has(u)||(o.add(u),s.push({id:u,architecture:c})))}return s.sort((a,u)=>a.architecture===u.architecture?a.id.localeCompare(u.id,"en"):u.architecture.localeCompare(a.architecture,"en",{numeric:!0})),Um({stt:s.map(({id:a})=>({id:a}))})},rS={elevenlabs:{capabilities:["stt","tts"],defaultModel:{stt:"scribe_v2_realtime",tts:"eleven_flash_v2_5"},keyEnv:"ELEVENLABS_API_KEY",probe:RP},anthropic:{capabilities:["text"],defaultModel:{text:"claude-opus-4-8"},fastModel:{text:"claude-sonnet-5"},keyEnv:"ANTHROPIC_API_KEY",probe:CP,listModels:NP},openai:{capabilities:["text","stt","tts","embedding"],defaultModel:{text:"gpt-4o",stt:"whisper-1",tts:"tts-1",embedding:"text-embedding-3-small"},fastModel:{text:"gpt-4o-mini"},keyEnv:"OPENAI_API_KEY",probe:PP,listModels:UP},deepgram:{capabilities:["stt"],defaultModel:{stt:"nova-3-general"},keyEnv:"DEEPGRAM_API_KEY",probe:zP,listModels:jP,keylessLister:!0}},Pn=class{fetchImpl;timeoutMs=3e3;providers;constructor(e=fetch){this.fetchImpl=e,this.providers=rS}async probe(e,n,i){let r=this.providers[e]?.probe;if(!r)return{ok:!1,status:"unimplemented",detail:`no probe for provider '${e}'`};let o=i?.signal??AbortSignal.timeout(this.timeoutMs);try{return await r(n,this.fetchImpl,o)}catch(s){return{ok:!1,status:"unreachable",detail:tS(s)}}}providersFor(e){return Object.keys(this.providers).filter(n=>this.providers[n].capabilities.includes(e))}defaultModel(e,n){return this.providers[e]?.defaultModel[n]}}});var MP,FP,cM,nS=v(()=>{"use strict";pr();jm();MP=1440*60*1e3,FP={stt:!0,tts:!0,text:!0,embedding:!0},cM=Object.keys(FP)});var Ga=v(()=>{"use strict";eS();ep();jm();nS();ip();np();op();rp();tp();zm();am();cm();Rm();em();Wp();qp();Kp();Pi();Mp();jp();$a();Jp();ap();up()});var Rn=z((vF,uS)=>{"use strict";var YP="2.0.0",XP=Number.MAX_SAFE_INTEGER||9007199254740991,QP=16,eC=250,tC=["major","premajor","minor","preminor","patch","prepatch","prerelease"];uS.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:QP,MAX_SAFE_BUILD_LENGTH:eC,MAX_SAFE_INTEGER:XP,RELEASE_TYPES:tC,SEMVER_SPEC_VERSION:YP,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var eo=z((yF,cS)=>{"use strict";var rC=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};cS.exports=rC});var Nn=z((gt,lS)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Vm,MAX_SAFE_BUILD_LENGTH:nC,MAX_LENGTH:iC}=Rn(),oC=eo();gt=lS.exports={};var sC=gt.re=[],aC=gt.safeRe=[],O=gt.src=[],uC=gt.safeSrc=[],A=gt.t={},cC=0,Zm="[a-zA-Z0-9-]",lC=[["\\s",1],["\\d",iC],[Zm,nC]],dC=t=>{for(let[e,n]of lC)t=t.split(`${e}*`).join(`${e}{0,${n}}`).split(`${e}+`).join(`${e}{1,${n}}`);return t},U=(t,e,n)=>{let i=dC(e),r=cC++;oC(t,r,e),A[t]=r,O[r]=e,uC[r]=i,sC[r]=new RegExp(e,n?"g":void 0),aC[r]=new RegExp(i,n?"g":void 0)};U("NUMERICIDENTIFIER","0|[1-9]\\d*");U("NUMERICIDENTIFIERLOOSE","\\d+");U("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Zm}*`);U("MAINVERSION",`(${O[A.NUMERICIDENTIFIER]})\\.(${O[A.NUMERICIDENTIFIER]})\\.(${O[A.NUMERICIDENTIFIER]})`);U("MAINVERSIONLOOSE",`(${O[A.NUMERICIDENTIFIERLOOSE]})\\.(${O[A.NUMERICIDENTIFIERLOOSE]})\\.(${O[A.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASEIDENTIFIER",`(?:${O[A.NONNUMERICIDENTIFIER]}|${O[A.NUMERICIDENTIFIER]})`);U("PRERELEASEIDENTIFIERLOOSE",`(?:${O[A.NONNUMERICIDENTIFIER]}|${O[A.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASE",`(?:-(${O[A.PRERELEASEIDENTIFIER]}(?:\\.${O[A.PRERELEASEIDENTIFIER]})*))`);U("PRERELEASELOOSE",`(?:-?(${O[A.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${O[A.PRERELEASEIDENTIFIERLOOSE]})*))`);U("BUILDIDENTIFIER",`${Zm}+`);U("BUILD",`(?:\\+(${O[A.BUILDIDENTIFIER]}(?:\\.${O[A.BUILDIDENTIFIER]})*))`);U("FULLPLAIN",`v?${O[A.MAINVERSION]}${O[A.PRERELEASE]}?${O[A.BUILD]}?`);U("FULL",`^${O[A.FULLPLAIN]}$`);U("LOOSEPLAIN",`[v=\\s]*${O[A.MAINVERSIONLOOSE]}${O[A.PRERELEASELOOSE]}?${O[A.BUILD]}?`);U("LOOSE",`^${O[A.LOOSEPLAIN]}$`);U("GTLT","((?:<|>)?=?)");U("XRANGEIDENTIFIERLOOSE",`${O[A.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);U("XRANGEIDENTIFIER",`${O[A.NUMERICIDENTIFIER]}|x|X|\\*`);U("XRANGEPLAIN",`[v=\\s]*(${O[A.XRANGEIDENTIFIER]})(?:\\.(${O[A.XRANGEIDENTIFIER]})(?:\\.(${O[A.XRANGEIDENTIFIER]})(?:${O[A.PRERELEASE]})?${O[A.BUILD]}?)?)?`);U("XRANGEPLAINLOOSE",`[v=\\s]*(${O[A.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[A.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[A.XRANGEIDENTIFIERLOOSE]})(?:${O[A.PRERELEASELOOSE]})?${O[A.BUILD]}?)?)?`);U("XRANGE",`^${O[A.GTLT]}\\s*${O[A.XRANGEPLAIN]}$`);U("XRANGELOOSE",`^${O[A.GTLT]}\\s*${O[A.XRANGEPLAINLOOSE]}$`);U("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Vm}})(?:\\.(\\d{1,${Vm}}))?(?:\\.(\\d{1,${Vm}}))?`);U("COERCE",`${O[A.COERCEPLAIN]}(?:$|[^\\d])`);U("COERCEFULL",O[A.COERCEPLAIN]+`(?:${O[A.PRERELEASE]})?(?:${O[A.BUILD]})?(?:$|[^\\d])`);U("COERCERTL",O[A.COERCE],!0);U("COERCERTLFULL",O[A.COERCEFULL],!0);U("LONETILDE","(?:~>?)");U("TILDETRIM",`(\\s*)${O[A.LONETILDE]}\\s+`,!0);gt.tildeTrimReplace="$1~";U("TILDE",`^${O[A.LONETILDE]}${O[A.XRANGEPLAIN]}$`);U("TILDELOOSE",`^${O[A.LONETILDE]}${O[A.XRANGEPLAINLOOSE]}$`);U("LONECARET","(?:\\^)");U("CARETTRIM",`(\\s*)${O[A.LONECARET]}\\s+`,!0);gt.caretTrimReplace="$1^";U("CARET",`^${O[A.LONECARET]}${O[A.XRANGEPLAIN]}$`);U("CARETLOOSE",`^${O[A.LONECARET]}${O[A.XRANGEPLAINLOOSE]}$`);U("COMPARATORLOOSE",`^${O[A.GTLT]}\\s*(${O[A.LOOSEPLAIN]})$|^$`);U("COMPARATOR",`^${O[A.GTLT]}\\s*(${O[A.FULLPLAIN]})$|^$`);U("COMPARATORTRIM",`(\\s*)${O[A.GTLT]}\\s*(${O[A.LOOSEPLAIN]}|${O[A.XRANGEPLAIN]})`,!0);gt.comparatorTrimReplace="$1$2$3";U("HYPHENRANGE",`^\\s*(${O[A.XRANGEPLAIN]})\\s+-\\s+(${O[A.XRANGEPLAIN]})\\s*$`);U("HYPHENRANGELOOSE",`^\\s*(${O[A.XRANGEPLAINLOOSE]})\\s+-\\s+(${O[A.XRANGEPLAINLOOSE]})\\s*$`);U("STAR","(<|>)?=?\\s*\\*");U("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");U("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ka=z((_F,dS)=>{"use strict";var fC=Object.freeze({loose:!0}),hC=Object.freeze({}),pC=t=>t?typeof t!="object"?fC:t:hC;dS.exports=pC});var Bm=z((bF,pS)=>{"use strict";var fS=/^[0-9]+$/,hS=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let n=fS.test(t),i=fS.test(e);return n&&i&&(t=+t,e=+e),t===e?0:n&&!i?-1:i&&!n?1:t<e?-1:1},mC=(t,e)=>hS(e,t);pS.exports={compareIdentifiers:hS,rcompareIdentifiers:mC}});var _e=z(($F,gS)=>{"use strict";var Ya=eo(),{MAX_LENGTH:mS,MAX_SAFE_INTEGER:Xa}=Rn(),{safeRe:Qa,t:eu}=Nn(),gC=Ka(),{compareIdentifiers:Gm}=Bm(),vC=(t,e)=>{let n=e.split(".");if(n.length>t.length)return!1;for(let i=0;i<n.length;i++)if(Gm(t[i],n[i])!==0)return!1;return!0},Wm=class t{constructor(e,n){if(n=gC(n),e instanceof t){if(e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>mS)throw new TypeError(`version is longer than ${mS} characters`);Ya("SemVer",e,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=e.trim().match(n.loose?Qa[eu.LOOSE]:Qa[eu.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Xa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Xa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Xa||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(r=>{if(/^[0-9]+$/.test(r)){let o=+r;if(o>=0&&o<Xa)return o}return r}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Ya("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let n=0;do{let i=this.prerelease[n],r=e.prerelease[n];if(Ya("prerelease compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Gm(i,r)}while(++n)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let n=0;do{let i=this.build[n],r=e.build[n];if(Ya("build compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Gm(i,r)}while(++n)}inc(e,n,i){if(e.startsWith("pre")){if(!n&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let r=`-${n}`.match(this.options.loose?Qa[eu.PRERELEASELOOSE]:Qa[eu.PRERELEASE]);if(!r||r[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,i),this.inc("pre",n,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,i),this.inc("pre",n,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let r=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[r];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(n===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(r)}}if(n){let o=[n,r];if(i===!1&&(o=[n]),vC(this.prerelease,n)){let s=this.prerelease[n.split(".").length];isNaN(s)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};gS.exports=Wm});var er=z((xF,yS)=>{"use strict";var vS=_e(),yC=(t,e,n=!1)=>{if(t instanceof vS)return t;try{return new vS(t,e)}catch(i){if(!n)return null;throw i}};yS.exports=yC});var bS=z((wF,_S)=>{"use strict";var _C=er(),bC=(t,e)=>{let n=_C(t,e);return n?n.version:null};_S.exports=bC});var xS=z((SF,$S)=>{"use strict";var $C=er(),xC=(t,e)=>{let n=$C(t.trim().replace(/^[=v]+/,""),e);return n?n.version:null};$S.exports=xC});var kS=z((kF,SS)=>{"use strict";var wS=_e(),wC=(t,e,n,i,r)=>{typeof n=="string"&&(r=i,i=n,n=void 0);try{return new wS(t instanceof wS?t.version:t,n).inc(e,i,r).version}catch{return null}};SS.exports=wC});var TS=z((EF,IS)=>{"use strict";var ES=er(),SC=(t,e)=>{let n=ES(t,null,!0),i=ES(e,null,!0),r=n.compare(i);if(r===0)return null;let o=r>0,s=o?n:i,a=o?i:n,u=!!s.prerelease.length;if(!!a.prerelease.length&&!u){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let l=u?"pre":"";return n.major!==i.major?l+"major":n.minor!==i.minor?l+"minor":n.patch!==i.patch?l+"patch":"prerelease"};IS.exports=SC});var AS=z((IF,OS)=>{"use strict";var kC=_e(),EC=(t,e)=>new kC(t,e).major;OS.exports=EC});var CS=z((TF,PS)=>{"use strict";var IC=_e(),TC=(t,e)=>new IC(t,e).minor;PS.exports=TC});var RS=z((OF,zS)=>{"use strict";var OC=_e(),AC=(t,e)=>new OC(t,e).patch;zS.exports=AC});var DS=z((AF,NS)=>{"use strict";var PC=er(),CC=(t,e)=>{let n=PC(t,e);return n&&n.prerelease.length?n.prerelease:null};NS.exports=CC});var tt=z((PF,US)=>{"use strict";var LS=_e(),zC=(t,e,n)=>new LS(t,n).compare(new LS(e,n));US.exports=zC});var MS=z((CF,jS)=>{"use strict";var RC=tt(),NC=(t,e,n)=>RC(e,t,n);jS.exports=NC});var VS=z((zF,FS)=>{"use strict";var DC=tt(),LC=(t,e)=>DC(t,e,!0);FS.exports=LC});var tu=z((RF,BS)=>{"use strict";var ZS=_e(),UC=(t,e,n)=>{let i=new ZS(t,n),r=new ZS(e,n);return i.compare(r)||i.compareBuild(r)};BS.exports=UC});var WS=z((NF,GS)=>{"use strict";var jC=tu(),MC=(t,e)=>t.sort((n,i)=>jC(n,i,e));GS.exports=MC});var HS=z((DF,qS)=>{"use strict";var FC=tu(),VC=(t,e)=>t.sort((n,i)=>FC(i,n,e));qS.exports=VC});var to=z((LF,JS)=>{"use strict";var ZC=tt(),BC=(t,e,n)=>ZC(t,e,n)>0;JS.exports=BC});var ru=z((UF,KS)=>{"use strict";var GC=tt(),WC=(t,e,n)=>GC(t,e,n)<0;KS.exports=WC});var qm=z((jF,YS)=>{"use strict";var qC=tt(),HC=(t,e,n)=>qC(t,e,n)===0;YS.exports=HC});var Hm=z((MF,XS)=>{"use strict";var JC=tt(),KC=(t,e,n)=>JC(t,e,n)!==0;XS.exports=KC});var nu=z((FF,QS)=>{"use strict";var YC=tt(),XC=(t,e,n)=>YC(t,e,n)>=0;QS.exports=XC});var iu=z((VF,e0)=>{"use strict";var QC=tt(),ez=(t,e,n)=>QC(t,e,n)<=0;e0.exports=ez});var Jm=z((ZF,t0)=>{"use strict";var tz=qm(),rz=Hm(),nz=to(),iz=nu(),oz=ru(),sz=iu(),az=(t,e,n,i)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t===n;case"!==":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t!==n;case"":case"=":case"==":return tz(t,n,i);case"!=":return rz(t,n,i);case">":return nz(t,n,i);case">=":return iz(t,n,i);case"<":return oz(t,n,i);case"<=":return sz(t,n,i);default:throw new TypeError(`Invalid operator: ${e}`)}};t0.exports=az});var n0=z((BF,r0)=>{"use strict";var uz=_e(),cz=er(),{safeRe:ou,t:su}=Nn(),lz=(t,e)=>{if(t instanceof uz)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let n=null;if(!e.rtl)n=t.match(e.includePrerelease?ou[su.COERCEFULL]:ou[su.COERCE]);else{let u=e.includePrerelease?ou[su.COERCERTLFULL]:ou[su.COERCERTL],c;for(;(c=u.exec(t))&&(!n||n.index+n[0].length!==t.length);)(!n||c.index+c[0].length!==n.index+n[0].length)&&(n=c),u.lastIndex=c.index+c[1].length+c[2].length;u.lastIndex=-1}if(n===null)return null;let i=n[2],r=n[3]||"0",o=n[4]||"0",s=e.includePrerelease&&n[5]?`-${n[5]}`:"",a=e.includePrerelease&&n[6]?`+${n[6]}`:"";return cz(`${i}.${r}.${o}${s}${a}`,e)};r0.exports=lz});var o0=z((GF,i0)=>{"use strict";var dz=er(),fz=Rn(),hz=_e(),pz=(t,e,n)=>{if(!fz.RELEASE_TYPES.includes(e))return null;let i=mz(t,n);return i&&gz(i,e)},mz=(t,e)=>{let n=t instanceof hz?t.version:t;return dz(n,e)},gz=(t,e)=>{if(vz(e))return t.version;switch(t.prerelease=[],e){case"major":t.minor=0,t.patch=0;break;case"minor":t.patch=0;break}return t.format()},vz=t=>t.startsWith("pre");i0.exports=pz});var a0=z((WF,s0)=>{"use strict";var Km=class{constructor(){this.max=1e3,this.map=new Map}get(e){let n=this.map.get(e);if(n!==void 0)return this.map.delete(e),this.map.set(e,n),n}delete(e){return this.map.delete(e)}set(e,n){if(!this.delete(e)&&n!==void 0){if(this.map.size>=this.max){let r=this.map.keys().next().value;this.delete(r)}this.map.set(e,n)}return this}};s0.exports=Km});var rt=z((qF,d0)=>{"use strict";var yz=/\s+/g,Ym=class t{constructor(e,n){if(n=bz(n),e instanceof t)return e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease?e:new t(e.raw,n);if(e instanceof Xm)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=e.trim().replace(yz," "),this.set=this.raw.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(r=>!c0(r[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let r of this.set)if(r.length===1&&Oz(r[0])){this.set=[r];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let n=this.set[e];for(let i=0;i<n.length;i++)i>0&&(this.formatted+=" "),this.formatted+=n[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(Tz,"");let i=((this.options.includePrerelease&&Ez)|(this.options.loose&&Iz))+":"+e,r=u0.get(i);if(r)return r;let o=this.options.loose,s=o?Pe[be.HYPHENRANGELOOSE]:Pe[be.HYPHENRANGE];e=e.replace(s,jz(this.options.includePrerelease)),te("hyphen replace",e),e=e.replace(Pe[be.COMPARATORTRIM],wz),te("comparator trim",e),e=e.replace(Pe[be.TILDETRIM],Sz),te("tilde trim",e),e=e.replace(Pe[be.CARETTRIM],kz),te("caret trim",e);let a=e.split(" ").map(d=>Az(d,this.options)).join(" ").split(/\s+/).map(d=>Uz(d,this.options));o&&(a=a.filter(d=>(te("loose invalid filter",d,this.options),!!d.match(Pe[be.COMPARATORLOOSE])))),te("range list",a);let u=new Map,c=a.map(d=>new Xm(d,this.options));for(let d of c){if(c0(d))return[d];u.set(d.value,d)}u.size>1&&u.has("")&&u.delete("");let l=[...u.values()];return u0.set(i,l),l}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(i=>l0(i,n)&&e.set.some(r=>l0(r,n)&&i.every(o=>r.every(s=>o.intersects(s,n)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new $z(e,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(Mz(this.set[n],e,this.options))return!0;return!1}};d0.exports=Ym;var _z=a0(),u0=new _z,bz=Ka(),Xm=ro(),te=eo(),$z=_e(),{safeRe:Pe,src:xz,t:be,comparatorTrimReplace:wz,tildeTrimReplace:Sz,caretTrimReplace:kz}=Nn(),{FLAG_INCLUDE_PRERELEASE:Ez,FLAG_LOOSE:Iz}=Rn(),Tz=new RegExp(xz[be.BUILD],"g"),c0=t=>t.value==="<0.0.0-0",Oz=t=>t.value==="",l0=(t,e)=>{let n=!0,i=t.slice(),r=i.pop();for(;n&&i.length;)n=i.every(o=>r.intersects(o,e)),r=i.pop();return n},Az=(t,e)=>(t=t.replace(Pe[be.BUILD],""),te("comp",t,e),t=zz(t,e),te("caret",t),t=Pz(t,e),te("tildes",t),t=Nz(t,e),te("xrange",t),t=Lz(t,e),te("stars",t),t),Ce=t=>!t||t.toLowerCase()==="x"||t==="*",Pz=(t,e)=>t.trim().split(/\s+/).map(n=>Cz(n,e)).join(" "),Cz=(t,e)=>{let n=e.loose?Pe[be.TILDELOOSE]:Pe[be.TILDE];return t.replace(n,(i,r,o,s,a)=>{te("tilde",t,i,r,o,s,a);let u;return Ce(r)?u="":Ce(o)?u=`>=${r}.0.0 <${+r+1}.0.0-0`:Ce(s)?u=`>=${r}.${o}.0 <${r}.${+o+1}.0-0`:a?(te("replaceTilde pr",a),u=`>=${r}.${o}.${s}-${a} <${r}.${+o+1}.0-0`):u=`>=${r}.${o}.${s} <${r}.${+o+1}.0-0`,te("tilde return",u),u})},zz=(t,e)=>t.trim().split(/\s+/).map(n=>Rz(n,e)).join(" "),Rz=(t,e)=>{te("caret",t,e);let n=e.loose?Pe[be.CARETLOOSE]:Pe[be.CARET],i=e.includePrerelease?"-0":"";return t.replace(n,(r,o,s,a,u)=>{te("caret",t,r,o,s,a,u);let c;return Ce(o)?c="":Ce(s)?c=`>=${o}.0.0${i} <${+o+1}.0.0-0`:Ce(a)?o==="0"?c=`>=${o}.${s}.0${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.0${i} <${+o+1}.0.0-0`:u?(te("replaceCaret pr",u),o==="0"?s==="0"?c=`>=${o}.${s}.${a}-${u} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}-${u} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a}-${u} <${+o+1}.0.0-0`):(te("no pr"),o==="0"?s==="0"?c=`>=${o}.${s}.${a}${i} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),te("caret return",c),c})},Nz=(t,e)=>(te("replaceXRanges",t,e),t.split(/\s+/).map(n=>Dz(n,e)).join(" ")),Dz=(t,e)=>{t=t.trim();let n=e.loose?Pe[be.XRANGELOOSE]:Pe[be.XRANGE];return t.replace(n,(i,r,o,s,a,u)=>{te("xRange",t,i,r,o,s,a,u);let c=Ce(o),l=c||Ce(s),d=l||Ce(a),f=d;return r==="="&&f&&(r=""),u=e.includePrerelease?"-0":"",c?r===">"||r==="<"?i="<0.0.0-0":i="*":r&&f?(l&&(s=0),a=0,r===">"?(r=">=",l?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):r==="<="&&(r="<",l?o=+o+1:s=+s+1),r==="<"&&(u="-0"),i=`${r+o}.${s}.${a}${u}`):l?i=`>=${o}.0.0${u} <${+o+1}.0.0-0`:d&&(i=`>=${o}.${s}.0${u} <${o}.${+s+1}.0-0`),te("xRange return",i),i})},Lz=(t,e)=>(te("replaceStars",t,e),t.trim().replace(Pe[be.STAR],"")),Uz=(t,e)=>(te("replaceGTE0",t,e),t.trim().replace(Pe[e.includePrerelease?be.GTE0PRE:be.GTE0],"")),jz=t=>(e,n,i,r,o,s,a,u,c,l,d,f)=>(Ce(i)?n="":Ce(r)?n=`>=${i}.0.0${t?"-0":""}`:Ce(o)?n=`>=${i}.${r}.0${t?"-0":""}`:s?n=`>=${n}`:n=`>=${n}${t?"-0":""}`,Ce(c)?u="":Ce(l)?u=`<${+c+1}.0.0-0`:Ce(d)?u=`<${c}.${+l+1}.0-0`:f?u=`<=${c}.${l}.${d}-${f}`:t?u=`<${c}.${l}.${+d+1}-0`:u=`<=${u}`,`${n} ${u}`.trim()),Mz=(t,e,n)=>{for(let i=0;i<t.length;i++)if(!t[i].test(e))return!1;if(e.prerelease.length&&!n.includePrerelease){for(let i=0;i<t.length;i++)if(te(t[i].semver),t[i].semver!==Xm.ANY&&t[i].semver.prerelease.length>0){let r=t[i].semver;if(r.major===e.major&&r.minor===e.minor&&r.patch===e.patch)return!0}return!1}return!0}});var ro=z((HF,v0)=>{"use strict";var no=Symbol("SemVer ANY"),tg=class t{static get ANY(){return no}constructor(e,n){if(n=f0(n),e instanceof t){if(e.loose===!!n.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),eg("comparator",e,n),this.options=n,this.loose=!!n.loose,this.parse(e),this.semver===no?this.value="":this.value=this.operator+this.semver.version,eg("comp",this)}parse(e){let n=this.options.loose?h0[p0.COMPARATORLOOSE]:h0[p0.COMPARATOR],i=e.match(n);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new m0(i[2],this.options.loose):this.semver=no}toString(){return this.value}test(e){if(eg("Comparator.test",e,this.options.loose),this.semver===no||e===no)return!0;if(typeof e=="string")try{e=new m0(e,this.options)}catch{return!1}return Qm(e,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new g0(e.value,n).test(this.value):e.operator===""?e.value===""?!0:new g0(this.value,n).test(e.semver):(n=f0(n),n.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Qm(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Qm(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};v0.exports=tg;var f0=Ka(),{safeRe:h0,t:p0}=Nn(),Qm=Jm(),eg=eo(),m0=_e(),g0=rt()});var io=z((JF,y0)=>{"use strict";var Fz=rt(),Vz=(t,e,n)=>{try{e=new Fz(e,n)}catch{return!1}return e.test(t)};y0.exports=Vz});var b0=z((KF,_0)=>{"use strict";var Zz=rt(),Bz=(t,e)=>new Zz(t,e).set.map(n=>n.map(i=>i.value).join(" ").trim().split(" "));_0.exports=Bz});var x0=z((YF,$0)=>{"use strict";var Gz=_e(),Wz=rt(),qz=(t,e,n)=>{let i=null,r=null,o=null;try{o=new Wz(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===-1)&&(i=s,r=new Gz(i,n))}),i};$0.exports=qz});var S0=z((XF,w0)=>{"use strict";var Hz=_e(),Jz=rt(),Kz=(t,e,n)=>{let i=null,r=null,o=null;try{o=new Jz(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===1)&&(i=s,r=new Hz(i,n))}),i};w0.exports=Kz});var I0=z((QF,E0)=>{"use strict";var rg=_e(),Yz=rt(),k0=to(),Xz=(t,e)=>{t=new Yz(t,e);let n=new rg("0.0.0");if(t.test(n)||(n=new rg("0.0.0-0"),t.test(n)))return n;n=null;for(let i=0;i<t.set.length;++i){let r=t.set[i],o=null;r.forEach(s=>{let a=new rg(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||k0(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!n||k0(n,o))&&(n=o)}return n&&t.test(n)?n:null};E0.exports=Xz});var O0=z((eV,T0)=>{"use strict";var Qz=rt(),eR=(t,e)=>{try{return new Qz(t,e).range||"*"}catch{return null}};T0.exports=eR});var au=z((tV,z0)=>{"use strict";var tR=_e(),C0=ro(),{ANY:rR}=C0,nR=rt(),iR=io(),A0=to(),P0=ru(),oR=iu(),sR=nu(),aR=(t,e,n,i)=>{t=new tR(t,i),e=new nR(e,i);let r,o,s,a,u;switch(n){case">":r=A0,o=oR,s=P0,a=">",u=">=";break;case"<":r=P0,o=sR,s=A0,a="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(iR(t,e,i))return!1;for(let c=0;c<e.set.length;++c){let l=e.set[c],d=null,f=null;if(l.forEach(h=>{h.semver===rR&&(h=new C0(">=0.0.0")),d=d||h,f=f||h,r(h.semver,d.semver,i)?d=h:s(h.semver,f.semver,i)&&(f=h)}),d.operator===a||d.operator===u||(!f.operator||f.operator===a)&&o(t,f.semver))return!1;if(f.operator===u&&s(t,f.semver))return!1}return!0};z0.exports=aR});var N0=z((rV,R0)=>{"use strict";var uR=au(),cR=(t,e,n)=>uR(t,e,">",n);R0.exports=cR});var L0=z((nV,D0)=>{"use strict";var lR=au(),dR=(t,e,n)=>lR(t,e,"<",n);D0.exports=dR});var M0=z((iV,j0)=>{"use strict";var U0=rt(),fR=(t,e,n)=>(t=new U0(t,n),e=new U0(e,n),t.intersects(e,n));j0.exports=fR});var V0=z((oV,F0)=>{"use strict";var hR=io(),pR=tt();F0.exports=(t,e,n)=>{let i=[],r=null,o=null,s=t.sort((l,d)=>pR(l,d,n));for(let l of s)hR(l,e,n)?(o=l,r||(r=l)):(o&&i.push([r,o]),o=null,r=null);r&&i.push([r,null]);let a=[];for(let[l,d]of i)l===d?a.push(l):!d&&l===s[0]?a.push("*"):d?l===s[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);let u=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return u.length<c.length?u:e}});var H0=z((sV,q0)=>{"use strict";var Z0=rt(),og=ro(),{ANY:ng}=og,ig=io(),sg=tt(),mR=(t,e,n={})=>{if(t===e)return!0;t=new Z0(t,n),e=new Z0(e,n);let i=!1;e:for(let r of t.set){for(let o of e.set){let s=vR(r,o,n);if(i=i||s!==null,s)continue e}if(i)return!1}return!0},gR=[new og(">=0.0.0-0")],B0=[new og(">=0.0.0")],vR=(t,e,n)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===ng){if(e.length===1&&e[0].semver===ng)return!0;n.includePrerelease?t=gR:t=B0}if(e.length===1&&e[0].semver===ng){if(n.includePrerelease)return!0;e=B0}let i=new Set,r,o;for(let h of t)h.operator===">"||h.operator===">="?r=G0(r,h,n):h.operator==="<"||h.operator==="<="?o=W0(o,h,n):i.add(h.semver);if(i.size>1)return null;let s;if(r&&o){if(s=sg(r.semver,o.semver,n),s>0)return null;if(s===0&&(r.operator!==">="||o.operator!=="<="))return null}for(let h of i){if(r&&!ig(h,String(r),n)||o&&!ig(h,String(o),n))return null;for(let p of e)if(!ig(h,String(p),n))return!1;return!0}let a,u,c,l,d=o&&!n.includePrerelease&&o.semver.prerelease.length?o.semver:!1,f=r&&!n.includePrerelease&&r.semver.prerelease.length?r.semver:!1;d&&d.prerelease.length===1&&o.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let h of e){if(l=l||h.operator===">"||h.operator===">=",c=c||h.operator==="<"||h.operator==="<=",r){if(f&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===f.major&&h.semver.minor===f.minor&&h.semver.patch===f.patch&&(f=!1),h.operator===">"||h.operator===">="){if(a=G0(r,h,n),a===h&&a!==r)return!1}else if(r.operator===">="&&!h.test(r.semver))return!1}if(o){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(u=W0(o,h,n),u===h&&u!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||r)&&s!==0)return!1}return!(r&&c&&!o&&s!==0||o&&l&&!r&&s!==0||f||d)},G0=(t,e,n)=>{if(!t)return e;let i=sg(t.semver,e.semver,n);return i>0?t:i<0||e.operator===">"&&t.operator===">="?e:t},W0=(t,e,n)=>{if(!t)return e;let i=sg(t.semver,e.semver,n);return i<0?t:i>0||e.operator==="<"&&t.operator==="<="?e:t};q0.exports=mR});var X0=z((aV,Y0)=>{"use strict";var ag=Nn(),J0=Rn(),yR=_e(),K0=Bm(),_R=er(),bR=bS(),$R=xS(),xR=kS(),wR=TS(),SR=AS(),kR=CS(),ER=RS(),IR=DS(),TR=tt(),OR=MS(),AR=VS(),PR=tu(),CR=WS(),zR=HS(),RR=to(),NR=ru(),DR=qm(),LR=Hm(),UR=nu(),jR=iu(),MR=Jm(),FR=n0(),VR=o0(),ZR=ro(),BR=rt(),GR=io(),WR=b0(),qR=x0(),HR=S0(),JR=I0(),KR=O0(),YR=au(),XR=N0(),QR=L0(),eN=M0(),tN=V0(),rN=H0();Y0.exports={parse:_R,valid:bR,clean:$R,inc:xR,diff:wR,major:SR,minor:kR,patch:ER,prerelease:IR,compare:TR,rcompare:OR,compareLoose:AR,compareBuild:PR,sort:CR,rsort:zR,gt:RR,lt:NR,eq:DR,neq:LR,gte:UR,lte:jR,cmp:MR,coerce:FR,truncate:VR,Comparator:ZR,Range:BR,satisfies:GR,toComparators:WR,maxSatisfying:qR,minSatisfying:HR,minVersion:JR,validRange:KR,outside:YR,gtr:XR,ltr:QR,intersects:eN,simplifyRange:tN,subset:rN,SemVer:yR,re:ag.re,src:ag.src,tokens:ag.t,SEMVER_SPEC_VERSION:J0.SEMVER_SPEC_VERSION,RELEASE_TYPES:J0.RELEASE_TYPES,compareIdentifiers:K0.compareIdentifiers,rcompareIdentifiers:K0.rcompareIdentifiers}});var nk=z((gV,ug)=>{var lu=process||{},tk=lu.argv||[],cu=lu.env||{},sN=!(cu.NO_COLOR||tk.includes("--no-color"))&&(!!cu.FORCE_COLOR||tk.includes("--color")||lu.platform==="win32"||(lu.stdout||{}).isTTY&&cu.TERM!=="dumb"||!!cu.CI),aN=(t,e,n=t)=>i=>{let r=""+i,o=r.indexOf(e,t.length);return~o?t+uN(r,e,n,o)+e:t+r+e},uN=(t,e,n,i)=>{let r="",o=0;do r+=t.substring(o,i)+n,o=i+e.length,i=t.indexOf(e,o);while(~i);return r+t.substring(o)},rk=(t=sN)=>{let e=t?aN:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};ug.exports=rk();ug.exports.createColors=rk});var pg=z((VV,xk)=>{"use strict";var hg={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},PN={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},CN={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?hg.up():"");return t&&(e+=hg.left),e}};xk.exports={cursor:hg,scroll:PN,erase:CN,beep:"\x07"}});function fE(t,e){if(e<=1)return t;let n=Math.floor(t.length/e),i=new Int16Array(n);for(let r=0;r<n;r++){let o=0,s=r*e;for(let a=0;a<e;a++)o+=t[s+a];i[r]=Math.round(o/e)}return i}var Au,hE=v(()=>{"use strict";Au=class{step;pos=0;prev=0;primed=!1;constructor(e,n){if(e<=0||n<=0)throw new RangeError("resampler rates must be positive");this.step=e/n}process(e){if(e.length===0)return new Int16Array(0);let n=[],i=e.length-1,r=this.primed?this.pos:0;for(;;){let o=Math.floor(r);if(o+1>i)break;let s=o<0?this.prev:e[o],a=e[o+1];n.push(Math.round(s+(a-s)*(r-o))),r+=this.step}return this.prev=e[i],this.primed=!0,this.pos=r-e.length,Int16Array.from(n)}}});function mE(t){return t.byteLength/2/I4}function T4(t){let e=t.byteLength>>1,n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let r=0;r<e;r++)i[r]=n.getInt16(r*2,!0);return i}var pE,I4,Pu,gE=v(()=>{"use strict";Ae();Ga();pE=32,I4=16,Pu=class{constructor(e,n,i={}){this.vad=e;this.onSpeech=n;this.speechThreshold=i.speechThreshold??.5,this.onsetMs=i.onsetMs??2*pE,this.holdoffMs=i.holdoffMs??300,this.energyThreshold=i.energyThreshold??.01,this.log=i.log??B}vad;onSpeech;speechThreshold;onsetMs;holdoffMs;energyThreshold;log;inSpeech=!1;speechRunMs=0;silenceRunMs=0;degraded=!1;closed=!1;feed(e){if(!(this.closed||e.byteLength===0)){if(this.degraded){this.applyVerdict(Gt(e,this.energyThreshold),mE(e));return}this.vad.process(T4(e)).then(n=>{if(!this.closed)for(let i of n)this.applyVerdict(i>=this.speechThreshold,pE)},n=>{this.closed||(this.degrade(n),this.applyVerdict(Gt(e,this.energyThreshold),mE(e)))})}}close(){this.closed=!0}applyVerdict(e,n){e?(this.silenceRunMs=0,this.speechRunMs+=n,!this.inSpeech&&this.speechRunMs>=this.onsetMs&&(this.inSpeech=!0,this.onSpeech())):(this.speechRunMs=0,this.inSpeech&&(this.silenceRunMs+=n,this.silenceRunMs>=this.holdoffMs&&(this.inSpeech=!1,this.silenceRunMs=0)))}degrade(e){this.degraded||(this.degraded=!0,this.log.debug("barge-in DEGRADED to energy onset - silero vad failed; speech onsets detect on RMS energy for the rest of the capture session",{error:e instanceof Error?e.message:String(e)}))}}});var zg={};He(zg,{DecibriCapture:()=>Pg,DecibriPlayback:()=>Cg,hasInputDevice:()=>P4});import{Microphone as O4,Speaker as A4,inputDevices as yE}from"decibri";function P4(){try{return yE().length>0}catch(t){return B.debug("audio input enumeration failed; treating as no microphone",{error:t}),!1}}function C4(){try{let t=yE(),e=t.find(n=>n.isDefault)??t[0];if(e&&e.defaultSampleRate>=1e3&&e.maxInputChannels>=1)return{sampleRate:Math.round(e.defaultSampleRate),channels:e.maxInputChannels}}catch(t){B.debug("could not read default input device; opening at 16k mono",{error:t})}return{sampleRate:po,channels:Cu}}function z4(t){return Math.max(64,Math.min(65536,Math.round(t/10)))}function R4(t,e,n){let i=new Uint8Array(t),r=new Int16Array(i.buffer,0,i.byteLength>>1),o=n.process(fE(r,e));return Buffer.from(o.buffer,o.byteOffset,o.byteLength)}function L4(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}var po,Cu,_E,vE,Pg,N4,D4,Cg,Rg=v(()=>{"use strict";Ae();Ga();hE();gE();po=16e3,Cu=1,_E="int16",vE=.01;Pg=class{constructor(e={}){this.deps=e}deps;mic=null;onData=null;onSpeech=null;onErr=null;vad=null;detector=null;async start(e){let{sampleRate:n,channels:i}=C4(),r=(this.deps.createVad??(()=>new br))(),o=null;try{await r.load(),o=new Pu(r,()=>e.onSpeechStart(),{energyThreshold:vE})}catch(u){B.debug("silero vad unavailable; barge-in falls back to decibri energy vad",{error:u}),r.dispose().catch(()=>{})}let s;try{s=await O4.open({sampleRate:n,channels:i,dtype:_E,...o?{vad:!1}:{vad:"energy",vadThreshold:vE},framesPerBuffer:z4(n)})}catch(u){throw o?.close(),o&&r.dispose().catch(()=>{}),u}this.vad=o?r:null,this.detector=o;let a=n===po&&i===Cu?null:new Au(n,po);this.onData=a?u=>{let c=R4(u,i,a);c.byteLength>0&&(this.detector?.feed(c),e.onFrame(c,Date.now()))}:u=>{this.detector?.feed(u),e.onFrame(u,Date.now())},this.onSpeech=()=>e.onSpeechStart(),this.onErr=u=>e.onError(u),s.on("data",this.onData),s.on("speech",this.onSpeech),s.on("error",this.onErr),this.mic=s}async stop(){let e=this.mic;this.mic=null,this.detector?.close(),this.detector=null,e&&(this.onData&&e.removeListener("data",this.onData),this.onSpeech&&e.removeListener("speech",this.onSpeech),this.onErr&&e.removeListener("error",this.onErr),e.on("error",()=>{}),e.stop()),this.onData=null,this.onSpeech=null,this.onErr=null;let n=this.vad;this.vad=null,n&&await n.dispose().catch(()=>{})}},N4=po*Cu*2/1e3,D4=250,Cg=class{speaker=null;writeChain=Promise.resolve();generation=0;closed=!1;playoutEndAtMs=0;drainWakes=new Set;play(e){if(this.closed)return;let n=this.generation;this.writeChain=this.writeChain.then(async()=>{if(!(this.closed||n!==this.generation))try{if(await this.ensureSpeaker().writeAsync(L4(e)),this.closed||n!==this.generation)return;this.playoutEndAtMs=Math.max(this.playoutEndAtMs,Date.now())+e.byteLength/N4}catch(i){B.debug("playback write skipped",{error:i})}})}flush(){this.generation++,this.playoutEndAtMs=0;let e=this.speaker;this.speaker=null,e?.stop();for(let n of[...this.drainWakes])n()}async drained(){await this.writeChain;let e=this.speaker;if(!e)return;let n=Promise.resolve().then(()=>e.drainAsync()).catch(s=>{B.debug("playback drain interrupted",{error:s})}),i=Math.max(0,this.playoutEndAtMs-Date.now())+D4,r=this.sleep(i);await Promise.race([n,r.done]),r.wake();let o=this.playoutEndAtMs-Date.now();o>0&&await this.sleep(o).done}sleep(e){let n;return{done:new Promise(r=>{let o=setTimeout(()=>n(),e);n=()=>{clearTimeout(o),this.drainWakes.delete(n),r()},this.drainWakes.add(n)}),wake:n}}close(){return this.closed=!0,this.flush(),Promise.resolve()}ensureSpeaker(){return this.speaker??=new A4({sampleRate:po,channels:Cu,dtype:_E}),this.speaker}}});Ae();Ga();ki();import{readFileSync as U4}from"node:fs";import{randomUUID as j4}from"node:crypto";var mt=class extends Error{constructor(e,n,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Ot=class extends mt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Xi=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Wa(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as GP}from"node:events";import Fm from"node:child_process";import At from"node:path";import Ha from"node:fs";import G from"node:process";import{stripVTControlCharacters as WP}from"node:util";import{stripVTControlCharacters as VP}from"node:util";var Qi=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let n=e.commands.filter(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&n.push(i),this.sortSubcommands&&n.sort((r,o)=>r.name().localeCompare(o.name())),n}compareOptions(e,n){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(n))}visibleOptions(e){let n=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),o=i.long&&e._findOption(i.long);!r&&!o?n.push(i):i.long&&!o?n.push(e.createOption(i.long,i.description)):i.short&&!r&&n.push(e.createOption(i.short,i.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let i=e.parent;i;i=i.parent){let r=i.options.filter(o=>!o.hidden);n.push(...r)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(i=>Wa(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(r)))),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(r)))),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.name()+" "+i;return i+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatItemList(e,n,i){return n.length===0?[]:[i.styleTitle(e),...n,""]}groupItems(e,n,i){let r=new Map;return e.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[])}),n.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[]),r.get(s).push(o)}),r}formatHelp(e,n){let i=n.padWidth(e,n),r=n.helpWidth??80;function o(d,f){return n.formatItem(d,i,f,n)}let s=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(e))}`,""],a=n.commandDescription(e);a.length>0&&(s=s.concat([n.boxWrap(n.styleCommandDescription(a),r),""]));let u=n.visibleArguments(e).map(d=>o(n.styleArgumentTerm(n.argumentTerm(d)),n.styleArgumentDescription(n.argumentDescription(d))));if(s=s.concat(this.formatItemList("Arguments:",u,n)),this.groupItems(e.options,n.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let h=d.map(p=>o(n.styleOptionTerm(n.optionTerm(p)),n.styleOptionDescription(n.optionDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),n.showGlobalOptions){let d=n.visibleGlobalOptions(e).map(f=>o(n.styleOptionTerm(n.optionTerm(f)),n.styleOptionDescription(n.optionDescription(f))));s=s.concat(this.formatItemList("Global Options:",d,n))}return this.groupItems(e.commands,n.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,f)=>{let h=d.map(p=>o(n.styleSubcommandTerm(n.subcommandTerm(p)),n.styleSubcommandDescription(n.subcommandDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),s.join(`
188
- `)}displayWidth(e){return VP(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,n,i,r){let s=" ".repeat(2);if(!i)return s+e;let a=e.padEnd(n+e.length-r.displayWidth(e)),u=2,l=(this.helpWidth??80)-n-u-2,d;return l<this.minWidthToWrap||r.preformatted(i)?d=i:d=r.boxWrap(i,l).replace(/\n/g,`
187
+ `+n)}function Er(t,e,n,i,r,o){if(t.listenerCount("wsClientError")){let s=new Error(r);Error.captureStackTrace(s,Er),t.emit("wsClientError",s,n,e)}else Ki(n,i,r,o)}});var $P,xP,wP,SP,kP,EP,Pm,IP,Qw=v(()=>{$P=Je(Bw(),1),xP=Je(Ua(),1),wP=Je(Sn(),1),SP=Je(bm(),1),kP=Je(wm(),1),EP=Je(Om(),1),Pm=Je(Va(),1),IP=Je(Xw(),1)});function TP(t){return Array.isArray(t)?Buffer.concat(t).toString("utf8"):Buffer.isBuffer(t)?t.toString("utf8"):Buffer.from(t).toString("utf8")}var Cm,zm=v(()=>{"use strict";Qw();Cm=(t,e)=>{let n=new Pm.default(t,{headers:e});return{send:i=>n.send(i),close:()=>n.close(),onOpen:i=>{n.on("open",i)},onMessage:i=>{n.on("message",r=>i(TP(r)))},onError:i=>{n.on("error",i)},onClose:i=>{n.on("close",()=>i())}}}});var Yi,Rm=v(()=>{"use strict";am();cm();zm();Yi=class{socketFactory;constructor(e=Cm){this.socketFactory=e}asrEngine(e,n){if(e.provider==="elevenlabs")return new Vi(n,this.socketFactory,e.model);throw new Error(`no stt adapter for provider '${e.provider}'`)}ttsEngine(e,n){if(e.provider==="elevenlabs")return new Zi(n,this.socketFactory,e.model);throw new Error(`no tts adapter for provider '${e.provider}'`)}}});import{randomUUID as OP}from"node:crypto";function Dm(t={}){let e=new mr;B.setLevel(e.logLevel),B.debug("core created",{logLevel:e.logLevel});let{fetchImpl:n}=t,i={configService:t.configService??new Ge,registry:t.registry??new Si(n),voiceRegistry:t.voiceRegistry??new Yi(t.voiceSocketFactory),createTurnEvaluator:t.createTurnEvaluator??(r=>new bn(r,n)),createAddresseeEvaluator:t.createAddresseeEvaluator??(r=>new hn(r,n)),...t.systemPrompt!==void 0&&{systemPrompt:t.systemPrompt},...t.voiceIdentity!==void 0&&{voiceIdentity:t.voiceIdentity},...t.createTurnController!==void 0&&{createTurnController:t.createTurnController},...t.createSmartTurnInference!==void 0&&{createSmartTurnInference:t.createSmartTurnInference},...t.createFrameClassifier!==void 0&&{createFrameClassifier:t.createFrameClassifier},...t.createSegmenter!==void 0&&{createSegmenter:t.createSegmenter},...t.clock!==void 0&&{clock:t.clock}};return new Nm(i)}var AP,PP,Nm,eS=v(()=>{"use strict";Ae();Qh();ep();ip();Gx();aa();Xp();Rm();AP="jarvis-core",PP="0.1.0-dev",Nm=class{deps;constructor(e){this.deps=e}describe(){return Promise.resolve({name:AP,version:PP})}openSession(e){let n=OP();return B.debug("core opened session",{sessionId:n,capabilities:e.clientCapabilities}),Promise.resolve(new Ea(n,e,this.deps))}}});function Ba(t){return t>=200&&t<300?{ok:!0,status:"valid"}:t===401||t===403?{ok:!1,status:"invalid",detail:`key rejected (HTTP ${t})`}:{ok:!1,status:"unreachable",detail:`unexpected response (HTTP ${t})`}}function tS(t){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":t.message:"network error"}function An(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Lm(t,e,n,i){let r=await n(t,{headers:e,signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}`);try{return await r.json()}catch{throw new Error("invalid JSON response")}}function Um(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&i.length>0&&(e[n]=i);if(Object.keys(e).length===0)throw new Error("catalogue curated to nothing");return e}function UP(t){return!/^gpt-(4\.1|4o|5)/.test(t)&&!/^o\d/.test(t)||LP.test(t)?!1:!/-(audio|realtime|transcribe|tts|image|search|codex|chat-latest|instruct|deep-research|pro)\b/.test(t)}var CP,zP,RP,NP,DP,LP,jP,MP,rS,Pn,jm=v(()=>{"use strict";CP=async(t,e,n)=>{let i=await e("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${t}`},signal:n});return Ba(i.status)},zP=async(t,e,n)=>{let i=await e("https://api.anthropic.com/v1/models",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"},signal:n});return Ba(i.status)},RP=async(t,e,n)=>{let i=await e("https://api.deepgram.com/v1/projects",{headers:{Authorization:`Token ${t}`},signal:n});return Ba(i.status)},NP=async(t,e,n)=>{let i=await e("https://api.elevenlabs.io/v1/user",{headers:{"xi-api-key":t},signal:n});return i.status===401||i.status===403?{ok:!1,status:"unverifiable",detail:"an ElevenLabs key scoped to the voice endpoints cannot reach a free validation endpoint; it will be confirmed at first use"}:Ba(i.status)};DP=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Lm("https://api.anthropic.com/v1/models?limit=100",{"x-api-key":t,"anthropic-version":"2023-06-01"},e,n),r=An(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let s of r){if(!An(s)||typeof s.id!="string")continue;let a=typeof s.display_name=="string"?s.display_name:void 0;o.push(a===void 0?{id:s.id}:{id:s.id,label:a})}return Um({text:o})},LP=/-\d{4}-\d{2}-\d{2}$/;jP=async(t,e,n)=>{if(!t)throw new Error("API key required");let i=await Lm("https://api.openai.com/v1/models",{Authorization:`Bearer ${t}`},e,n),r=An(i)&&Array.isArray(i.data)?i.data:[],o=[];for(let a of r)An(a)&&typeof a.id=="string"&&o.push(a.id);o.sort();let s=a=>o.filter(a).map(u=>({id:u}));return Um({text:s(UP),stt:s(a=>a==="whisper-1"||a.endsWith("-transcribe")),tts:s(a=>/^tts-1(-hd)?$/.test(a)||a.endsWith("-tts")),embedding:s(a=>a.startsWith("text-embedding-3-"))})},MP=async(t,e,n)=>{let i=await Lm("https://api.deepgram.com/v1/models",{},e,n),r=An(i)&&Array.isArray(i.stt)?i.stt:[],o=new Set,s=[];for(let a of r){if(!An(a)||a.streaming!==!0)continue;let{canonical_name:u,architecture:c}=a;typeof u!="string"||typeof c!="string"||c.startsWith("nova-")&&(o.has(u)||(o.add(u),s.push({id:u,architecture:c})))}return s.sort((a,u)=>a.architecture===u.architecture?a.id.localeCompare(u.id,"en"):u.architecture.localeCompare(a.architecture,"en",{numeric:!0})),Um({stt:s.map(({id:a})=>({id:a}))})},rS={elevenlabs:{capabilities:["stt","tts"],defaultModel:{stt:"scribe_v2_realtime",tts:"eleven_flash_v2_5"},keyEnv:"ELEVENLABS_API_KEY",probe:NP},anthropic:{capabilities:["text"],defaultModel:{text:"claude-opus-4-8"},fastModel:{text:"claude-sonnet-5"},keyEnv:"ANTHROPIC_API_KEY",probe:zP,listModels:DP},openai:{capabilities:["text","stt","tts","embedding"],defaultModel:{text:"gpt-4o",stt:"whisper-1",tts:"tts-1",embedding:"text-embedding-3-small"},fastModel:{text:"gpt-4o-mini"},keyEnv:"OPENAI_API_KEY",probe:CP,listModels:jP},deepgram:{capabilities:["stt"],defaultModel:{stt:"nova-3-general"},keyEnv:"DEEPGRAM_API_KEY",probe:RP,listModels:MP,keylessLister:!0}},Pn=class{fetchImpl;timeoutMs=3e3;providers;constructor(e=fetch){this.fetchImpl=e,this.providers=rS}async probe(e,n,i){let r=this.providers[e]?.probe;if(!r)return{ok:!1,status:"unimplemented",detail:`no probe for provider '${e}'`};let o=i?.signal??AbortSignal.timeout(this.timeoutMs);try{return await r(n,this.fetchImpl,o)}catch(s){return{ok:!1,status:"unreachable",detail:tS(s)}}}providersFor(e){return Object.keys(this.providers).filter(n=>this.providers[n].capabilities.includes(e))}defaultModel(e,n){return this.providers[e]?.defaultModel[n]}}});var FP,VP,lM,nS=v(()=>{"use strict";pr();jm();FP=1440*60*1e3,VP={stt:!0,tts:!0,text:!0,embedding:!0},lM=Object.keys(VP)});var Ga=v(()=>{"use strict";eS();ep();jm();nS();ip();np();op();rp();tp();zm();am();cm();Rm();em();Wp();qp();Kp();Pi();Mp();jp();$a();Jp();ap();up()});var Rn=z((yF,uS)=>{"use strict";var XP="2.0.0",QP=Number.MAX_SAFE_INTEGER||9007199254740991,eC=16,tC=250,rC=["major","premajor","minor","preminor","patch","prepatch","prerelease"];uS.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:eC,MAX_SAFE_BUILD_LENGTH:tC,MAX_SAFE_INTEGER:QP,RELEASE_TYPES:rC,SEMVER_SPEC_VERSION:XP,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var eo=z((_F,cS)=>{"use strict";var nC=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};cS.exports=nC});var Nn=z((gt,lS)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Vm,MAX_SAFE_BUILD_LENGTH:iC,MAX_LENGTH:oC}=Rn(),sC=eo();gt=lS.exports={};var aC=gt.re=[],uC=gt.safeRe=[],O=gt.src=[],cC=gt.safeSrc=[],A=gt.t={},lC=0,Zm="[a-zA-Z0-9-]",dC=[["\\s",1],["\\d",oC],[Zm,iC]],fC=t=>{for(let[e,n]of dC)t=t.split(`${e}*`).join(`${e}{0,${n}}`).split(`${e}+`).join(`${e}{1,${n}}`);return t},U=(t,e,n)=>{let i=fC(e),r=lC++;sC(t,r,e),A[t]=r,O[r]=e,cC[r]=i,aC[r]=new RegExp(e,n?"g":void 0),uC[r]=new RegExp(i,n?"g":void 0)};U("NUMERICIDENTIFIER","0|[1-9]\\d*");U("NUMERICIDENTIFIERLOOSE","\\d+");U("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Zm}*`);U("MAINVERSION",`(${O[A.NUMERICIDENTIFIER]})\\.(${O[A.NUMERICIDENTIFIER]})\\.(${O[A.NUMERICIDENTIFIER]})`);U("MAINVERSIONLOOSE",`(${O[A.NUMERICIDENTIFIERLOOSE]})\\.(${O[A.NUMERICIDENTIFIERLOOSE]})\\.(${O[A.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASEIDENTIFIER",`(?:${O[A.NONNUMERICIDENTIFIER]}|${O[A.NUMERICIDENTIFIER]})`);U("PRERELEASEIDENTIFIERLOOSE",`(?:${O[A.NONNUMERICIDENTIFIER]}|${O[A.NUMERICIDENTIFIERLOOSE]})`);U("PRERELEASE",`(?:-(${O[A.PRERELEASEIDENTIFIER]}(?:\\.${O[A.PRERELEASEIDENTIFIER]})*))`);U("PRERELEASELOOSE",`(?:-?(${O[A.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${O[A.PRERELEASEIDENTIFIERLOOSE]})*))`);U("BUILDIDENTIFIER",`${Zm}+`);U("BUILD",`(?:\\+(${O[A.BUILDIDENTIFIER]}(?:\\.${O[A.BUILDIDENTIFIER]})*))`);U("FULLPLAIN",`v?${O[A.MAINVERSION]}${O[A.PRERELEASE]}?${O[A.BUILD]}?`);U("FULL",`^${O[A.FULLPLAIN]}$`);U("LOOSEPLAIN",`[v=\\s]*${O[A.MAINVERSIONLOOSE]}${O[A.PRERELEASELOOSE]}?${O[A.BUILD]}?`);U("LOOSE",`^${O[A.LOOSEPLAIN]}$`);U("GTLT","((?:<|>)?=?)");U("XRANGEIDENTIFIERLOOSE",`${O[A.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);U("XRANGEIDENTIFIER",`${O[A.NUMERICIDENTIFIER]}|x|X|\\*`);U("XRANGEPLAIN",`[v=\\s]*(${O[A.XRANGEIDENTIFIER]})(?:\\.(${O[A.XRANGEIDENTIFIER]})(?:\\.(${O[A.XRANGEIDENTIFIER]})(?:${O[A.PRERELEASE]})?${O[A.BUILD]}?)?)?`);U("XRANGEPLAINLOOSE",`[v=\\s]*(${O[A.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[A.XRANGEIDENTIFIERLOOSE]})(?:\\.(${O[A.XRANGEIDENTIFIERLOOSE]})(?:${O[A.PRERELEASELOOSE]})?${O[A.BUILD]}?)?)?`);U("XRANGE",`^${O[A.GTLT]}\\s*${O[A.XRANGEPLAIN]}$`);U("XRANGELOOSE",`^${O[A.GTLT]}\\s*${O[A.XRANGEPLAINLOOSE]}$`);U("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Vm}})(?:\\.(\\d{1,${Vm}}))?(?:\\.(\\d{1,${Vm}}))?`);U("COERCE",`${O[A.COERCEPLAIN]}(?:$|[^\\d])`);U("COERCEFULL",O[A.COERCEPLAIN]+`(?:${O[A.PRERELEASE]})?(?:${O[A.BUILD]})?(?:$|[^\\d])`);U("COERCERTL",O[A.COERCE],!0);U("COERCERTLFULL",O[A.COERCEFULL],!0);U("LONETILDE","(?:~>?)");U("TILDETRIM",`(\\s*)${O[A.LONETILDE]}\\s+`,!0);gt.tildeTrimReplace="$1~";U("TILDE",`^${O[A.LONETILDE]}${O[A.XRANGEPLAIN]}$`);U("TILDELOOSE",`^${O[A.LONETILDE]}${O[A.XRANGEPLAINLOOSE]}$`);U("LONECARET","(?:\\^)");U("CARETTRIM",`(\\s*)${O[A.LONECARET]}\\s+`,!0);gt.caretTrimReplace="$1^";U("CARET",`^${O[A.LONECARET]}${O[A.XRANGEPLAIN]}$`);U("CARETLOOSE",`^${O[A.LONECARET]}${O[A.XRANGEPLAINLOOSE]}$`);U("COMPARATORLOOSE",`^${O[A.GTLT]}\\s*(${O[A.LOOSEPLAIN]})$|^$`);U("COMPARATOR",`^${O[A.GTLT]}\\s*(${O[A.FULLPLAIN]})$|^$`);U("COMPARATORTRIM",`(\\s*)${O[A.GTLT]}\\s*(${O[A.LOOSEPLAIN]}|${O[A.XRANGEPLAIN]})`,!0);gt.comparatorTrimReplace="$1$2$3";U("HYPHENRANGE",`^\\s*(${O[A.XRANGEPLAIN]})\\s+-\\s+(${O[A.XRANGEPLAIN]})\\s*$`);U("HYPHENRANGELOOSE",`^\\s*(${O[A.XRANGEPLAINLOOSE]})\\s+-\\s+(${O[A.XRANGEPLAINLOOSE]})\\s*$`);U("STAR","(<|>)?=?\\s*\\*");U("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");U("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ka=z((bF,dS)=>{"use strict";var hC=Object.freeze({loose:!0}),pC=Object.freeze({}),mC=t=>t?typeof t!="object"?hC:t:pC;dS.exports=mC});var Bm=z(($F,pS)=>{"use strict";var fS=/^[0-9]+$/,hS=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let n=fS.test(t),i=fS.test(e);return n&&i&&(t=+t,e=+e),t===e?0:n&&!i?-1:i&&!n?1:t<e?-1:1},gC=(t,e)=>hS(e,t);pS.exports={compareIdentifiers:hS,rcompareIdentifiers:gC}});var _e=z((xF,gS)=>{"use strict";var Ya=eo(),{MAX_LENGTH:mS,MAX_SAFE_INTEGER:Xa}=Rn(),{safeRe:Qa,t:eu}=Nn(),vC=Ka(),{compareIdentifiers:Gm}=Bm(),yC=(t,e)=>{let n=e.split(".");if(n.length>t.length)return!1;for(let i=0;i<n.length;i++)if(Gm(t[i],n[i])!==0)return!1;return!0},Wm=class t{constructor(e,n){if(n=vC(n),e instanceof t){if(e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>mS)throw new TypeError(`version is longer than ${mS} characters`);Ya("SemVer",e,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=e.trim().match(n.loose?Qa[eu.LOOSE]:Qa[eu.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Xa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Xa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Xa||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(r=>{if(/^[0-9]+$/.test(r)){let o=+r;if(o>=0&&o<Xa)return o}return r}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Ya("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let n=0;do{let i=this.prerelease[n],r=e.prerelease[n];if(Ya("prerelease compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Gm(i,r)}while(++n)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let n=0;do{let i=this.build[n],r=e.build[n];if(Ya("build compare",n,i,r),i===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;if(i===r)continue;return Gm(i,r)}while(++n)}inc(e,n,i){if(e.startsWith("pre")){if(!n&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let r=`-${n}`.match(this.options.loose?Qa[eu.PRERELEASELOOSE]:Qa[eu.PRERELEASE]);if(!r||r[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,i),this.inc("pre",n,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,i),this.inc("pre",n,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let r=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[r];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(n===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(r)}}if(n){let o=[n,r];if(i===!1&&(o=[n]),yC(this.prerelease,n)){let s=this.prerelease[n.split(".").length];isNaN(s)&&(this.prerelease=o)}else this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};gS.exports=Wm});var er=z((wF,yS)=>{"use strict";var vS=_e(),_C=(t,e,n=!1)=>{if(t instanceof vS)return t;try{return new vS(t,e)}catch(i){if(!n)return null;throw i}};yS.exports=_C});var bS=z((SF,_S)=>{"use strict";var bC=er(),$C=(t,e)=>{let n=bC(t,e);return n?n.version:null};_S.exports=$C});var xS=z((kF,$S)=>{"use strict";var xC=er(),wC=(t,e)=>{let n=xC(t.trim().replace(/^[=v]+/,""),e);return n?n.version:null};$S.exports=wC});var kS=z((EF,SS)=>{"use strict";var wS=_e(),SC=(t,e,n,i,r)=>{typeof n=="string"&&(r=i,i=n,n=void 0);try{return new wS(t instanceof wS?t.version:t,n).inc(e,i,r).version}catch{return null}};SS.exports=SC});var TS=z((IF,IS)=>{"use strict";var ES=er(),kC=(t,e)=>{let n=ES(t,null,!0),i=ES(e,null,!0),r=n.compare(i);if(r===0)return null;let o=r>0,s=o?n:i,a=o?i:n,u=!!s.prerelease.length;if(!!a.prerelease.length&&!u){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let l=u?"pre":"";return n.major!==i.major?l+"major":n.minor!==i.minor?l+"minor":n.patch!==i.patch?l+"patch":"prerelease"};IS.exports=kC});var AS=z((TF,OS)=>{"use strict";var EC=_e(),IC=(t,e)=>new EC(t,e).major;OS.exports=IC});var CS=z((OF,PS)=>{"use strict";var TC=_e(),OC=(t,e)=>new TC(t,e).minor;PS.exports=OC});var RS=z((AF,zS)=>{"use strict";var AC=_e(),PC=(t,e)=>new AC(t,e).patch;zS.exports=PC});var DS=z((PF,NS)=>{"use strict";var CC=er(),zC=(t,e)=>{let n=CC(t,e);return n&&n.prerelease.length?n.prerelease:null};NS.exports=zC});var tt=z((CF,US)=>{"use strict";var LS=_e(),RC=(t,e,n)=>new LS(t,n).compare(new LS(e,n));US.exports=RC});var MS=z((zF,jS)=>{"use strict";var NC=tt(),DC=(t,e,n)=>NC(e,t,n);jS.exports=DC});var VS=z((RF,FS)=>{"use strict";var LC=tt(),UC=(t,e)=>LC(t,e,!0);FS.exports=UC});var tu=z((NF,BS)=>{"use strict";var ZS=_e(),jC=(t,e,n)=>{let i=new ZS(t,n),r=new ZS(e,n);return i.compare(r)||i.compareBuild(r)};BS.exports=jC});var WS=z((DF,GS)=>{"use strict";var MC=tu(),FC=(t,e)=>t.sort((n,i)=>MC(n,i,e));GS.exports=FC});var HS=z((LF,qS)=>{"use strict";var VC=tu(),ZC=(t,e)=>t.sort((n,i)=>VC(i,n,e));qS.exports=ZC});var to=z((UF,JS)=>{"use strict";var BC=tt(),GC=(t,e,n)=>BC(t,e,n)>0;JS.exports=GC});var ru=z((jF,KS)=>{"use strict";var WC=tt(),qC=(t,e,n)=>WC(t,e,n)<0;KS.exports=qC});var qm=z((MF,YS)=>{"use strict";var HC=tt(),JC=(t,e,n)=>HC(t,e,n)===0;YS.exports=JC});var Hm=z((FF,XS)=>{"use strict";var KC=tt(),YC=(t,e,n)=>KC(t,e,n)!==0;XS.exports=YC});var nu=z((VF,QS)=>{"use strict";var XC=tt(),QC=(t,e,n)=>XC(t,e,n)>=0;QS.exports=QC});var iu=z((ZF,e0)=>{"use strict";var ez=tt(),tz=(t,e,n)=>ez(t,e,n)<=0;e0.exports=tz});var Jm=z((BF,t0)=>{"use strict";var rz=qm(),nz=Hm(),iz=to(),oz=nu(),sz=ru(),az=iu(),uz=(t,e,n,i)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t===n;case"!==":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t!==n;case"":case"=":case"==":return rz(t,n,i);case"!=":return nz(t,n,i);case">":return iz(t,n,i);case">=":return oz(t,n,i);case"<":return sz(t,n,i);case"<=":return az(t,n,i);default:throw new TypeError(`Invalid operator: ${e}`)}};t0.exports=uz});var n0=z((GF,r0)=>{"use strict";var cz=_e(),lz=er(),{safeRe:ou,t:su}=Nn(),dz=(t,e)=>{if(t instanceof cz)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let n=null;if(!e.rtl)n=t.match(e.includePrerelease?ou[su.COERCEFULL]:ou[su.COERCE]);else{let u=e.includePrerelease?ou[su.COERCERTLFULL]:ou[su.COERCERTL],c;for(;(c=u.exec(t))&&(!n||n.index+n[0].length!==t.length);)(!n||c.index+c[0].length!==n.index+n[0].length)&&(n=c),u.lastIndex=c.index+c[1].length+c[2].length;u.lastIndex=-1}if(n===null)return null;let i=n[2],r=n[3]||"0",o=n[4]||"0",s=e.includePrerelease&&n[5]?`-${n[5]}`:"",a=e.includePrerelease&&n[6]?`+${n[6]}`:"";return lz(`${i}.${r}.${o}${s}${a}`,e)};r0.exports=dz});var o0=z((WF,i0)=>{"use strict";var fz=er(),hz=Rn(),pz=_e(),mz=(t,e,n)=>{if(!hz.RELEASE_TYPES.includes(e))return null;let i=gz(t,n);return i&&vz(i,e)},gz=(t,e)=>{let n=t instanceof pz?t.version:t;return fz(n,e)},vz=(t,e)=>{if(yz(e))return t.version;switch(t.prerelease=[],e){case"major":t.minor=0,t.patch=0;break;case"minor":t.patch=0;break}return t.format()},yz=t=>t.startsWith("pre");i0.exports=mz});var a0=z((qF,s0)=>{"use strict";var Km=class{constructor(){this.max=1e3,this.map=new Map}get(e){let n=this.map.get(e);if(n!==void 0)return this.map.delete(e),this.map.set(e,n),n}delete(e){return this.map.delete(e)}set(e,n){if(!this.delete(e)&&n!==void 0){if(this.map.size>=this.max){let r=this.map.keys().next().value;this.delete(r)}this.map.set(e,n)}return this}};s0.exports=Km});var rt=z((HF,d0)=>{"use strict";var _z=/\s+/g,Ym=class t{constructor(e,n){if(n=$z(n),e instanceof t)return e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease?e:new t(e.raw,n);if(e instanceof Xm)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=e.trim().replace(_z," "),this.set=this.raw.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(r=>!c0(r[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let r of this.set)if(r.length===1&&Az(r[0])){this.set=[r];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let n=this.set[e];for(let i=0;i<n.length;i++)i>0&&(this.formatted+=" "),this.formatted+=n[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(Oz,"");let i=((this.options.includePrerelease&&Iz)|(this.options.loose&&Tz))+":"+e,r=u0.get(i);if(r)return r;let o=this.options.loose,s=o?Pe[be.HYPHENRANGELOOSE]:Pe[be.HYPHENRANGE];e=e.replace(s,Mz(this.options.includePrerelease)),te("hyphen replace",e),e=e.replace(Pe[be.COMPARATORTRIM],Sz),te("comparator trim",e),e=e.replace(Pe[be.TILDETRIM],kz),te("tilde trim",e),e=e.replace(Pe[be.CARETTRIM],Ez),te("caret trim",e);let a=e.split(" ").map(d=>Pz(d,this.options)).join(" ").split(/\s+/).map(d=>jz(d,this.options));o&&(a=a.filter(d=>(te("loose invalid filter",d,this.options),!!d.match(Pe[be.COMPARATORLOOSE])))),te("range list",a);let u=new Map,c=a.map(d=>new Xm(d,this.options));for(let d of c){if(c0(d))return[d];u.set(d.value,d)}u.size>1&&u.has("")&&u.delete("");let l=[...u.values()];return u0.set(i,l),l}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(i=>l0(i,n)&&e.set.some(r=>l0(r,n)&&i.every(o=>r.every(s=>o.intersects(s,n)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new xz(e,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(Fz(this.set[n],e,this.options))return!0;return!1}};d0.exports=Ym;var bz=a0(),u0=new bz,$z=Ka(),Xm=ro(),te=eo(),xz=_e(),{safeRe:Pe,src:wz,t:be,comparatorTrimReplace:Sz,tildeTrimReplace:kz,caretTrimReplace:Ez}=Nn(),{FLAG_INCLUDE_PRERELEASE:Iz,FLAG_LOOSE:Tz}=Rn(),Oz=new RegExp(wz[be.BUILD],"g"),c0=t=>t.value==="<0.0.0-0",Az=t=>t.value==="",l0=(t,e)=>{let n=!0,i=t.slice(),r=i.pop();for(;n&&i.length;)n=i.every(o=>r.intersects(o,e)),r=i.pop();return n},Pz=(t,e)=>(t=t.replace(Pe[be.BUILD],""),te("comp",t,e),t=Rz(t,e),te("caret",t),t=Cz(t,e),te("tildes",t),t=Dz(t,e),te("xrange",t),t=Uz(t,e),te("stars",t),t),Ce=t=>!t||t.toLowerCase()==="x"||t==="*",Cz=(t,e)=>t.trim().split(/\s+/).map(n=>zz(n,e)).join(" "),zz=(t,e)=>{let n=e.loose?Pe[be.TILDELOOSE]:Pe[be.TILDE];return t.replace(n,(i,r,o,s,a)=>{te("tilde",t,i,r,o,s,a);let u;return Ce(r)?u="":Ce(o)?u=`>=${r}.0.0 <${+r+1}.0.0-0`:Ce(s)?u=`>=${r}.${o}.0 <${r}.${+o+1}.0-0`:a?(te("replaceTilde pr",a),u=`>=${r}.${o}.${s}-${a} <${r}.${+o+1}.0-0`):u=`>=${r}.${o}.${s} <${r}.${+o+1}.0-0`,te("tilde return",u),u})},Rz=(t,e)=>t.trim().split(/\s+/).map(n=>Nz(n,e)).join(" "),Nz=(t,e)=>{te("caret",t,e);let n=e.loose?Pe[be.CARETLOOSE]:Pe[be.CARET],i=e.includePrerelease?"-0":"";return t.replace(n,(r,o,s,a,u)=>{te("caret",t,r,o,s,a,u);let c;return Ce(o)?c="":Ce(s)?c=`>=${o}.0.0${i} <${+o+1}.0.0-0`:Ce(a)?o==="0"?c=`>=${o}.${s}.0${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.0${i} <${+o+1}.0.0-0`:u?(te("replaceCaret pr",u),o==="0"?s==="0"?c=`>=${o}.${s}.${a}-${u} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}-${u} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a}-${u} <${+o+1}.0.0-0`):(te("no pr"),o==="0"?s==="0"?c=`>=${o}.${s}.${a}${i} <${o}.${s}.${+a+1}-0`:c=`>=${o}.${s}.${a}${i} <${o}.${+s+1}.0-0`:c=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),te("caret return",c),c})},Dz=(t,e)=>(te("replaceXRanges",t,e),t.split(/\s+/).map(n=>Lz(n,e)).join(" ")),Lz=(t,e)=>{t=t.trim();let n=e.loose?Pe[be.XRANGELOOSE]:Pe[be.XRANGE];return t.replace(n,(i,r,o,s,a,u)=>{te("xRange",t,i,r,o,s,a,u);let c=Ce(o),l=c||Ce(s),d=l||Ce(a),f=d;return r==="="&&f&&(r=""),u=e.includePrerelease?"-0":"",c?r===">"||r==="<"?i="<0.0.0-0":i="*":r&&f?(l&&(s=0),a=0,r===">"?(r=">=",l?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):r==="<="&&(r="<",l?o=+o+1:s=+s+1),r==="<"&&(u="-0"),i=`${r+o}.${s}.${a}${u}`):l?i=`>=${o}.0.0${u} <${+o+1}.0.0-0`:d&&(i=`>=${o}.${s}.0${u} <${o}.${+s+1}.0-0`),te("xRange return",i),i})},Uz=(t,e)=>(te("replaceStars",t,e),t.trim().replace(Pe[be.STAR],"")),jz=(t,e)=>(te("replaceGTE0",t,e),t.trim().replace(Pe[e.includePrerelease?be.GTE0PRE:be.GTE0],"")),Mz=t=>(e,n,i,r,o,s,a,u,c,l,d,f)=>(Ce(i)?n="":Ce(r)?n=`>=${i}.0.0${t?"-0":""}`:Ce(o)?n=`>=${i}.${r}.0${t?"-0":""}`:s?n=`>=${n}`:n=`>=${n}${t?"-0":""}`,Ce(c)?u="":Ce(l)?u=`<${+c+1}.0.0-0`:Ce(d)?u=`<${c}.${+l+1}.0-0`:f?u=`<=${c}.${l}.${d}-${f}`:t?u=`<${c}.${l}.${+d+1}-0`:u=`<=${u}`,`${n} ${u}`.trim()),Fz=(t,e,n)=>{for(let i=0;i<t.length;i++)if(!t[i].test(e))return!1;if(e.prerelease.length&&!n.includePrerelease){for(let i=0;i<t.length;i++)if(te(t[i].semver),t[i].semver!==Xm.ANY&&t[i].semver.prerelease.length>0){let r=t[i].semver;if(r.major===e.major&&r.minor===e.minor&&r.patch===e.patch)return!0}return!1}return!0}});var ro=z((JF,v0)=>{"use strict";var no=Symbol("SemVer ANY"),tg=class t{static get ANY(){return no}constructor(e,n){if(n=f0(n),e instanceof t){if(e.loose===!!n.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),eg("comparator",e,n),this.options=n,this.loose=!!n.loose,this.parse(e),this.semver===no?this.value="":this.value=this.operator+this.semver.version,eg("comp",this)}parse(e){let n=this.options.loose?h0[p0.COMPARATORLOOSE]:h0[p0.COMPARATOR],i=e.match(n);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new m0(i[2],this.options.loose):this.semver=no}toString(){return this.value}test(e){if(eg("Comparator.test",e,this.options.loose),this.semver===no||e===no)return!0;if(typeof e=="string")try{e=new m0(e,this.options)}catch{return!1}return Qm(e,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new g0(e.value,n).test(this.value):e.operator===""?e.value===""?!0:new g0(this.value,n).test(e.semver):(n=f0(n),n.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Qm(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Qm(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};v0.exports=tg;var f0=Ka(),{safeRe:h0,t:p0}=Nn(),Qm=Jm(),eg=eo(),m0=_e(),g0=rt()});var io=z((KF,y0)=>{"use strict";var Vz=rt(),Zz=(t,e,n)=>{try{e=new Vz(e,n)}catch{return!1}return e.test(t)};y0.exports=Zz});var b0=z((YF,_0)=>{"use strict";var Bz=rt(),Gz=(t,e)=>new Bz(t,e).set.map(n=>n.map(i=>i.value).join(" ").trim().split(" "));_0.exports=Gz});var x0=z((XF,$0)=>{"use strict";var Wz=_e(),qz=rt(),Hz=(t,e,n)=>{let i=null,r=null,o=null;try{o=new qz(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===-1)&&(i=s,r=new Wz(i,n))}),i};$0.exports=Hz});var S0=z((QF,w0)=>{"use strict";var Jz=_e(),Kz=rt(),Yz=(t,e,n)=>{let i=null,r=null,o=null;try{o=new Kz(e,n)}catch{return null}return t.forEach(s=>{o.test(s)&&(!i||r.compare(s)===1)&&(i=s,r=new Jz(i,n))}),i};w0.exports=Yz});var I0=z((eV,E0)=>{"use strict";var rg=_e(),Xz=rt(),k0=to(),Qz=(t,e)=>{t=new Xz(t,e);let n=new rg("0.0.0");if(t.test(n)||(n=new rg("0.0.0-0"),t.test(n)))return n;n=null;for(let i=0;i<t.set.length;++i){let r=t.set[i],o=null;r.forEach(s=>{let a=new rg(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||k0(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!n||k0(n,o))&&(n=o)}return n&&t.test(n)?n:null};E0.exports=Qz});var O0=z((tV,T0)=>{"use strict";var eR=rt(),tR=(t,e)=>{try{return new eR(t,e).range||"*"}catch{return null}};T0.exports=tR});var au=z((rV,z0)=>{"use strict";var rR=_e(),C0=ro(),{ANY:nR}=C0,iR=rt(),oR=io(),A0=to(),P0=ru(),sR=iu(),aR=nu(),uR=(t,e,n,i)=>{t=new rR(t,i),e=new iR(e,i);let r,o,s,a,u;switch(n){case">":r=A0,o=sR,s=P0,a=">",u=">=";break;case"<":r=P0,o=aR,s=A0,a="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(oR(t,e,i))return!1;for(let c=0;c<e.set.length;++c){let l=e.set[c],d=null,f=null;if(l.forEach(h=>{h.semver===nR&&(h=new C0(">=0.0.0")),d=d||h,f=f||h,r(h.semver,d.semver,i)?d=h:s(h.semver,f.semver,i)&&(f=h)}),d.operator===a||d.operator===u||(!f.operator||f.operator===a)&&o(t,f.semver))return!1;if(f.operator===u&&s(t,f.semver))return!1}return!0};z0.exports=uR});var N0=z((nV,R0)=>{"use strict";var cR=au(),lR=(t,e,n)=>cR(t,e,">",n);R0.exports=lR});var L0=z((iV,D0)=>{"use strict";var dR=au(),fR=(t,e,n)=>dR(t,e,"<",n);D0.exports=fR});var M0=z((oV,j0)=>{"use strict";var U0=rt(),hR=(t,e,n)=>(t=new U0(t,n),e=new U0(e,n),t.intersects(e,n));j0.exports=hR});var V0=z((sV,F0)=>{"use strict";var pR=io(),mR=tt();F0.exports=(t,e,n)=>{let i=[],r=null,o=null,s=t.sort((l,d)=>mR(l,d,n));for(let l of s)pR(l,e,n)?(o=l,r||(r=l)):(o&&i.push([r,o]),o=null,r=null);r&&i.push([r,null]);let a=[];for(let[l,d]of i)l===d?a.push(l):!d&&l===s[0]?a.push("*"):d?l===s[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);let u=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return u.length<c.length?u:e}});var H0=z((aV,q0)=>{"use strict";var Z0=rt(),og=ro(),{ANY:ng}=og,ig=io(),sg=tt(),gR=(t,e,n={})=>{if(t===e)return!0;t=new Z0(t,n),e=new Z0(e,n);let i=!1;e:for(let r of t.set){for(let o of e.set){let s=yR(r,o,n);if(i=i||s!==null,s)continue e}if(i)return!1}return!0},vR=[new og(">=0.0.0-0")],B0=[new og(">=0.0.0")],yR=(t,e,n)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===ng){if(e.length===1&&e[0].semver===ng)return!0;n.includePrerelease?t=vR:t=B0}if(e.length===1&&e[0].semver===ng){if(n.includePrerelease)return!0;e=B0}let i=new Set,r,o;for(let h of t)h.operator===">"||h.operator===">="?r=G0(r,h,n):h.operator==="<"||h.operator==="<="?o=W0(o,h,n):i.add(h.semver);if(i.size>1)return null;let s;if(r&&o){if(s=sg(r.semver,o.semver,n),s>0)return null;if(s===0&&(r.operator!==">="||o.operator!=="<="))return null}for(let h of i){if(r&&!ig(h,String(r),n)||o&&!ig(h,String(o),n))return null;for(let p of e)if(!ig(h,String(p),n))return!1;return!0}let a,u,c,l,d=o&&!n.includePrerelease&&o.semver.prerelease.length?o.semver:!1,f=r&&!n.includePrerelease&&r.semver.prerelease.length?r.semver:!1;d&&d.prerelease.length===1&&o.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let h of e){if(l=l||h.operator===">"||h.operator===">=",c=c||h.operator==="<"||h.operator==="<=",r){if(f&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===f.major&&h.semver.minor===f.minor&&h.semver.patch===f.patch&&(f=!1),h.operator===">"||h.operator===">="){if(a=G0(r,h,n),a===h&&a!==r)return!1}else if(r.operator===">="&&!h.test(r.semver))return!1}if(o){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(u=W0(o,h,n),u===h&&u!==o)return!1}else if(o.operator==="<="&&!h.test(o.semver))return!1}if(!h.operator&&(o||r)&&s!==0)return!1}return!(r&&c&&!o&&s!==0||o&&l&&!r&&s!==0||f||d)},G0=(t,e,n)=>{if(!t)return e;let i=sg(t.semver,e.semver,n);return i>0?t:i<0||e.operator===">"&&t.operator===">="?e:t},W0=(t,e,n)=>{if(!t)return e;let i=sg(t.semver,e.semver,n);return i<0?t:i>0||e.operator==="<"&&t.operator==="<="?e:t};q0.exports=gR});var X0=z((uV,Y0)=>{"use strict";var ag=Nn(),J0=Rn(),_R=_e(),K0=Bm(),bR=er(),$R=bS(),xR=xS(),wR=kS(),SR=TS(),kR=AS(),ER=CS(),IR=RS(),TR=DS(),OR=tt(),AR=MS(),PR=VS(),CR=tu(),zR=WS(),RR=HS(),NR=to(),DR=ru(),LR=qm(),UR=Hm(),jR=nu(),MR=iu(),FR=Jm(),VR=n0(),ZR=o0(),BR=ro(),GR=rt(),WR=io(),qR=b0(),HR=x0(),JR=S0(),KR=I0(),YR=O0(),XR=au(),QR=N0(),eN=L0(),tN=M0(),rN=V0(),nN=H0();Y0.exports={parse:bR,valid:$R,clean:xR,inc:wR,diff:SR,major:kR,minor:ER,patch:IR,prerelease:TR,compare:OR,rcompare:AR,compareLoose:PR,compareBuild:CR,sort:zR,rsort:RR,gt:NR,lt:DR,eq:LR,neq:UR,gte:jR,lte:MR,cmp:FR,coerce:VR,truncate:ZR,Comparator:BR,Range:GR,satisfies:WR,toComparators:qR,maxSatisfying:HR,minSatisfying:JR,minVersion:KR,validRange:YR,outside:XR,gtr:QR,ltr:eN,intersects:tN,simplifyRange:rN,subset:nN,SemVer:_R,re:ag.re,src:ag.src,tokens:ag.t,SEMVER_SPEC_VERSION:J0.SEMVER_SPEC_VERSION,RELEASE_TYPES:J0.RELEASE_TYPES,compareIdentifiers:K0.compareIdentifiers,rcompareIdentifiers:K0.rcompareIdentifiers}});var nk=z((vV,ug)=>{var lu=process||{},tk=lu.argv||[],cu=lu.env||{},aN=!(cu.NO_COLOR||tk.includes("--no-color"))&&(!!cu.FORCE_COLOR||tk.includes("--color")||lu.platform==="win32"||(lu.stdout||{}).isTTY&&cu.TERM!=="dumb"||!!cu.CI),uN=(t,e,n=t)=>i=>{let r=""+i,o=r.indexOf(e,t.length);return~o?t+cN(r,e,n,o)+e:t+r+e},cN=(t,e,n,i)=>{let r="",o=0;do r+=t.substring(o,i)+n,o=i+e.length,i=t.indexOf(e,o);while(~i);return r+t.substring(o)},rk=(t=aN)=>{let e=t?uN:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};ug.exports=rk();ug.exports.createColors=rk});var pg=z((ZV,xk)=>{"use strict";var hg={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},CN={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},zN={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?hg.up():"");return t&&(e+=hg.left),e}};xk.exports={cursor:hg,scroll:CN,erase:zN,beep:"\x07"}});function fE(t,e){if(e<=1)return t;let n=Math.floor(t.length/e),i=new Int16Array(n);for(let r=0;r<n;r++){let o=0,s=r*e;for(let a=0;a<e;a++)o+=t[s+a];i[r]=Math.round(o/e)}return i}var Au,hE=v(()=>{"use strict";Au=class{step;pos=0;prev=0;primed=!1;constructor(e,n){if(e<=0||n<=0)throw new RangeError("resampler rates must be positive");this.step=e/n}process(e){if(e.length===0)return new Int16Array(0);let n=[],i=e.length-1,r=this.primed?this.pos:0;for(;;){let o=Math.floor(r);if(o+1>i)break;let s=o<0?this.prev:e[o],a=e[o+1];n.push(Math.round(s+(a-s)*(r-o))),r+=this.step}return this.prev=e[i],this.primed=!0,this.pos=r-e.length,Int16Array.from(n)}}});function mE(t){return t.byteLength/2/T4}function O4(t){let e=t.byteLength>>1,n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=new Int16Array(e);for(let r=0;r<e;r++)i[r]=n.getInt16(r*2,!0);return i}var pE,T4,Pu,gE=v(()=>{"use strict";Ae();Ga();pE=32,T4=16,Pu=class{constructor(e,n,i={}){this.vad=e;this.onSpeech=n;this.speechThreshold=i.speechThreshold??.5,this.onsetMs=i.onsetMs??2*pE,this.holdoffMs=i.holdoffMs??300,this.energyThreshold=i.energyThreshold??.01,this.log=i.log??B}vad;onSpeech;speechThreshold;onsetMs;holdoffMs;energyThreshold;log;inSpeech=!1;speechRunMs=0;silenceRunMs=0;degraded=!1;closed=!1;feed(e){if(!(this.closed||e.byteLength===0)){if(this.degraded){this.applyVerdict(Gt(e,this.energyThreshold),mE(e));return}this.vad.process(O4(e)).then(n=>{if(!this.closed)for(let i of n)this.applyVerdict(i>=this.speechThreshold,pE)},n=>{this.closed||(this.degrade(n),this.applyVerdict(Gt(e,this.energyThreshold),mE(e)))})}}close(){this.closed=!0}applyVerdict(e,n){e?(this.silenceRunMs=0,this.speechRunMs+=n,!this.inSpeech&&this.speechRunMs>=this.onsetMs&&(this.inSpeech=!0,this.onSpeech())):(this.speechRunMs=0,this.inSpeech&&(this.silenceRunMs+=n,this.silenceRunMs>=this.holdoffMs&&(this.inSpeech=!1,this.silenceRunMs=0)))}degrade(e){this.degraded||(this.degraded=!0,this.log.debug("barge-in DEGRADED to energy onset - silero vad failed; speech onsets detect on RMS energy for the rest of the capture session",{error:e instanceof Error?e.message:String(e)}))}}});var zg={};He(zg,{DecibriCapture:()=>Pg,DecibriPlayback:()=>Cg,hasInputDevice:()=>C4});import{Microphone as A4,Speaker as P4,inputDevices as yE}from"decibri";function C4(){try{return yE().length>0}catch(t){return B.debug("audio input enumeration failed; treating as no microphone",{error:t}),!1}}function z4(){try{let t=yE(),e=t.find(n=>n.isDefault)??t[0];if(e&&e.defaultSampleRate>=1e3&&e.maxInputChannels>=1)return{sampleRate:Math.round(e.defaultSampleRate),channels:e.maxInputChannels}}catch(t){B.debug("could not read default input device; opening at 16k mono",{error:t})}return{sampleRate:po,channels:Cu}}function R4(t){return Math.max(64,Math.min(65536,Math.round(t/10)))}function N4(t,e,n){let i=new Uint8Array(t),r=new Int16Array(i.buffer,0,i.byteLength>>1),o=n.process(fE(r,e));return Buffer.from(o.buffer,o.byteOffset,o.byteLength)}function U4(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}var po,Cu,_E,vE,Pg,D4,L4,Cg,Rg=v(()=>{"use strict";Ae();Ga();hE();gE();po=16e3,Cu=1,_E="int16",vE=.01;Pg=class{constructor(e={}){this.deps=e}deps;mic=null;onData=null;onSpeech=null;onErr=null;vad=null;detector=null;async start(e){let{sampleRate:n,channels:i}=z4(),r=(this.deps.createVad??(()=>new br))(),o=null;try{await r.load(),o=new Pu(r,()=>e.onSpeechStart(),{energyThreshold:vE})}catch(u){B.debug("silero vad unavailable; barge-in falls back to decibri energy vad",{error:u}),r.dispose().catch(()=>{})}let s;try{s=await A4.open({sampleRate:n,channels:i,dtype:_E,...o?{vad:!1}:{vad:"energy",vadThreshold:vE},framesPerBuffer:R4(n)})}catch(u){throw o?.close(),o&&r.dispose().catch(()=>{}),u}this.vad=o?r:null,this.detector=o;let a=n===po&&i===Cu?null:new Au(n,po);this.onData=a?u=>{let c=N4(u,i,a);c.byteLength>0&&(this.detector?.feed(c),e.onFrame(c,Date.now()))}:u=>{this.detector?.feed(u),e.onFrame(u,Date.now())},this.onSpeech=()=>e.onSpeechStart(),this.onErr=u=>e.onError(u),s.on("data",this.onData),s.on("speech",this.onSpeech),s.on("error",this.onErr),this.mic=s}async stop(){let e=this.mic;this.mic=null,this.detector?.close(),this.detector=null,e&&(this.onData&&e.removeListener("data",this.onData),this.onSpeech&&e.removeListener("speech",this.onSpeech),this.onErr&&e.removeListener("error",this.onErr),e.on("error",()=>{}),e.stop()),this.onData=null,this.onSpeech=null,this.onErr=null;let n=this.vad;this.vad=null,n&&await n.dispose().catch(()=>{})}},D4=po*Cu*2/1e3,L4=250,Cg=class{speaker=null;writeChain=Promise.resolve();generation=0;closed=!1;playoutEndAtMs=0;drainWakes=new Set;play(e){if(this.closed)return;let n=this.generation;this.writeChain=this.writeChain.then(async()=>{if(!(this.closed||n!==this.generation))try{if(await this.ensureSpeaker().writeAsync(U4(e)),this.closed||n!==this.generation)return;this.playoutEndAtMs=Math.max(this.playoutEndAtMs,Date.now())+e.byteLength/D4}catch(i){B.debug("playback write skipped",{error:i})}})}flush(){this.generation++,this.playoutEndAtMs=0;let e=this.speaker;this.speaker=null,e?.stop();for(let n of[...this.drainWakes])n()}async drained(){await this.writeChain;let e=this.speaker;if(!e)return;let n=Promise.resolve().then(()=>e.drainAsync()).catch(s=>{B.debug("playback drain interrupted",{error:s})}),i=Math.max(0,this.playoutEndAtMs-Date.now())+L4,r=this.sleep(i);await Promise.race([n,r.done]),r.wake();let o=this.playoutEndAtMs-Date.now();o>0&&await this.sleep(o).done}sleep(e){let n;return{done:new Promise(r=>{let o=setTimeout(()=>n(),e);n=()=>{clearTimeout(o),this.drainWakes.delete(n),r()},this.drainWakes.add(n)}),wake:n}}close(){return this.closed=!0,this.flush(),Promise.resolve()}ensureSpeaker(){return this.speaker??=new P4({sampleRate:po,channels:Cu,dtype:_E}),this.speaker}}});Ae();Ga();ki();import{readFileSync as j4}from"node:fs";import{randomUUID as M4}from"node:crypto";var mt=class extends Error{constructor(e,n,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Ot=class extends mt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Xi=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Wa(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as WP}from"node:events";import Fm from"node:child_process";import At from"node:path";import Ha from"node:fs";import G from"node:process";import{stripVTControlCharacters as qP}from"node:util";import{stripVTControlCharacters as ZP}from"node:util";var Qi=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let n=e.commands.filter(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&n.push(i),this.sortSubcommands&&n.sort((r,o)=>r.name().localeCompare(o.name())),n}compareOptions(e,n){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(n))}visibleOptions(e){let n=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),o=i.long&&e._findOption(i.long);!r&&!o?n.push(i):i.long&&!o?n.push(e.createOption(i.long,i.description)):i.short&&!r&&n.push(e.createOption(i.short,i.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let i=e.parent;i;i=i.parent){let r=i.options.filter(o=>!o.hidden);n.push(...r)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(i=>Wa(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(r)))),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(r)))),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((i,r)=>Math.max(i,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(r)))),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.name()+" "+i;return i+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatItemList(e,n,i){return n.length===0?[]:[i.styleTitle(e),...n,""]}groupItems(e,n,i){let r=new Map;return e.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[])}),n.forEach(o=>{let s=i(o);r.has(s)||r.set(s,[]),r.get(s).push(o)}),r}formatHelp(e,n){let i=n.padWidth(e,n),r=n.helpWidth??80;function o(d,f){return n.formatItem(d,i,f,n)}let s=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(e))}`,""],a=n.commandDescription(e);a.length>0&&(s=s.concat([n.boxWrap(n.styleCommandDescription(a),r),""]));let u=n.visibleArguments(e).map(d=>o(n.styleArgumentTerm(n.argumentTerm(d)),n.styleArgumentDescription(n.argumentDescription(d))));if(s=s.concat(this.formatItemList("Arguments:",u,n)),this.groupItems(e.options,n.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let h=d.map(p=>o(n.styleOptionTerm(n.optionTerm(p)),n.styleOptionDescription(n.optionDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),n.showGlobalOptions){let d=n.visibleGlobalOptions(e).map(f=>o(n.styleOptionTerm(n.optionTerm(f)),n.styleOptionDescription(n.optionDescription(f))));s=s.concat(this.formatItemList("Global Options:",d,n))}return this.groupItems(e.commands,n.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,f)=>{let h=d.map(p=>o(n.styleSubcommandTerm(n.subcommandTerm(p)),n.styleSubcommandDescription(n.subcommandDescription(p))));s=s.concat(this.formatItemList(f,h,n))}),s.join(`
188
+ `)}displayWidth(e){return ZP(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,n,i,r){let s=" ".repeat(2);if(!i)return s+e;let a=e.padEnd(n+e.length-r.displayWidth(e)),u=2,l=(this.helpWidth??80)-n-u-2,d;return l<this.minWidthToWrap||r.preformatted(i)?d=i:d=r.boxWrap(i,l).replace(/\n/g,`
189
189
  `+" ".repeat(n+u)),s+a+" ".repeat(u)+d.replace(/\n/g,`
190
190
  ${s}`)}boxWrap(e,n){if(n<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,o=[];return i.forEach(s=>{let a=s.match(r);if(a===null){o.push("");return}let u=[a.shift()],c=this.displayWidth(u[0]);a.forEach(l=>{let d=this.displayWidth(l);if(c+d<=n){u.push(l),c+=d;return}o.push(u.join(""));let f=l.trimStart();u=[f],c=this.displayWidth(f)}),o.push(u.join(""))}),o.join(`
191
- `)}};var Cn=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=ZP(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?iS(this.name().replace(/^no-/,"")):iS(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},qa=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,n){let i=n.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg,o=r!==void 0?r:!1;return n.negate===(o===e)}};function iS(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function ZP(t){let e,n,i=/^-[^-]$/,r=/^--[^-]/,o=t.split(/[ |,]+/).concat("guard");if(i.test(o[0])&&(e=o.shift()),r.test(o[0])&&(n=o.shift()),!e&&i.test(o[0])&&(e=o.shift()),!e&&r.test(o[0])&&(e=n,n=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${t}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
191
+ `)}};var Cn=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=BP(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Ot(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?iS(this.name().replace(/^no-/,"")):iS(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},qa=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,n){let i=n.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg,o=r!==void 0?r:!1;return n.negate===(o===e)}};function iS(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function BP(t){let e,n,i=/^-[^-]$/,r=/^--[^-]/,o=t.split(/[ |,]+/).concat("guard");if(i.test(o[0])&&(e=o.shift()),r.test(o[0])&&(n=o.shift()),!e&&i.test(o[0])&&(e=o.shift()),!e&&r.test(o[0])&&(e=n,n=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${t}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
192
192
  - a short flag is a single dash and a single character
193
193
  - either use a single dash and a single character (for a short flag)
194
194
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(s)?new Error(`${a}
195
195
  - too many short flags`):r.test(s)?new Error(`${a}
196
196
  - too many long flags`):new Error(`${a}
197
- - unrecognised flag format`)}if(e===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:n}}function BP(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let i=0;i<=t.length;i++)n[i]=[i];for(let i=0;i<=e.length;i++)n[0][i]=i;for(let i=1;i<=e.length;i++)for(let r=1;r<=t.length;r++){let o;t[r-1]===e[i-1]?o=0:o=1,n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+o),r>1&&i>1&&t[r-1]===e[i-2]&&t[r-2]===e[i-1]&&(n[r][i]=Math.min(n[r][i],n[r-2][i-2]+1))}return n[t.length][e.length]}function Mm(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let i=[],r=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=BP(t,s),u=Math.max(t.length,s.length);(u-a)/u>o&&(a<r?(r=a,i=[s]):a===r&&i.push(s))}),i.sort((s,a)=>s.localeCompare(a)),n&&(i=i.map(s=>`--${s}`)),i.length>1?`
197
+ - unrecognised flag format`)}if(e===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:n}}function GP(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let i=0;i<=t.length;i++)n[i]=[i];for(let i=0;i<=e.length;i++)n[0][i]=i;for(let i=1;i<=e.length;i++)for(let r=1;r<=t.length;r++){let o;t[r-1]===e[i-1]?o=0:o=1,n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+o),r>1&&i>1&&t[r-1]===e[i-2]&&t[r-2]===e[i-1]&&(n[r][i]=Math.min(n[r][i],n[r-2][i-2]+1))}return n[t.length][e.length]}function Mm(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(s=>s.slice(2)));let i=[],r=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=GP(t,s),u=Math.max(t.length,s.length);(u-a)/u>o&&(a<r?(r=a,i=[s]):a===r&&i.push(s))}),i.sort((s,a)=>s.localeCompare(a)),n&&(i=i.map(s=>`--${s}`)),i.length>1?`
198
198
  (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
199
- (Did you mean ${i[0]}?)`:""}var zn=class t extends GP{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>G.stdout.write(n),writeErr:n=>G.stderr.write(n),outputError:(n,i)=>i(n),getOutHelpWidth:()=>G.stdout.isTTY?G.stdout.columns:void 0,getErrHelpWidth:()=>G.stderr.isTTY?G.stderr.columns:void 0,getOutHasColors:()=>sS()??(G.stdout.isTTY&&G.stdout.hasColors?.()),getErrHasColors:()=>sS()??(G.stderr.isTTY&&G.stderr.hasColors?.()),stripColor:n=>WP(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,i){let r=n,o=i;typeof r=="object"&&r!==null&&(o=r,r=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(s);return r&&(u.description(r),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),r?this:u}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Qi,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
199
+ (Did you mean ${i[0]}?)`:""}var zn=class t extends WP{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>G.stdout.write(n),writeErr:n=>G.stderr.write(n),outputError:(n,i)=>i(n),getOutHelpWidth:()=>G.stdout.isTTY?G.stdout.columns:void 0,getErrHelpWidth:()=>G.stderr.isTTY?G.stderr.columns:void 0,getOutHasColors:()=>sS()??(G.stdout.isTTY&&G.stdout.hasColors?.()),getErrHasColors:()=>sS()??(G.stderr.isTTY&&G.stderr.hasColors?.()),stripColor:n=>qP(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,i){let r=n,o=i;typeof r=="object"&&r!==null&&(o=r,r=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(s);return r&&(u.description(r),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),r?this:u}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Qi,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
200
200
  - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new Xi(e,n)}argument(e,n,i,r){let o=this.createArgument(e,n);return typeof i=="function"?o.default(r).argParser(i):o.default(i),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n?.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=e??"help [command]",[,r,o]=i.match(/([^ ]+) *(.*)/),s=n??"display help for command",a=this.createCommand(r);return a.helpOption(!1),o&&a.arguments(o),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||n)&&this._initCommandGroup(a),this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,n){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
201
201
  Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,i){this._exitCallback&&this._exitCallback(new mt(e,n,i)),G.exit(e)}action(e){let n=i=>{let r=this.registeredArguments.length,o=i.slice(0,r);return this._storeOptionsAsProperties?o[r]=this:o[r]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=n,this}createOption(e,n){return new Cn(e,n)}_callParseArg(e,n,i,r){try{return e.parseArg(n,i)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${r} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
202
202
  - already used by option '${n.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let n=r=>[r.name()].concat(r.aliases()),i=n(e).find(r=>this._findCommand(r));if(i){let r=n(this._findCommand(i)).join("|"),o=n(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),i=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let r=(o,s,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(i);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,s):o!==null&&e.variadic&&(o=e._collectValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(i,o,a)};return this.on("option:"+n,o=>{let s=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,s,"cli")}),e.envVar&&this.on("optionEnv:"+n,o=>{let s=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,s,"env")}),this}_optionEx(e,n,i,r,o){if(typeof n=="object"&&n instanceof Cn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(n,i);if(s.makeOptionMandatory(!!e.mandatory),typeof r=="function")s.default(o).argParser(r);else if(r instanceof RegExp){let a=r;r=(u,c)=>{let l=a.exec(u);return l?l[0]:c},s.default(o).argParser(r)}else s.default(r);return this.addOption(s)}option(e,n,i,r){return this._optionEx({},e,n,i,r)}requiredOption(e,n,i,r){return this._optionEx({mandatory:!0},e,n,i,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,i){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(n=i.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){G.versions?.electron&&(n.from="electron");let r=G.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(n.from="eval")}e===void 0&&(e=G.argv),this.rawArgs=e.slice();let i;switch(n.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":G.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,n){this._prepareForParse();let i=this._prepareUserArgs(e,n);return this._parseCommand([],i),this}async parseAsync(e,n){this._prepareForParse();let i=this._prepareUserArgs(e,n);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
@@ -209,7 +209,7 @@ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
209
209
  `),this.outputHelp({error:!0}));let i=n||{},r=i.exitCode||1,o=i.code||"commander.error";this._exit(r,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in G.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,G.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new qa(this.options),n=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&n(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(r=>!n(r)).forEach(r=>{this.setOptionValueWithSource(r,i.implied[r],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let i=s=>{let a=s.attributeName(),u=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),l=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:l||s},r=s=>{let a=i(s),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${r(e)} cannot be used with ${r(n)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);r=r.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);n=Mm(e,r)}let i=`error: unknown option '${e}'${n}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,i=n===1?"":"s",r=e.length,o=this.parent?` for '${this.name()}'`:"",s=e.join(", "),a=`error: too many arguments${o}. Expected ${n} argument${i} but got ${r}: ${s}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(o=>{r.push(o.name()),o.alias()&&r.push(o.alias())}),n=Mm(e,r)}let i=`error: unknown command '${e}'${n}`;this.error(i,{code:"commander.unknownCommand"})}version(e,n,i){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",i=i||"output the version number";let r=this.createOption(n,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
210
210
  `),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(i=>Wa(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=At.basename(e,At.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp(),i=this._getOutputContext(e);n.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let r=n.formatHelp(this,n);return i.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let n=!!e.error,i,r,o;return n?(i=a=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(r||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:r,helpWidth:o}}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let i=this._getOutputContext(e),r={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation({error:i.error});if(n&&(o=n(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",n??"display help for command"),(e||n)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let n=Number(G.exitCode??0);n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
211
211
  Expecting one of '${i.join("', '")}'`);let r=`${e}Help`;return this.on(r,o=>{let s;typeof n=="function"?s=n({error:o.error,command:o.command}):s=n,s&&o.write(`${s}
212
- `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(r=>n.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function oS(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,i="127.0.0.1",r="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?n=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=o[1],/^\d+$/.test(o[3])?r=o[3]:i=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=o[1],i=o[3],r=o[4]),n&&r!=="0"?`${n}=${i}:${parseInt(r)+1}`:e})}function sS(){if(G.env.NO_COLOR||G.env.FORCE_COLOR==="0"||G.env.FORCE_COLOR==="false")return!1;if(G.env.FORCE_COLOR||G.env.CLICOLOR_FORCE!==void 0)return!0}var lF=new zn;Ae();var ue={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function qP(t){if(t==="debug"||t==="info"||t==="warn"||t==="error")return t;throw new Ot("expected one of debug|info|warn|error")}function Ja(t){return t.option("--log-level <level>","set log verbosity (debug|info|warn|error)",qP).option("--project <path>","approved project scope (default: cwd)").option("--text","force text-only operation").option("--no-voice","force text-only operation (disable voice)").option("--half-duplex","mute barge-in; mute the mic while jarvis speaks (no headphones)").option("--ptt","push-to-talk: press space to talk, again to send")}function HP(t){return t.text===!0||t.voice===!1}function JP(t,e,n,i=ue){let r=new zn;r.name("jarvis").description("jarvis - voice-first personal agent").configureOutput({writeOut:s=>i.out(s),writeErr:s=>i.err(s)}).showHelpAfterError().exitOverride().allowExcessArguments(!0).version(t,"-v, --version","print version"),Ja(r),r.hook("preAction",(s,a)=>{let u=a.optsWithGlobals();u.logLevel&&B.setLevel(u.logLevel)}),r.action(async(s,a)=>{if(a.args.length>0){a.error(`error: unknown command '${a.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}n.exitCode=await e.activate({project:s.project??process.cwd(),textOnly:HP(s),halfDuplex:s.halfDuplex===!0,ptt:s.ptt===!0})});let o=(s,a)=>{let u=r.command(s).description(a).allowExcessArguments(!1);return Ja(u)};return o("init","first-run setup (interactive wizard)").action(async()=>{n.exitCode=await e.init()}),o("start","start the local core service").action(()=>{n.exitCode=e.stub("start")}),o("stop","stop the local core service").action(()=>{n.exitCode=e.stub("stop")}),o("restart","restart the local core service").action(()=>{n.exitCode=e.stub("restart")}),o("status","show version and check for updates").action(async()=>{n.exitCode=await e.status()}),o("doctor","run diagnostics").action(async()=>{n.exitCode=await e.doctor()}),o("devices","list audio devices").action(()=>{n.exitCode=e.stub("devices")}),o("upgrade","upgrade the installed CLI to the latest published version").action(async()=>{n.exitCode=await e.upgrade()}),KP(r,e,n),r}function KP(t,e,n){let i=t.command("config").description("inspect and edit configuration").allowExcessArguments(!0);Ja(i),i.action((o,s)=>{if(s.args.length>0){s.error(`error: unknown command 'config ${s.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}s.outputHelp(),n.exitCode=0});let r=(o,s)=>{let a=i.command(o).description(s).allowExcessArguments(!1);return Ja(a)};r("list","print the resolved config (secrets redacted)").action(async()=>{n.exitCode=await e.configList()}),r("get <path>","print one config value by dotted path").action(async o=>{n.exitCode=await e.configGet(o)}),r("set <path> <value>","set one config value by dotted path").action(async(o,s)=>{n.exitCode=await e.configSet(o,s)}),r("unset <path>","remove one config value by dotted path").action(async o=>{n.exitCode=await e.configUnset(o)})}async function aS(t,e,n,i=ue){let r={exitCode:0},o=JP(e,n,r,i);try{return await o.parseAsync(t,{from:"user"}),r.exitCode}catch(s){if(s instanceof mt)return s.exitCode;throw s}}Ae();import{execSync as ek,spawnSync as nN}from"node:child_process";import{existsSync as iN}from"node:fs";import{join as oN}from"node:path";var uu=Je(X0(),1);function Ir(t,e){let n=Q0(t),i=Q0(e);return n===null||i===null?!1:uu.default.gt(n,i)}function Q0(t){return uu.default.valid(t)??uu.default.coerce(t)?.version??null}var Tr=class{constructor(e,n=ue){this.currentVersion=e;this.io=n}currentVersion;io;packageName="@neuvybe/jarvis";registryTimeoutMs=3e3;safeVersion=/^[0-9A-Za-z.\-+]+$/;npmCmd(){return process.platform==="win32"?"npm.cmd":"npm"}async fetchLatest(){try{let e=await fetch(`https://registry.npmjs.org/${this.packageName}/latest`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(this.registryTimeoutMs)});if(!e.ok)return null;let n=await e.json();return typeof n.version=="string"?n.version:null}catch{return null}}async status(){this.io.out(`jarvis ${this.currentVersion}
212
+ `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(r=>n.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function oS(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,i="127.0.0.1",r="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?n=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=o[1],/^\d+$/.test(o[3])?r=o[3]:i=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=o[1],i=o[3],r=o[4]),n&&r!=="0"?`${n}=${i}:${parseInt(r)+1}`:e})}function sS(){if(G.env.NO_COLOR||G.env.FORCE_COLOR==="0"||G.env.FORCE_COLOR==="false")return!1;if(G.env.FORCE_COLOR||G.env.CLICOLOR_FORCE!==void 0)return!0}var dF=new zn;Ae();var ue={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function HP(t){if(t==="debug"||t==="info"||t==="warn"||t==="error")return t;throw new Ot("expected one of debug|info|warn|error")}function Ja(t){return t.option("--log-level <level>","set log verbosity (debug|info|warn|error)",HP).option("--project <path>","approved project scope (default: cwd)").option("--text","force text-only operation").option("--no-voice","force text-only operation (disable voice)").option("--half-duplex","mute barge-in; mute the mic while jarvis speaks (no headphones)").option("--ptt","push-to-talk: press space to talk, again to send")}function JP(t){return t.text===!0||t.voice===!1}function KP(t,e,n,i=ue){let r=new zn;r.name("jarvis").description("jarvis - voice-first personal agent").configureOutput({writeOut:s=>i.out(s),writeErr:s=>i.err(s)}).showHelpAfterError().exitOverride().allowExcessArguments(!0).version(t,"-v, --version","print version"),Ja(r),r.hook("preAction",(s,a)=>{let u=a.optsWithGlobals();u.logLevel&&B.setLevel(u.logLevel)}),r.action(async(s,a)=>{if(a.args.length>0){a.error(`error: unknown command '${a.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}n.exitCode=await e.activate({project:s.project??process.cwd(),textOnly:JP(s),halfDuplex:s.halfDuplex===!0,ptt:s.ptt===!0})});let o=(s,a)=>{let u=r.command(s).description(a).allowExcessArguments(!1);return Ja(u)};return o("init","first-run setup (interactive wizard)").action(async()=>{n.exitCode=await e.init()}),o("start","start the local core service").action(()=>{n.exitCode=e.stub("start")}),o("stop","stop the local core service").action(()=>{n.exitCode=e.stub("stop")}),o("restart","restart the local core service").action(()=>{n.exitCode=e.stub("restart")}),o("status","show version and check for updates").action(async()=>{n.exitCode=await e.status()}),o("doctor","run diagnostics").action(async()=>{n.exitCode=await e.doctor()}),o("devices","list audio devices").action(()=>{n.exitCode=e.stub("devices")}),o("upgrade","upgrade the installed CLI to the latest published version").action(async()=>{n.exitCode=await e.upgrade()}),YP(r,e,n),r}function YP(t,e,n){let i=t.command("config").description("inspect and edit configuration").allowExcessArguments(!0);Ja(i),i.action((o,s)=>{if(s.args.length>0){s.error(`error: unknown command 'config ${s.args[0]}'`,{exitCode:1,code:"commander.unknownCommand"});return}s.outputHelp(),n.exitCode=0});let r=(o,s)=>{let a=i.command(o).description(s).allowExcessArguments(!1);return Ja(a)};r("list","print the resolved config (secrets redacted)").action(async()=>{n.exitCode=await e.configList()}),r("get <path>","print one config value by dotted path").action(async o=>{n.exitCode=await e.configGet(o)}),r("set <path> <value>","set one config value by dotted path").action(async(o,s)=>{n.exitCode=await e.configSet(o,s)}),r("unset <path>","remove one config value by dotted path").action(async o=>{n.exitCode=await e.configUnset(o)})}async function aS(t,e,n,i=ue){let r={exitCode:0},o=KP(e,n,r,i);try{return await o.parseAsync(t,{from:"user"}),r.exitCode}catch(s){if(s instanceof mt)return s.exitCode;throw s}}Ae();import{execSync as ek,spawnSync as iN}from"node:child_process";import{existsSync as oN}from"node:fs";import{join as sN}from"node:path";var uu=Je(X0(),1);function Ir(t,e){let n=Q0(t),i=Q0(e);return n===null||i===null?!1:uu.default.gt(n,i)}function Q0(t){return uu.default.valid(t)??uu.default.coerce(t)?.version??null}var Tr=class{constructor(e,n=ue){this.currentVersion=e;this.io=n}currentVersion;io;packageName="@neuvybe/jarvis";registryTimeoutMs=3e3;safeVersion=/^[0-9A-Za-z.\-+]+$/;npmCmd(){return process.platform==="win32"?"npm.cmd":"npm"}async fetchLatest(){try{let e=await fetch(`https://registry.npmjs.org/${this.packageName}/latest`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(this.registryTimeoutMs)});if(!e.ok)return null;let n=await e.json();return typeof n.version=="string"?n.version:null}catch{return null}}async status(){this.io.out(`jarvis ${this.currentVersion}
213
213
  `);let e=await this.fetchLatest();return e===null?this.io.out(`could not check for updates (offline?)
214
214
  `):Ir(e,this.currentVersion)?this.io.out(`upgrade available: ${this.currentVersion} -> ${e} (run: jarvis upgrade)
215
215
  `):this.io.out(`up to date
@@ -221,9 +221,9 @@ Expecting one of '${i.join("', '")}'`);let r=`${e}Help`;return this.on(r,o=>{let
221
221
  `),await this.stopCore();let n=`${this.npmCmd()} install -g ${this.packageName}@${e}`;try{ek(n,{stdio:"inherit"})}catch{return this.io.err(`upgrade failed; run manually: ${this.npmCmd()} install -g ${this.packageName}@latest
222
222
  `),1}let i=this.resolveFreshEntrypoint();return i===null?(this.io.out(`upgraded to ${e}. run "jarvis --version" to confirm.
223
223
  `),0):(this.io.err(`verifying the freshly installed jarvis...
224
- `),nN(process.execPath,[i,"--version"],{stdio:"inherit"}).status!==0?(this.io.err(`upgrade installed but the fresh entrypoint exited abnormally; run "jarvis --version" to confirm
224
+ `),iN(process.execPath,[i,"--version"],{stdio:"inherit"}).status!==0?(this.io.err(`upgrade installed but the fresh entrypoint exited abnormally; run "jarvis --version" to confirm
225
225
  `),0):(this.io.out(`upgraded to ${e}.
226
- `),0))}async stopCore(){return B.debug("stop-core hook: no daemon in v0.1; nothing to stop (proposal 0013 fills this in)"),Promise.resolve()}resolveFreshEntrypoint(){try{let e=ek(`${this.npmCmd()} root -g`,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(!e)return null;let n=oN(e,this.packageName,"dist","index.js");return iN(n)?n:null}catch{return null}}};Ae();pr();import{spawn as cN}from"node:child_process";import{existsSync as lN,readFileSync as dN,writeFileSync as fN}from"node:fs";var Or=Je(nk(),1),N={dim:t=>Or.default.dim(t),bold:t=>Or.default.bold(t),ok:t=>Or.default.green(t),warn:t=>Or.default.yellow(t),fail:t=>Or.default.red(t),accent:t=>Or.default.cyan(t)};var du=class{constructor(e,n=Be){this.currentVersion=e;this.home=n}currentVersion;home;packageName="@neuvybe/jarvis";cacheFile="update-check.json";ttlMs=360*60*1e3;cachePath(){return this.home.resolve(this.cacheFile)}read(){let e=this.cachePath();if(!lN(e))return null;try{let n=JSON.parse(dN(e,"utf8"));return typeof n.lastCheckedAt=="number"&&typeof n.latestVersion=="string"?{lastCheckedAt:n.lastCheckedAt,latestVersion:n.latestVersion}:null}catch{return null}}write(e,n){let i={lastCheckedAt:n,latestVersion:e};try{this.home.ensureDir(),fN(this.cachePath(),JSON.stringify(i))}catch{}}isStale(e){let n=this.read();return!n||e-n.lastCheckedAt>this.ttlMs}notice(){let e=this.read();return!e||!Ir(e.latestVersion,this.currentVersion)?null:N.dim(`upgrade available: ${this.currentVersion} -> ${e.latestVersion} (run: jarvis upgrade)`)}refreshInBackground(){try{let e=this.cachePath();this.home.ensureDir();let n=`
226
+ `),0))}async stopCore(){return B.debug("stop-core hook: no daemon in v0.1; nothing to stop (proposal 0013 fills this in)"),Promise.resolve()}resolveFreshEntrypoint(){try{let e=ek(`${this.npmCmd()} root -g`,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(!e)return null;let n=sN(e,this.packageName,"dist","index.js");return oN(n)?n:null}catch{return null}}};Ae();pr();import{spawn as lN}from"node:child_process";import{existsSync as dN,readFileSync as fN,writeFileSync as hN}from"node:fs";var Or=Je(nk(),1),N={dim:t=>Or.default.dim(t),bold:t=>Or.default.bold(t),ok:t=>Or.default.green(t),warn:t=>Or.default.yellow(t),fail:t=>Or.default.red(t),accent:t=>Or.default.cyan(t)};var du=class{constructor(e,n=Be){this.currentVersion=e;this.home=n}currentVersion;home;packageName="@neuvybe/jarvis";cacheFile="update-check.json";ttlMs=360*60*1e3;cachePath(){return this.home.resolve(this.cacheFile)}read(){let e=this.cachePath();if(!dN(e))return null;try{let n=JSON.parse(fN(e,"utf8"));return typeof n.lastCheckedAt=="number"&&typeof n.latestVersion=="string"?{lastCheckedAt:n.lastCheckedAt,latestVersion:n.latestVersion}:null}catch{return null}}write(e,n){let i={lastCheckedAt:n,latestVersion:e};try{this.home.ensureDir(),hN(this.cachePath(),JSON.stringify(i))}catch{}}isStale(e){let n=this.read();return!n||e-n.lastCheckedAt>this.ttlMs}notice(){let e=this.read();return!e||!Ir(e.latestVersion,this.currentVersion)?null:N.dim(`upgrade available: ${this.currentVersion} -> ${e.latestVersion} (run: jarvis upgrade)`)}refreshInBackground(){try{let e=this.cachePath();this.home.ensureDir();let n=`
227
227
  import { writeFileSync } from 'node:fs';
228
228
  try {
229
229
  const res = await fetch('https://registry.npmjs.org/${this.packageName}/latest', {
@@ -240,36 +240,36 @@ try {
240
240
  }
241
241
  }
242
242
  } catch {}
243
- `;cN(process.execPath,["--input-type=module","-e",n],{detached:!0,stdio:"ignore"}).unref()}catch{B.debug("background update check skipped (could not refresh cache)")}}};var Ar=class{constructor(e,n=ue){this.config=e;this.io=n}config;io;list(){let e=ik(this.config.list());for(let[n,i]of e)this.io.out(`${N.accent(n)} = ${this.renderValue(n,i)}
243
+ `;lN(process.execPath,["--input-type=module","-e",n],{detached:!0,stdio:"ignore"}).unref()}catch{B.debug("background update check skipped (could not refresh cache)")}}};var Ar=class{constructor(e,n=ue){this.config=e;this.io=n}config;io;list(){let e=ik(this.config.list());for(let[n,i]of e)this.io.out(`${N.accent(n)} = ${this.renderValue(n,i)}
244
244
  `);return 0}get(e){let n;try{n=this.config.get(e)}catch(i){return this.io.err(`error: ${cg(i)}
245
245
  `),1}return n===void 0?(this.io.err(`config: '${e}' is not set
246
- `),1):(this.io.out(`${hN(n)}
246
+ `),1):(this.io.out(`${pN(n)}
247
247
  `),0)}set(e,n){try{this.config.set(e,n)}catch(i){return this.io.err(`error: ${cg(i)}
248
248
  `),1}return this.io.out(`${N.ok("set")} ${N.accent(e)}
249
249
  `),0}unset(e){try{this.config.unset(e)}catch(n){return this.io.err(`error: ${cg(n)}
250
250
  `),1}return this.io.out(`${N.ok("unset")} ${N.accent(e)}
251
- `),0}renderValue(e,n){return e.startsWith("secrets.")?N.dim(String(n)):String(n)}};function ik(t,e=""){let n=[];for(let[i,r]of Object.entries(t)){let o=e?`${e}.${i}`:i;r!==null&&typeof r=="object"&&!Array.isArray(r)?n.push(...ik(r,o)):n.push([o,r])}return n}function hN(t){return t!==null&&typeof t=="object"?JSON.stringify(t,null,2):String(t)}function cg(t){return t instanceof Error?t.message:String(t)}pr();import{existsSync as ok,statSync as sk}from"node:fs";var ak=["text","stt","tts","embedding"],pN={text:"Brain",stt:"Voice",tts:"Voice",embedding:"Memory"},fu=class{config;probe;version;io;homeCheck;checkUpdate;constructor(e){this.config=e.config,this.probe=e.probe,this.version=e.version,this.io=e.io??ue,this.homeCheck=e.homeCheck??gN,this.checkUpdate=e.checkUpdate??(async()=>({latest:await new Tr(this.version).fetchLatest()}))}async run(){let e=[],n;try{n=this.config.resolved(),e.push({level:"ok",label:"config",detail:"valid"})}catch(r){e.push({level:"fail",label:"config",detail:`invalid - ${vN(r)}`})}e.push(this.homeLine()),n&&e.push(...await this.routeLines(n)),e.push(await this.versionLine()),e.push({level:"info",label:"project",detail:process.cwd()});let i=e.some(r=>r.level==="fail")?1:0;return this.render(e,i),i}homeLine(){let e=this.homeCheck();return e.permsOk===!1?{level:"fail",label:"home",detail:`${e.dir} - ${e.detail??"permissions wrong"}`}:e.exists?{level:"ok",label:"home",detail:`${e.dir} (${e.detail??"owner-only"})`}:{level:"info",label:"home",detail:`${e.dir} (${e.detail??"not created yet"})`}}async routeLines(e){let n=e.routes??{},i=new Map;for(let s of ak){let a=n[s],u=a&&e.secrets?.[a.provider];a&&u&&i.set(a.provider,u)}let r=new Map;await Promise.all([...i].map(async([s,a])=>{let u=await this.probe.probe(s,a);r.set(s,u.status)}));let o=[];for(let s of ak){let a=n[s];if(!a){o.push(this.unconfiguredLine(s));continue}let u=`${a.provider}/${a.model}`;if(!e.secrets?.[a.provider]){o.push({level:"fail",label:`${s} route`,detail:`${u} - key for '${a.provider}' is missing`});continue}o.push(this.probedLine(s,u,a.provider,r.get(a.provider)))}return o}unconfiguredLine(e){return e==="text"?{level:"fail",label:"text route",detail:"not configured - Jarvis cannot reason (run: jarvis init)"}:{level:"info",label:`${e} route`,detail:`not configured (optional, ${pN[e]})`}}probedLine(e,n,i,r){let o=`${e} route`,s=e==="text";switch(r){case"valid":return{level:"ok",label:o,detail:`${n} (key valid)`};case"invalid":return{level:s?"fail":"warn",label:o,detail:`${n} - key rejected by ${i}`};case"unreachable":return{level:"warn",label:o,detail:`${n} (key present; could not verify - offline/unreachable)`};case"unimplemented":return{level:"warn",label:o,detail:`${n} (key present; no probe for ${i})`};case"unverifiable":return{level:"warn",label:o,detail:`${n} (key present; reached ${i} but cannot verify this key here - confirmed at first use)`};default:return{level:"warn",label:o,detail:`${n} (key present; not verified)`}}}async versionLine(){let{latest:e}=await this.checkUpdate();return e===null?{level:"info",label:"version",detail:`${this.version} (could not check for updates)`}:Ir(e,this.version)?{level:"warn",label:"version",detail:`${this.version} -> ${e} available (run: jarvis upgrade)`}:{level:"ok",label:"version",detail:`${this.version} (up to date)`}}render(e,n){this.io.out(`
251
+ `),0}renderValue(e,n){return e.startsWith("secrets.")?N.dim(String(n)):String(n)}};function ik(t,e=""){let n=[];for(let[i,r]of Object.entries(t)){let o=e?`${e}.${i}`:i;r!==null&&typeof r=="object"&&!Array.isArray(r)?n.push(...ik(r,o)):n.push([o,r])}return n}function pN(t){return t!==null&&typeof t=="object"?JSON.stringify(t,null,2):String(t)}function cg(t){return t instanceof Error?t.message:String(t)}pr();import{existsSync as ok,statSync as sk}from"node:fs";var ak=["text","stt","tts","embedding"],mN={text:"Brain",stt:"Voice",tts:"Voice",embedding:"Memory"},fu=class{config;probe;version;io;homeCheck;checkUpdate;constructor(e){this.config=e.config,this.probe=e.probe,this.version=e.version,this.io=e.io??ue,this.homeCheck=e.homeCheck??vN,this.checkUpdate=e.checkUpdate??(async()=>({latest:await new Tr(this.version).fetchLatest()}))}async run(){let e=[],n;try{n=this.config.resolved(),e.push({level:"ok",label:"config",detail:"valid"})}catch(r){e.push({level:"fail",label:"config",detail:`invalid - ${yN(r)}`})}e.push(this.homeLine()),n&&e.push(...await this.routeLines(n)),e.push(await this.versionLine()),e.push({level:"info",label:"project",detail:process.cwd()});let i=e.some(r=>r.level==="fail")?1:0;return this.render(e,i),i}homeLine(){let e=this.homeCheck();return e.permsOk===!1?{level:"fail",label:"home",detail:`${e.dir} - ${e.detail??"permissions wrong"}`}:e.exists?{level:"ok",label:"home",detail:`${e.dir} (${e.detail??"owner-only"})`}:{level:"info",label:"home",detail:`${e.dir} (${e.detail??"not created yet"})`}}async routeLines(e){let n=e.routes??{},i=new Map;for(let s of ak){let a=n[s],u=a&&e.secrets?.[a.provider];a&&u&&i.set(a.provider,u)}let r=new Map;await Promise.all([...i].map(async([s,a])=>{let u=await this.probe.probe(s,a);r.set(s,u.status)}));let o=[];for(let s of ak){let a=n[s];if(!a){o.push(this.unconfiguredLine(s));continue}let u=`${a.provider}/${a.model}`;if(!e.secrets?.[a.provider]){o.push({level:"fail",label:`${s} route`,detail:`${u} - key for '${a.provider}' is missing`});continue}o.push(this.probedLine(s,u,a.provider,r.get(a.provider)))}return o}unconfiguredLine(e){return e==="text"?{level:"fail",label:"text route",detail:"not configured - Jarvis cannot reason (run: jarvis init)"}:{level:"info",label:`${e} route`,detail:`not configured (optional, ${mN[e]})`}}probedLine(e,n,i,r){let o=`${e} route`,s=e==="text";switch(r){case"valid":return{level:"ok",label:o,detail:`${n} (key valid)`};case"invalid":return{level:s?"fail":"warn",label:o,detail:`${n} - key rejected by ${i}`};case"unreachable":return{level:"warn",label:o,detail:`${n} (key present; could not verify - offline/unreachable)`};case"unimplemented":return{level:"warn",label:o,detail:`${n} (key present; no probe for ${i})`};case"unverifiable":return{level:"warn",label:o,detail:`${n} (key present; reached ${i} but cannot verify this key here - confirmed at first use)`};default:return{level:"warn",label:o,detail:`${n} (key present; not verified)`}}}async versionLine(){let{latest:e}=await this.checkUpdate();return e===null?{level:"info",label:"version",detail:`${this.version} (could not check for updates)`}:Ir(e,this.version)?{level:"warn",label:"version",detail:`${this.version} -> ${e} available (run: jarvis upgrade)`}:{level:"ok",label:"version",detail:`${this.version} (up to date)`}}render(e,n){this.io.out(`
252
252
  ${N.bold("jarvis doctor")}
253
253
 
254
- `);for(let i of e){let r=i.detail?`: ${i.detail}`:"";this.io.out(` ${mN(i.level)} ${i.label}${r}
254
+ `);for(let i of e){let r=i.detail?`: ${i.detail}`:"";this.io.out(` ${gN(i.level)} ${i.label}${r}
255
255
  `)}this.io.out(`
256
256
  `),n!==0?this.io.out(`${N.fail("not ready")} - resolve the failing checks above (start with: jarvis init)
257
257
  `):e.some(i=>i.level==="warn")?this.io.out(`${N.warn("ready, with warnings")}
258
258
  `):this.io.out(`${N.ok("all checks passed")}
259
- `)}};function mN(t){switch(t){case"ok":return N.ok("OK ");case"warn":return N.warn("WARN");case"fail":return N.fail("FAIL");case"info":return N.dim("INFO")}}function gN(){let t=Be.dir();if(!ok(t))return{dir:t,exists:!1,permsOk:"n/a",detail:"not created yet - run: jarvis init"};if(process.platform==="win32")return{dir:t,exists:!0,permsOk:"n/a",detail:"permissions not enforced on this platform"};let e=(sk(t).mode&63)===0,n=Be.resolve("config.json"),i=!ok(n)||(sk(n).mode&63)===0,r=e&&i;return{dir:t,exists:!0,permsOk:r,detail:r?"owner-only":"should be owner-only (chmod 700 ~/.jarvis; chmod 600 ~/.jarvis/config.json)"}}function vN(t){return t instanceof Error?t.message:String(t)}import{styleText as mg}from"node:util";import{stdout as vg,stdin as Sk}from"node:process";import*as tr from"node:readline";import zN from"node:readline";var uk=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let n=0;for(t.lastIndex=0;t.test(e);)n+=1;return e.length-n}})(),ck=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,lk=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var yN=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,_N=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,dk=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,bN=/\t{1,1000}/y,fk=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,$N=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,xN=/\p{M}+/gu,wN={limit:1/0,ellipsis:""},hk=(t,e={},n={})=>{let i=e.limit??1/0,r=e.ellipsis??"",o=e?.ellipsisWidth??(r?hk(r,wN,n).width:0),s=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,d=n.regularWidth??1,f=n.wideWidth??l,h=[[$N,d],[yN,s],[_N,a],[bN,u],[fk,c],[dk,f]],p=0,_=0,S=t.length,k=0,P=!1,C=S,E=Math.max(0,i-o),T=0,Z=0,F=0,q=0;e:for(;;){if(Z>T||_>=S&&_>p){let ne=t.slice(T,Z)||t.slice(p,_);k=0;for(let $e of ne.replaceAll(xN,"")){let he=$e.codePointAt(0)||0;if(ck(he)?q=l:lk(he)?q=f:q=d,F+q>E&&(C=Math.min(C,Math.max(T,p)+k)),F+q>i){P=!0;break e}k+=$e.length,F+=q}T=Z=0}if(_>=S)break e;for(let ne=0,$e=h.length;ne<$e;ne++){let[he,Se]=h[ne];if(he.lastIndex=_,he.test(t)){if(k=he===dk?uk(t.slice(_,he.lastIndex)):he===fk?1:he.lastIndex-_,q=k*Se,F+q>E&&(C=Math.min(C,_+Math.floor((E-F)/Se))),F+q>i){P=!0;break e}F+=q,T=p,Z=_,_=p=he.lastIndex;continue e}}_+=1}return{width:P?E:F,index:P?C:S,truncated:P,ellipsed:P&&i>=o}},pk=hk;var SN={limit:1/0,ellipsis:"",ellipsisWidth:0},kN=(t,e={})=>pk(t,SN,e).width,ze=kN;var hu="\x1B",_k="\x9B",EN=39,dg="\x07",bk="[",IN="]",$k="m",fg=`${IN}8;;`,mk=new RegExp(`(?:\\${bk}(?<code>\\d+)m|\\${fg}(?<uri>.*)${dg})`,"y"),gk=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},vk=t=>`${hu}${bk}${t}${$k}`,yk=t=>`${hu}${fg}${t}${dg}`,lg=(t,e,n)=>{let i=e[Symbol.iterator](),r=!1,o=!1,s=t.at(-1),a=s===void 0?0:ze(s),u=i.next(),c=i.next(),l=0;for(;!u.done;){let d=u.value,f=ze(d);a+f<=n?t[t.length-1]+=d:(t.push(d),a=0),(d===hu||d===_k)&&(r=!0,o=e.startsWith(fg,l+1)),r?o?d===dg&&(r=!1,o=!1):d===$k&&(r=!1):(a+=f,a===n&&!c.done&&(t.push(""),a=0)),u=c,c=i.next(),l+=d.length}s=t.at(-1),!a&&s!==void 0&&s.length&&t.length>1&&(t[t.length-2]+=t.pop())},TN=t=>{let e=t.split(" "),n=e.length;for(;n&&!ze(e[n-1]);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},ON=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let i="",r,o,s=t.split(" "),a=[""],u=0;for(let d=0;d<s.length;d++){let f=s[d];if(n.trim!==!1){let p=a.at(-1)??"",_=p.trimStart();p.length!==_.length&&(a[a.length-1]=_,u=ze(_))}d!==0&&(u>=e&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),u=0),(u||n.trim===!1)&&(a[a.length-1]+=" ",u++));let h=ze(f);if(n.hard&&h>e){let p=e-u,_=1+Math.floor((h-p-1)/e);Math.floor((h-1)/e)<_&&a.push(""),lg(a,f,e),u=ze(a.at(-1)??"");continue}if(u+h>e&&u&&h){if(n.wordWrap===!1&&u<e){lg(a,f,e),u=ze(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>e&&n.wordWrap===!1){lg(a,f,e),u=ze(a.at(-1)??"");continue}a[a.length-1]+=f,u+=h}n.trim!==!1&&(a=a.map(d=>TN(d)));let c=a.join(`
260
- `),l=!1;for(let d=0;d<c.length;d++){let f=c[d];if(i+=f,l)l=!1;else if(l=f>="\uD800"&&f<="\uDBFF",l)continue;if(f===hu||f===_k){mk.lastIndex=d+1;let p=mk.exec(c)?.groups;if(p?.code!==void 0){let _=Number.parseFloat(p.code);r=_===EN?void 0:_}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(c[d+1]===`
259
+ `)}};function gN(t){switch(t){case"ok":return N.ok("OK ");case"warn":return N.warn("WARN");case"fail":return N.fail("FAIL");case"info":return N.dim("INFO")}}function vN(){let t=Be.dir();if(!ok(t))return{dir:t,exists:!1,permsOk:"n/a",detail:"not created yet - run: jarvis init"};if(process.platform==="win32")return{dir:t,exists:!0,permsOk:"n/a",detail:"permissions not enforced on this platform"};let e=(sk(t).mode&63)===0,n=Be.resolve("config.json"),i=!ok(n)||(sk(n).mode&63)===0,r=e&&i;return{dir:t,exists:!0,permsOk:r,detail:r?"owner-only":"should be owner-only (chmod 700 ~/.jarvis; chmod 600 ~/.jarvis/config.json)"}}function yN(t){return t instanceof Error?t.message:String(t)}import{styleText as mg}from"node:util";import{stdout as vg,stdin as Sk}from"node:process";import*as tr from"node:readline";import RN from"node:readline";var uk=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let n=0;for(t.lastIndex=0;t.test(e);)n+=1;return e.length-n}})(),ck=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,lk=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var _N=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,bN=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,dk=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,$N=/\t{1,1000}/y,fk=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,xN=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,wN=/\p{M}+/gu,SN={limit:1/0,ellipsis:""},hk=(t,e={},n={})=>{let i=e.limit??1/0,r=e.ellipsis??"",o=e?.ellipsisWidth??(r?hk(r,SN,n).width:0),s=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,d=n.regularWidth??1,f=n.wideWidth??l,h=[[xN,d],[_N,s],[bN,a],[$N,u],[fk,c],[dk,f]],p=0,_=0,S=t.length,k=0,P=!1,C=S,E=Math.max(0,i-o),T=0,Z=0,F=0,q=0;e:for(;;){if(Z>T||_>=S&&_>p){let ne=t.slice(T,Z)||t.slice(p,_);k=0;for(let $e of ne.replaceAll(wN,"")){let he=$e.codePointAt(0)||0;if(ck(he)?q=l:lk(he)?q=f:q=d,F+q>E&&(C=Math.min(C,Math.max(T,p)+k)),F+q>i){P=!0;break e}k+=$e.length,F+=q}T=Z=0}if(_>=S)break e;for(let ne=0,$e=h.length;ne<$e;ne++){let[he,Se]=h[ne];if(he.lastIndex=_,he.test(t)){if(k=he===dk?uk(t.slice(_,he.lastIndex)):he===fk?1:he.lastIndex-_,q=k*Se,F+q>E&&(C=Math.min(C,_+Math.floor((E-F)/Se))),F+q>i){P=!0;break e}F+=q,T=p,Z=_,_=p=he.lastIndex;continue e}}_+=1}return{width:P?E:F,index:P?C:S,truncated:P,ellipsed:P&&i>=o}},pk=hk;var kN={limit:1/0,ellipsis:"",ellipsisWidth:0},EN=(t,e={})=>pk(t,kN,e).width,ze=EN;var hu="\x1B",_k="\x9B",IN=39,dg="\x07",bk="[",TN="]",$k="m",fg=`${TN}8;;`,mk=new RegExp(`(?:\\${bk}(?<code>\\d+)m|\\${fg}(?<uri>.*)${dg})`,"y"),gk=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},vk=t=>`${hu}${bk}${t}${$k}`,yk=t=>`${hu}${fg}${t}${dg}`,lg=(t,e,n)=>{let i=e[Symbol.iterator](),r=!1,o=!1,s=t.at(-1),a=s===void 0?0:ze(s),u=i.next(),c=i.next(),l=0;for(;!u.done;){let d=u.value,f=ze(d);a+f<=n?t[t.length-1]+=d:(t.push(d),a=0),(d===hu||d===_k)&&(r=!0,o=e.startsWith(fg,l+1)),r?o?d===dg&&(r=!1,o=!1):d===$k&&(r=!1):(a+=f,a===n&&!c.done&&(t.push(""),a=0)),u=c,c=i.next(),l+=d.length}s=t.at(-1),!a&&s!==void 0&&s.length&&t.length>1&&(t[t.length-2]+=t.pop())},ON=t=>{let e=t.split(" "),n=e.length;for(;n&&!ze(e[n-1]);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},AN=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let i="",r,o,s=t.split(" "),a=[""],u=0;for(let d=0;d<s.length;d++){let f=s[d];if(n.trim!==!1){let p=a.at(-1)??"",_=p.trimStart();p.length!==_.length&&(a[a.length-1]=_,u=ze(_))}d!==0&&(u>=e&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),u=0),(u||n.trim===!1)&&(a[a.length-1]+=" ",u++));let h=ze(f);if(n.hard&&h>e){let p=e-u,_=1+Math.floor((h-p-1)/e);Math.floor((h-1)/e)<_&&a.push(""),lg(a,f,e),u=ze(a.at(-1)??"");continue}if(u+h>e&&u&&h){if(n.wordWrap===!1&&u<e){lg(a,f,e),u=ze(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>e&&n.wordWrap===!1){lg(a,f,e),u=ze(a.at(-1)??"");continue}a[a.length-1]+=f,u+=h}n.trim!==!1&&(a=a.map(d=>ON(d)));let c=a.join(`
260
+ `),l=!1;for(let d=0;d<c.length;d++){let f=c[d];if(i+=f,l)l=!1;else if(l=f>="\uD800"&&f<="\uDBFF",l)continue;if(f===hu||f===_k){mk.lastIndex=d+1;let p=mk.exec(c)?.groups;if(p?.code!==void 0){let _=Number.parseFloat(p.code);r=_===IN?void 0:_}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(c[d+1]===`
261
261
  `){o&&(i+=yk(""));let h=r?gk(r):void 0;r&&h&&(i+=vk(h))}else f===`
262
- `&&(r&&gk(r)&&(i+=vk(r)),o&&(i+=yk(o)))}return i},AN=/\r?\n/;function vt(t,e,n){return String(t).normalize().split(AN).map(i=>ON(i,e,n)).join(`
263
- `)}var we=Je(pg(),1);import{ReadStream as wk}from"node:tty";function Pr(t,e,n){if(!n.some(s=>!s.disabled))return t;let i=t+e,r=Math.max(n.length-1,0),o=i<0?r:i>r?0:i;return n[o].disabled?Pr(o,e<0?-1:1,n):o}var RN=["up","down","left","right","space","enter","cancel"],NN=["January","February","March","April","May","June","July","August","September","October","November","December"],fe={actions:new Set(RN),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...NN],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function yg(t,e){if(typeof t=="string")return fe.aliases.get(t)===e;for(let n of t)if(n!==void 0&&yg(n,e))return!0;return!1}function DN(t,e){if(t===e)return;let n=t.split(`
262
+ `&&(r&&gk(r)&&(i+=vk(r)),o&&(i+=yk(o)))}return i},PN=/\r?\n/;function vt(t,e,n){return String(t).normalize().split(PN).map(i=>AN(i,e,n)).join(`
263
+ `)}var we=Je(pg(),1);import{ReadStream as wk}from"node:tty";function Pr(t,e,n){if(!n.some(s=>!s.disabled))return t;let i=t+e,r=Math.max(n.length-1,0),o=i<0?r:i>r?0:i;return n[o].disabled?Pr(o,e<0?-1:1,n):o}var NN=["up","down","left","right","space","enter","cancel"],DN=["January","February","March","April","May","June","July","August","September","October","November","December"],fe={actions:new Set(NN),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...DN],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function yg(t,e){if(typeof t=="string")return fe.aliases.get(t)===e;for(let n of t)if(n!==void 0&&yg(n,e))return!0;return!1}function LN(t,e){if(t===e)return;let n=t.split(`
264
264
  `),i=e.split(`
265
- `),r=Math.max(n.length,i.length),o=[];for(let s=0;s<r;s++)n[s]!==i[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:i.length,numLines:r}}var LN=globalThis.process.platform.startsWith("win"),gg=Symbol("clack:cancel");function _u(t){return t===gg}function pu(t,e){let n=t;n.isTTY&&n.setRawMode(e)}function kk({input:t=Sk,output:e=vg,overwrite:n=!0,hideCursor:i=!0}={}){let r=tr.createInterface({input:t,output:e,prompt:"",tabSize:1});tr.emitKeypressEvents(t,r),t instanceof wk&&t.isTTY&&t.setRawMode(!0);let o=(s,{name:a,sequence:u})=>{let c=String(s);if(yg([c,a,u],"cancel")){i&&e.write(we.cursor.show),process.exit(0);return}if(!n)return;tr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{tr.clearLine(e,1,()=>{t.once("keypress",o)})})};return i&&e.write(we.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),i&&e.write(we.cursor.show),t instanceof wk&&t.isTTY&&!LN&&t.setRawMode(!1),r.terminal=!1,r.close()}}var oo=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,_g=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function rr(t,e,n,i=n,r=n,o){let s=oo(t??vg);return vt(e,s-n.length,{hard:!0,trim:!1}).split(`
265
+ `),r=Math.max(n.length,i.length),o=[];for(let s=0;s<r;s++)n[s]!==i[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:i.length,numLines:r}}var UN=globalThis.process.platform.startsWith("win"),gg=Symbol("clack:cancel");function _u(t){return t===gg}function pu(t,e){let n=t;n.isTTY&&n.setRawMode(e)}function kk({input:t=Sk,output:e=vg,overwrite:n=!0,hideCursor:i=!0}={}){let r=tr.createInterface({input:t,output:e,prompt:"",tabSize:1});tr.emitKeypressEvents(t,r),t instanceof wk&&t.isTTY&&t.setRawMode(!0);let o=(s,{name:a,sequence:u})=>{let c=String(s);if(yg([c,a,u],"cancel")){i&&e.write(we.cursor.show),process.exit(0);return}if(!n)return;tr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{tr.clearLine(e,1,()=>{t.once("keypress",o)})})};return i&&e.write(we.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),i&&e.write(we.cursor.show),t instanceof wk&&t.isTTY&&!UN&&t.setRawMode(!1),r.terminal=!1,r.close()}}var oo=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,_g=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function rr(t,e,n,i=n,r=n,o){let s=oo(t??vg);return vt(e,s-n.length,{hard:!0,trim:!1}).split(`
266
266
  `).map((a,u,c)=>{let l=o?o(a,u):a;return u===0?`${i}${l}`:u===c.length-1?`${r}${l}`:`${n}${l}`}).join(`
267
- `)}function Ek(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}var Cr=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,n=!0){let{input:i=Sk,output:r=vg,render:o,signal:s,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=o.bind(this),this._track=n,this._abortSignal=s,this.input=i,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let i=this._subscribers.get(e)??[];i.push(n),this._subscribers.set(e,i)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let i=this._subscribers.get(e)??[],r=[];for(let o of i)o.cb(...n),o.once&&r.push(()=>i.splice(i.indexOf(o),1));for(let o of r)o()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(gg);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=zN.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),pu(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),pu(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),pu(this.input,!1),e(gg)})})}_isActionKey(e,n){return e===" "}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&fe.aliases.has(n.name)&&this.emit("cursor",fe.aliases.get(n.name)),fe.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let i=Ek(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}yg([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
267
+ `)}function Ek(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}var Cr=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,n=!0){let{input:i=Sk,output:r=vg,render:o,signal:s,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=o.bind(this),this._track=n,this._abortSignal=s,this.input=i,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let i=this._subscribers.get(e)??[];i.push(n),this._subscribers.set(e,i)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let i=this._subscribers.get(e)??[],r=[];for(let o of i)o.cb(...n),o.once&&r.push(()=>i.splice(i.indexOf(o),1));for(let o of r)o()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(gg);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=RN.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),pu(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),pu(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(we.cursor.show),this.output.off("resize",this.render),pu(this.input,!1),e(gg)})})}_isActionKey(e,n){return e===" "}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&fe.aliases.has(n.name)&&this.emit("cursor",fe.aliases.get(n.name)),fe.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let i=Ek(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}yg([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
268
268
  `),pu(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=vt(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
269
- `).length-1;this.output.write(we.cursor.move(-999,e*-1))}render(){let e=vt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(we.cursor.hide);else{let n=DN(this._prevFrame,e),i=_g(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-i),o=Math.max(0,n.numLinesBefore-i),s=n.lines.find(a=>a>=r);if(s===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(we.cursor.move(0,s-o)),this.output.write(we.erase.lines(1));let a=e.split(`
269
+ `).length-1;this.output.write(we.cursor.move(-999,e*-1))}render(){let e=vt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(we.cursor.hide);else{let n=LN(this._prevFrame,e),i=_g(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-i),o=Math.max(0,n.numLinesBefore-i),s=n.lines.find(a=>a>=r);if(s===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(we.cursor.move(0,s-o)),this.output.write(we.erase.lines(1));let a=e.split(`
270
270
  `);this.output.write(a[s]),this._prevFrame=e,this.output.write(we.cursor.move(0,a.length-s-1));return}else if(n.lines.length>1){if(r<o)s=r;else{let u=s-o;u>0&&this.output.write(we.cursor.move(0,u))}this.output.write(we.erase.down());let a=e.split(`
271
271
  `).slice(s);this.output.write(a.join(`
272
- `)),this._prevFrame=e;return}}this.output.write(we.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var mu=class extends Cr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(we.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var Ik=class extends Cr{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,n=this.value!==void 0&&this.value.length===e.length;this.value=n?[]:e.map(i=>i.value)}toggleInvert(){let e=this.value;if(!e)return;let n=this._enabledOptions.filter(i=>!e.includes(i.value));this.value=n.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(n=>n!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let n=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),0);this.cursor=this.options[n].disabled?Pr(n,1,this.options):n,this.on("key",(i,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},gu=class extends Cr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${mg(["inverse","hidden"],"_")}`;let n=this.masked,i=n.slice(0,this.cursor),r=n.slice(this.cursor);return`${i}${mg("inverse",r[0])}${r.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...n}){super(n),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},vu=class extends Cr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:r})=>r===e.initialValue),i=n===-1?0:n;this.cursor=this.options[i].disabled?Pr(i,1,this.options):i,this.changeValue(),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break}this.changeValue()})}};var yu=class extends Cr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let n=e.slice(0,this.cursor),[i,...r]=e.slice(this.cursor);return`${n}${mg("inverse",i)}${r.join("")}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",n=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as y,stripVTControlCharacters as iZ}from"node:util";import nt from"node:process";var ao=Je(pg(),1);function UN(){return nt.platform!=="win32"?nt.env.TERM!=="linux":!!nt.env.CI||!!nt.env.WT_SESSION||!!nt.env.TERMINUS_SUBLIME||nt.env.ConEmuTask==="{cmd::Cmder}"||nt.env.TERM_PROGRAM==="Terminus-Sublime"||nt.env.TERM_PROGRAM==="vscode"||nt.env.TERM==="xterm-256color"||nt.env.TERM==="alacritty"||nt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var bg=UN(),jN=()=>process.env.CI==="true";var Y=(t,e)=>bg?t:e,MN=Y("\u25C6","*"),Ck=Y("\u25A0","x"),zk=Y("\u25B2","x"),xu=Y("\u25C7","o"),FN=Y("\u250C","T"),M=Y("\u2502","|"),yt=Y("\u2514","\u2014"),uZ=Y("\u2510","T"),cZ=Y("\u2518","\u2014"),$g=Y("\u25CF",">"),$u=Y("\u25CB"," "),VN=Y("\u25FB","[\u2022]"),Tk=Y("\u25FC","[+]"),Ok=Y("\u25FB","[ ]"),ZN=Y("\u25AA","\u2022"),Ak=Y("\u2500","-"),BN=Y("\u256E","+"),GN=Y("\u251C","+"),WN=Y("\u256F","+"),qN=Y("\u2570","+"),lZ=Y("\u256D","+"),HN=Y("\u25CF","\u2022"),JN=Y("\u25C6","*"),KN=Y("\u25B2","!"),YN=Y("\u25A0","x"),uo=t=>{switch(t){case"initial":case"active":return y("cyan",MN);case"cancel":return y("red",Ck);case"error":return y("yellow",zk);case"submit":return y("green",xu)}},Rk=t=>{switch(t){case"initial":case"active":return y("cyan",M);case"cancel":return y("red",M);case"error":return y("yellow",M);case"submit":return y("green",M)}},Pk=(t,e,n,i,r,o=!1)=>{let s=e,a=0;if(o)for(let u=i-1;u>=n&&(s-=t[u].length,a++,!(s<=r));u--);else for(let u=n;u<i&&(s-=t[u].length,a++,!(s<=r));u++);return{lineCount:s,removals:a}},xg=({cursor:t,options:e,style:n,output:i=process.stdout,maxItems:r=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let a=oo(i)-o,u=_g(i),c=y("dim","..."),l=Math.max(u-s,0),d=Math.max(Math.min(r,l),5),f=0;t>=d-3&&(f=Math.max(Math.min(t-d+3,e.length-d),0));let h=d<e.length&&f>0,p=d<e.length&&f+d<e.length,_=Math.min(f+d,e.length),S=[],k=0;h&&k++,p&&k++;let P=f+(h?1:0),C=_-(p?1:0);for(let T=P;T<C;T++){let Z=vt(n(e[T],T===t),a,{hard:!0,trim:!1}).split(`
272
+ `)),this._prevFrame=e;return}}this.output.write(we.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var mu=class extends Cr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(we.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var Ik=class extends Cr{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,n=this.value!==void 0&&this.value.length===e.length;this.value=n?[]:e.map(i=>i.value)}toggleInvert(){let e=this.value;if(!e)return;let n=this._enabledOptions.filter(i=>!e.includes(i.value));this.value=n.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(n=>n!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let n=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),0);this.cursor=this.options[n].disabled?Pr(n,1,this.options):n,this.on("key",(i,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},gu=class extends Cr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${mg(["inverse","hidden"],"_")}`;let n=this.masked,i=n.slice(0,this.cursor),r=n.slice(this.cursor);return`${i}${mg("inverse",r[0])}${r.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...n}){super(n),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},vu=class extends Cr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:r})=>r===e.initialValue),i=n===-1?0:n;this.cursor=this.options[i].disabled?Pr(i,1,this.options):i,this.changeValue(),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=Pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Pr(this.cursor,1,this.options);break}this.changeValue()})}};var yu=class extends Cr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let n=e.slice(0,this.cursor),[i,...r]=e.slice(this.cursor);return`${n}${mg("inverse",i)}${r.join("")}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",n=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as y,stripVTControlCharacters as oZ}from"node:util";import nt from"node:process";var ao=Je(pg(),1);function jN(){return nt.platform!=="win32"?nt.env.TERM!=="linux":!!nt.env.CI||!!nt.env.WT_SESSION||!!nt.env.TERMINUS_SUBLIME||nt.env.ConEmuTask==="{cmd::Cmder}"||nt.env.TERM_PROGRAM==="Terminus-Sublime"||nt.env.TERM_PROGRAM==="vscode"||nt.env.TERM==="xterm-256color"||nt.env.TERM==="alacritty"||nt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var bg=jN(),MN=()=>process.env.CI==="true";var Y=(t,e)=>bg?t:e,FN=Y("\u25C6","*"),Ck=Y("\u25A0","x"),zk=Y("\u25B2","x"),xu=Y("\u25C7","o"),VN=Y("\u250C","T"),M=Y("\u2502","|"),yt=Y("\u2514","\u2014"),cZ=Y("\u2510","T"),lZ=Y("\u2518","\u2014"),$g=Y("\u25CF",">"),$u=Y("\u25CB"," "),ZN=Y("\u25FB","[\u2022]"),Tk=Y("\u25FC","[+]"),Ok=Y("\u25FB","[ ]"),BN=Y("\u25AA","\u2022"),Ak=Y("\u2500","-"),GN=Y("\u256E","+"),WN=Y("\u251C","+"),qN=Y("\u256F","+"),HN=Y("\u2570","+"),dZ=Y("\u256D","+"),JN=Y("\u25CF","\u2022"),KN=Y("\u25C6","*"),YN=Y("\u25B2","!"),XN=Y("\u25A0","x"),uo=t=>{switch(t){case"initial":case"active":return y("cyan",FN);case"cancel":return y("red",Ck);case"error":return y("yellow",zk);case"submit":return y("green",xu)}},Rk=t=>{switch(t){case"initial":case"active":return y("cyan",M);case"cancel":return y("red",M);case"error":return y("yellow",M);case"submit":return y("green",M)}},Pk=(t,e,n,i,r,o=!1)=>{let s=e,a=0;if(o)for(let u=i-1;u>=n&&(s-=t[u].length,a++,!(s<=r));u--);else for(let u=n;u<i&&(s-=t[u].length,a++,!(s<=r));u++);return{lineCount:s,removals:a}},xg=({cursor:t,options:e,style:n,output:i=process.stdout,maxItems:r=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let a=oo(i)-o,u=_g(i),c=y("dim","..."),l=Math.max(u-s,0),d=Math.max(Math.min(r,l),5),f=0;t>=d-3&&(f=Math.max(Math.min(t-d+3,e.length-d),0));let h=d<e.length&&f>0,p=d<e.length&&f+d<e.length,_=Math.min(f+d,e.length),S=[],k=0;h&&k++,p&&k++;let P=f+(h?1:0),C=_-(p?1:0);for(let T=P;T<C;T++){let Z=vt(n(e[T],T===t),a,{hard:!0,trim:!1}).split(`
273
273
  `);S.push(Z),k+=Z.length}if(k>l){let T=0,Z=0,F=k,q=t-P,ne=l,$e=()=>Pk(S,F,0,q,ne),he=()=>Pk(S,F,q+1,S.length,ne,!0);h?({lineCount:F,removals:T}=$e(),F>ne&&(p||(ne-=1),{lineCount:F,removals:Z}=he())):(p||(ne-=1),{lineCount:F,removals:Z}=he(),F>ne&&(ne-=1,{lineCount:F,removals:T}=$e())),T>0&&(h=!0,S.splice(0,T)),Z>0&&(p=!0,S.splice(S.length-Z,Z))}let E=[];h&&E.push(c);for(let T of S)for(let Z of T)E.push(Z);return p&&E.push(c),E};var wu=t=>{let e=t.active??"Yes",n=t.inactive??"No";return new mu({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let i=t.withGuide??fe.withGuide,r=`${uo(this.state)} `,o=i?`${y("gray",M)} `:"",s=rr(t.output,t.message,o,r),a=`${i?`${y("gray",M)}
274
274
  `:""}${s}
275
275
  `,u=this.value?e:n;switch(this.state){case"submit":{let c=i?`${y("gray",M)} `:"";return`${a}${c}${y("dim",u)}`}case"cancel":{let c=i?`${y("gray",M)} `:"";return`${a}${c}${y(["strikethrough","dim"],u)}${i?`
@@ -280,15 +280,15 @@ ${l}
280
280
  `}}}}).prompt()};var qe={message:(t=[],{symbol:e=y("gray",M),secondarySymbol:n=y("gray",M),output:i=process.stdout,spacing:r=1,withGuide:o}={})=>{let s=[],a=o??fe.withGuide,u=a?n:"",c=a?`${e} `:"",l=a?`${n} `:"";for(let f=0;f<r;f++)s.push(u);let d=Array.isArray(t)?t:t.split(`
281
281
  `);if(d.length>0){let[f,...h]=d;f.length>0?s.push(`${c}${f}`):s.push(a?e:"");for(let p of h)p.length>0?s.push(`${l}${p}`):s.push(a?n:"")}i.write(`${s.join(`
282
282
  `)}
283
- `)},info:(t,e)=>{qe.message(t,{...e,symbol:y("blue",HN)})},success:(t,e)=>{qe.message(t,{...e,symbol:y("green",JN)})},step:(t,e)=>{qe.message(t,{...e,symbol:y("green",xu)})},warn:(t,e)=>{qe.message(t,{...e,symbol:y("yellow",KN)})},warning:(t,e)=>{qe.warn(t,e)},error:(t,e)=>{qe.message(t,{...e,symbol:y("red",YN)})}},Nk=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",yt)} `:"";n.write(`${i}${y("red",t)}
283
+ `)},info:(t,e)=>{qe.message(t,{...e,symbol:y("blue",JN)})},success:(t,e)=>{qe.message(t,{...e,symbol:y("green",KN)})},step:(t,e)=>{qe.message(t,{...e,symbol:y("green",xu)})},warn:(t,e)=>{qe.message(t,{...e,symbol:y("yellow",YN)})},warning:(t,e)=>{qe.warn(t,e)},error:(t,e)=>{qe.message(t,{...e,symbol:y("red",XN)})}},Nk=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",yt)} `:"";n.write(`${i}${y("red",t)}
284
284
 
285
- `)},Dk=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",FN)} `:"";n.write(`${i}${t}
285
+ `)},Dk=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",VN)} `:"";n.write(`${i}${t}
286
286
  `)},Lk=(t="",e)=>{let n=e?.output??process.stdout,i=e?.withGuide??fe.withGuide?`${y("gray",M)}
287
287
  ${y("gray",yt)} `:"";n.write(`${i}${t}
288
288
 
289
289
  `)};var so=(t,e)=>t.split(`
290
290
  `).map(n=>e(n)).join(`
291
- `),Uk=t=>{let e=(i,r)=>{let o=i.label??String(i.value);return r==="disabled"?`${y("gray",Ok)} ${so(o,s=>y(["strikethrough","gray"],s))}${i.hint?` ${y("dim",`(${i.hint??"disabled"})`)}`:""}`:r==="active"?`${y("cyan",VN)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="selected"?`${y("green",Tk)} ${so(o,s=>y("dim",s))}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="cancelled"?`${so(o,s=>y(["strikethrough","dim"],s))}`:r==="active-selected"?`${y("green",Tk)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="submitted"?`${so(o,s=>y("dim",s))}`:`${y("dim",Ok)} ${so(o,s=>y("dim",s))}`},n=t.required??!0;return new Ik({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
291
+ `),Uk=t=>{let e=(i,r)=>{let o=i.label??String(i.value);return r==="disabled"?`${y("gray",Ok)} ${so(o,s=>y(["strikethrough","gray"],s))}${i.hint?` ${y("dim",`(${i.hint??"disabled"})`)}`:""}`:r==="active"?`${y("cyan",ZN)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="selected"?`${y("green",Tk)} ${so(o,s=>y("dim",s))}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="cancelled"?`${so(o,s=>y(["strikethrough","dim"],s))}`:r==="active-selected"?`${y("green",Tk)} ${o}${i.hint?` ${y("dim",`(${i.hint})`)}`:""}`:r==="submitted"?`${so(o,s=>y("dim",s))}`:`${y("dim",Ok)} ${so(o,s=>y("dim",s))}`},n=t.required??!0;return new Ik({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
292
292
  ${y("reset",y("dim",`Press ${y(["gray","bgWhite","inverse"]," space ")} to select, ${y("gray",y("bgWhite",y("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??fe.withGuide,r=rr(t.output,t.message,i?`${Rk(this.state)} `:"",`${uo(this.state)} `),o=`${i?`${y("gray",M)}
293
293
  `:""}${r}
294
294
  `,s=this.value??[],a=(u,c)=>{if(u.disabled)return e(u,"disabled");let l=s.includes(u.value);return c&&l?e(u,"active-selected"):l?e(u,"selected"):e(u,c?"active":"inactive")};switch(this.state){case"submit":{let u=this.options.filter(({value:l})=>s.includes(l)).map(l=>e(l,"submitted")).join(y("dim",", "))||y("dim","none"),c=rr(t.output,u,i?`${y("gray",M)} `:"");return`${o}${c}`}case"cancel":{let u=this.options.filter(({value:l})=>s.includes(l)).map(l=>e(l,"cancelled")).join(y("dim",", "));if(u.trim()==="")return`${o}${y("gray",M)}`;let c=rr(t.output,u,i?`${y("gray",M)} `:"");return`${o}${c}${i?`
@@ -303,14 +303,14 @@ ${c}
303
303
  `).length,l=i?2:1;return`${o}${u}${xg({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:c+l,style:a}).join(`
304
304
  ${u}`)}
305
305
  ${i?y("cyan",yt):""}
306
- `}}}}).prompt()},XN=t=>y("dim",t),QN=(t,e,n)=>{let i={hard:!0,trim:!1},r=vt(t,e,i).split(`
307
- `),o=r.reduce((u,c)=>Math.max(ze(c),u),0),s=r.map(n).reduce((u,c)=>Math.max(ze(c),u),0),a=e-(s-o);return vt(t,a,i)},wg=(t="",e="",n)=>{let i=n?.output??nt.stdout,r=n?.withGuide??fe.withGuide,o=n?.format??XN,s=["",...QN(t,oo(i)-6,o).split(`
306
+ `}}}}).prompt()},QN=t=>y("dim",t),e4=(t,e,n)=>{let i={hard:!0,trim:!1},r=vt(t,e,i).split(`
307
+ `),o=r.reduce((u,c)=>Math.max(ze(c),u),0),s=r.map(n).reduce((u,c)=>Math.max(ze(c),u),0),a=e-(s-o);return vt(t,a,i)},wg=(t="",e="",n)=>{let i=n?.output??nt.stdout,r=n?.withGuide??fe.withGuide,o=n?.format??QN,s=["",...e4(t,oo(i)-6,o).split(`
308
308
  `).map(o),""],a=ze(e),u=Math.max(s.reduce((f,h)=>{let p=ze(h);return p>f?p:f},0),a)+2,c=s.map(f=>`${y("gray",M)} ${f}${" ".repeat(u-ze(f))}${y("gray",M)}`).join(`
309
309
  `),l=r?`${y("gray",M)}
310
- `:"",d=r?GN:qN;i.write(`${l}${y("green",xu)} ${y("reset",e)} ${y("gray",Ak.repeat(Math.max(u-a-1,1))+BN)}
310
+ `:"",d=r?WN:HN;i.write(`${l}${y("green",xu)} ${y("reset",e)} ${y("gray",Ak.repeat(Math.max(u-a-1,1))+GN)}
311
311
  ${c}
312
- ${y("gray",d+Ak.repeat(u+2)+WN)}
313
- `)},jk=t=>new gu({validate:t.validate,mask:t.mask??ZN,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??fe.withGuide,n=`${e?`${y("gray",M)}
312
+ ${y("gray",d+Ak.repeat(u+2)+qN)}
313
+ `)},jk=t=>new gu({validate:t.validate,mask:t.mask??BN,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??fe.withGuide,n=`${e?`${y("gray",M)}
314
314
  `:""}${uo(this.state)} ${t.message}
315
315
  `,i=this.userInputWithCursor,r=this.masked;switch(this.state){case"error":{let o=e?`${y("yellow",M)} `:"",s=e?`${y("yellow",yt)} `:"",a=r??"";return t.clearOnError&&this.clear(),`${n.trim()}
316
316
  ${o}${a}
@@ -318,12 +318,12 @@ ${s}${y("yellow",this.error)}
318
318
  `}case"submit":{let o=e?`${y("gray",M)} `:"",s=r?y("dim",r):"";return`${n}${o}${s}`}case"cancel":{let o=e?`${y("gray",M)} `:"",s=r?y(["strikethrough","dim"],r):"";return`${n}${o}${s}${r&&e?`
319
319
  ${y("gray",M)}`:""}`}default:{let o=e?`${y("cyan",M)} `:"",s=e?y("cyan",yt):"";return`${n}${o}${i}
320
320
  ${s}
321
- `}}}}).prompt();var e4=t=>y("magenta",t),Mk=({indicator:t="dots",onCancel:e,output:n=process.stdout,cancelMessage:i,errorMessage:r,frames:o=bg?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=bg?80:120,signal:a,...u}={})=>{let c=jN(),l,d,f=!1,h=!1,p="",_,S=performance.now(),k=oo(n),P=u?.styleFrame??e4,C=Q=>{let D=Q>1?r??fe.messages.error:i??fe.messages.cancel;h=Q===1,f&&(ke(D,Q),h&&typeof e=="function"&&e())},E=()=>C(2),T=()=>C(1),Z=()=>{process.on("uncaughtExceptionMonitor",E),process.on("unhandledRejection",E),process.on("SIGINT",T),process.on("SIGTERM",T),process.on("exit",C),a&&a.addEventListener("abort",T)},F=()=>{process.removeListener("uncaughtExceptionMonitor",E),process.removeListener("unhandledRejection",E),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T),process.removeListener("exit",C),a&&a.removeEventListener("abort",T)},q=()=>{if(_===void 0)return;c&&n.write(`
321
+ `}}}}).prompt();var t4=t=>y("magenta",t),Mk=({indicator:t="dots",onCancel:e,output:n=process.stdout,cancelMessage:i,errorMessage:r,frames:o=bg?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=bg?80:120,signal:a,...u}={})=>{let c=MN(),l,d,f=!1,h=!1,p="",_,S=performance.now(),k=oo(n),P=u?.styleFrame??t4,C=Q=>{let D=Q>1?r??fe.messages.error:i??fe.messages.cancel;h=Q===1,f&&(ke(D,Q),h&&typeof e=="function"&&e())},E=()=>C(2),T=()=>C(1),Z=()=>{process.on("uncaughtExceptionMonitor",E),process.on("unhandledRejection",E),process.on("SIGINT",T),process.on("SIGTERM",T),process.on("exit",C),a&&a.addEventListener("abort",T)},F=()=>{process.removeListener("uncaughtExceptionMonitor",E),process.removeListener("unhandledRejection",E),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T),process.removeListener("exit",C),a&&a.removeEventListener("abort",T)},q=()=>{if(_===void 0)return;c&&n.write(`
322
322
  `);let Q=vt(_,k,{hard:!0,trim:!1}).split(`
323
323
  `);Q.length>1&&n.write(ao.cursor.up(Q.length-1)),n.write(ao.cursor.to(0)),n.write(ao.erase.down())},ne=Q=>Q.replace(/\.+$/,""),$e=Q=>{let D=(performance.now()-Q)/1e3,ce=Math.floor(D/60),it=Math.floor(D%60);return ce>0?`[${ce}m ${it}s]`:`[${it}s]`},he=u.withGuide??fe.withGuide,Se=(Q="")=>{f=!0,l=kk({output:n}),p=ne(Q),S=performance.now(),he&&n.write(`${y("gray",M)}
324
324
  `);let D=0,ce=0;Z(),d=setInterval(()=>{if(c&&p===_)return;q(),_=p;let it=P(o[D]),je;if(c)je=`${it} ${p}...`;else if(t==="timer")je=`${it} ${p} ${$e(S)}`;else{let le=".".repeat(Math.floor(ce)).slice(0,3);je=`${it} ${p}${le}`}let zr=vt(je,k,{hard:!0,trim:!1});n.write(zr),D=D+1<o.length?D+1:0,ce=ce<4?ce+.125:0},s)},ke=(Q="",D=0,ce=!1)=>{if(!f)return;f=!1,clearInterval(d),q();let it=D===0?y("green",xu):D===1?y("red",Ck):y("red",zk);p=Q??p,ce||(t==="timer"?n.write(`${it} ${p} ${$e(S)}
325
325
  `):n.write(`${it} ${p}
326
- `)),F(),l()};return{start:Se,stop:(Q="")=>ke(Q,0),message:(Q="")=>{p=ne(Q??p)},cancel:(Q="")=>ke(Q,1),error:(Q="")=>ke(Q,2),clear:()=>ke("",0,!0),get isCancelled(){return h}}},dZ={light:Y("\u2500","-"),heavy:Y("\u2501","="),block:Y("\u2588","#")};var bu=(t,e)=>t.includes(`
326
+ `)),F(),l()};return{start:Se,stop:(Q="")=>ke(Q,0),message:(Q="")=>{p=ne(Q??p)},cancel:(Q="")=>ke(Q,1),error:(Q="")=>ke(Q,2),clear:()=>ke("",0,!0),get isCancelled(){return h}}},fZ={light:Y("\u2500","-"),heavy:Y("\u2501","="),block:Y("\u2588","#")};var bu=(t,e)=>t.includes(`
327
327
  `)?t.split(`
328
328
  `).map(n=>e(n)).join(`
329
329
  `):e(t),co=t=>{let e=(n,i)=>{let r=n.label??String(n.value);switch(i){case"disabled":return`${y("gray",$u)} ${bu(r,o=>y("gray",o))}${n.hint?` ${y("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${bu(r,o=>y("dim",o))}`;case"active":return`${y("green",$g)} ${r}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${bu(r,o=>y(["strikethrough","dim"],o))}`;default:return`${y("dim",$u)} ${bu(r,o=>y("dim",o))}`}};return new vu({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let n=t.withGuide??fe.withGuide,i=`${uo(this.state)} `,r=`${Rk(this.state)} `,o=rr(t.output,t.message,r,i),s=`${n?`${y("gray",M)}
@@ -333,7 +333,7 @@ ${y("gray",M)}`:""}`}default:{let a=n?`${y("cyan",M)} `:"",u=n?y("cyan",yt):"",
333
333
  `).length,l=n?2:1;return`${s}${a}${xg({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:a.length,rowPadding:c+l,style:(d,f)=>e(d,d.disabled?"disabled":f?"active":"inactive")}).join(`
334
334
  ${a}`)}
335
335
  ${u}
336
- `}}}}).prompt()};var fZ=`${y("gray",M)} `;var Fk=t=>new yu({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??fe.withGuide,n=`${`${e?`${y("gray",M)}
336
+ `}}}}).prompt()};var hZ=`${y("gray",M)} `;var Fk=t=>new yu({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??fe.withGuide,n=`${`${e?`${y("gray",M)}
337
337
  `:""}${uo(this.state)} `}${t.message}
338
338
  `,i=t.placeholder?y("inverse",t.placeholder[0])+y("dim",t.placeholder.slice(1)):y(["inverse","hidden"],"_"),r=this.userInput?this.userInputWithCursor:i,o=this.value??"";switch(this.state){case"error":{let s=this.error?` ${y("yellow",this.error)}`:"",a=e?`${y("yellow",M)} `:"",u=e?y("yellow",yt):"";return`${n.trim()}
339
339
  ${a}${r}
@@ -341,31 +341,31 @@ ${u}${s}
341
341
  `}case"submit":{let s=o?` ${y("dim",o)}`:"",a=e?y("gray",M):"";return`${n}${a}${s}`}case"cancel":{let s=o?` ${y(["strikethrough","dim"],o)}`:"",a=e?y("gray",M):"";return`${n}${a}${s}${o.trim()?`
342
342
  ${a}`:""}`}default:{let s=e?`${y("cyan",M)} `:"",a=e?y("cyan",yt):"";return`${n}${s}${r}
343
343
  ${a}
344
- `}}}}).prompt();Ae();pr();var t4={brain:["text"],voice:["stt","tts"],memory:["embedding"]},Vk=["brain","voice","memory"],Sg="brain",r4=["text","stt","tts","embedding"];function n4(t){return t==="text"}function Zk(t){let e=new Set;for(let n of t)for(let i of t4[n])e.add(i);return r4.filter(n=>e.has(n))}function Bk(t){let e=["brain"],n=t.routes;return(n?.stt||n?.tts)&&e.push("voice"),n?.embedding&&e.push("memory"),e}function Gk(t,e){if(e==="valid")return[];let n=n4(t);return e==="invalid"?n?["retry","change"]:["retry","change","skip"]:n?["save","retry","change"]:["save","retry","change","skip"]}function Wk(t){let e={},n={};for(let r of t.routes){e[r.capability]={provider:r.provider,model:r.model};let o=t.keys.get(r.provider);o!==void 0&&o.length>0&&(n[r.provider]=o)}let i={version:t.existing.version,defaults:{logLevel:t.logLevel,modality:t.modality},upgrade:{auto:t.existing.upgrade.auto}};return Object.keys(e).length>0&&(i.routes=e),Object.keys(n).length>0&&(i.secrets=n),i}function qk(t,e){return!!t.isTTY&&!!e.isTTY}var lo=class extends Error{},Hk={save:{label:"save anyway",hint:"keep this key; verify later with jarvis doctor"},retry:{label:"re-enter the key"},change:{label:"choose a different provider"},skip:{label:"skip this capability",hint:"optional"}},Su=class{config;probe;io;stdin;stdout;constructor(e){this.config=e.config,this.probe=e.probe,this.io=e.io??ue,this.stdin=e.stdin??process.stdin,this.stdout=e.stdout??process.stdout}async run(){if(!qk(this.stdin,this.stdout))return this.printHeadlessGuidance(),1;try{return await this.wizard()}catch(e){if(e instanceof lo)return Nk("no changes written."),130;throw e}}loadExisting(){try{return{config:this.config.resolved(),corrupt:!1}}catch{return{config:hr.parse({}),corrupt:!0}}}async wizard(){let{config:e,corrupt:n}=this.loadExisting(),i=!n&&!!(e.routes??e.secrets);Dk(N.bold("jarvis init")),n&&qe.warn("the existing config.json is invalid; init will replace it with a fresh config."),wg(`Writes ${N.accent(Be.resolve("config.json"))} (owner-only).`+(i?`
344
+ `}}}}).prompt();Ae();pr();var r4={brain:["text"],voice:["stt","tts"],memory:["embedding"]},Vk=["brain","voice","memory"],Sg="brain",n4=["text","stt","tts","embedding"];function i4(t){return t==="text"}function Zk(t){let e=new Set;for(let n of t)for(let i of r4[n])e.add(i);return n4.filter(n=>e.has(n))}function Bk(t){let e=["brain"],n=t.routes;return(n?.stt||n?.tts)&&e.push("voice"),n?.embedding&&e.push("memory"),e}function Gk(t,e){if(e==="valid")return[];let n=i4(t);return e==="invalid"?n?["retry","change"]:["retry","change","skip"]:n?["save","retry","change"]:["save","retry","change","skip"]}function Wk(t){let e={},n={};for(let r of t.routes){e[r.capability]={provider:r.provider,model:r.model};let o=t.keys.get(r.provider);o!==void 0&&o.length>0&&(n[r.provider]=o)}let i={version:t.existing.version,defaults:{logLevel:t.logLevel,modality:t.modality},upgrade:{auto:t.existing.upgrade.auto}};return Object.keys(e).length>0&&(i.routes=e),Object.keys(n).length>0&&(i.secrets=n),i}function qk(t,e){return!!t.isTTY&&!!e.isTTY}var lo=class extends Error{},Hk={save:{label:"save anyway",hint:"keep this key; verify later with jarvis doctor"},retry:{label:"re-enter the key"},change:{label:"choose a different provider"},skip:{label:"skip this capability",hint:"optional"}},Su=class{config;probe;io;stdin;stdout;constructor(e){this.config=e.config,this.probe=e.probe,this.io=e.io??ue,this.stdin=e.stdin??process.stdin,this.stdout=e.stdout??process.stdout}async run(){if(!qk(this.stdin,this.stdout))return this.printHeadlessGuidance(),1;try{return await this.wizard()}catch(e){if(e instanceof lo)return Nk("no changes written."),130;throw e}}loadExisting(){try{return{config:this.config.resolved(),corrupt:!1}}catch{return{config:hr.parse({}),corrupt:!0}}}async wizard(){let{config:e,corrupt:n}=this.loadExisting(),i=!n&&!!(e.routes??e.secrets);Dk(N.bold("jarvis init")),n&&qe.warn("the existing config.json is invalid; init will replace it with a fresh config."),wg(`Writes ${N.accent(Be.resolve("config.json"))} (owner-only).`+(i?`
345
345
  A config already exists - values are prefilled; edit or keep them.`:""),"setup");let r=await this.pickCapabilities(e),o=new Map,s=[];for(let d of Zk(r)){let f=await this.configureCapability(d,e,o);f&&s.push(f)}let a=this.ensure(await co({message:"Default modality",options:[{value:"voice",label:"voice",hint:"speak and listen when available"},{value:"text",label:"text",hint:"text-only"}],initialValue:e.defaults.modality})),u=this.ensure(await co({message:"Log level",options:["debug","info","warn","error"].map(d=>({value:d,label:d})),initialValue:e.defaults.logLevel}));if(this.review(s,o,a,u),!this.ensure(await wu({message:"Write this configuration?"})))throw new lo;return this.config.write(Wk({existing:e,routes:s,keys:o,modality:a,logLevel:u})),qe.success(`wrote ${Be.resolve("config.json")}`),await wu({message:"Start Jarvis now?",initialValue:!1})===!0&&qe.info("starting is not wired yet in v0.1 - run `jarvis` to begin a session."),Lk(N.ok("done.")),0}async pickCapabilities(e){let n=this.ensure(await Uk({message:"Which capabilities do you want to set up?",options:[{value:"brain",label:"Brain (text)",hint:"required - the reasoning model"},{value:"voice",label:"Voice (speech in + out)",hint:"optional"},{value:"memory",label:"Memory (embeddings)",hint:"optional"}],initialValues:Bk(e),required:!1}));n.includes(Sg)||qe.warn("Brain (text) is required; keeping it selected.");let i=new Set(n);return i.add(Sg),Vk.filter(r=>i.has(r))}async configureCapability(e,n,i){let r=this.probe.providersFor(e);if(r.length===0)return qe.warn(`no providers available for ${e}; skipping.`),null;for(;;){let o=await this.pickProvider(e,r,n),s=await this.pickModel(e,o,n);if(i.has(o))return{capability:e,provider:o,model:s};let a=await this.resolveKey(e,o,s,n,i);if(a!=="change-provider")return a}}async resolveKey(e,n,i,r,o){let s=await this.firstKey(n,r);for(;;){let a=await this.validateKey(n,s);if(a==="valid")return o.set(n,s),{capability:e,provider:n,model:i};let u=await this.pickAfterFailure(e,a);if(u==="save")return o.set(n,s),{capability:e,provider:n,model:i};if(u==="skip")return qe.info(`skipped ${e} (optional).`),null;if(u==="change")return"change-provider";s=await this.promptPassword(n)}}async pickProvider(e,n,i){let r=i.routes?.[e]?.provider;return this.ensure(await co({message:`${e} provider`,options:n.map(o=>({value:o,label:o})),initialValue:r&&n.includes(r)?r:void 0}))}async pickModel(e,n,i){let r=i.routes?.[e],o=r?.provider===n?r.model:this.probe.defaultModel(n,e)??"";return this.ensure(await Fk({message:`${e} model`,initialValue:o,validate:s=>s?.trim()?void 0:"a model is required"}))}async firstKey(e,n){let i=n.secrets?.[e];return i&&this.ensure(await wu({message:`Reuse the saved key for ${e}?`,initialValue:!0}))?i.trim():this.promptPassword(e)}async promptPassword(e){return this.ensure(await jk({message:`${e} API key`,validate:i=>i?.trim()?void 0:"a key is required"})).trim()}async validateKey(e,n){let i=Mk();i.start(`validating ${e} key...`);let r=await this.probe.probe(e,n),o=r.detail?` (${r.detail})`:"";return r.ok?i.stop(N.ok(`${e} key valid`)):r.status==="invalid"?i.stop(N.fail(`${e} key rejected${o}`)):r.status==="unverifiable"?i.stop(N.warn(`could not verify ${e} here${o}`)):i.stop(N.warn(`could not validate ${e}${o}`)),r.status}async pickAfterFailure(e,n){let i=Gk(e,n);return this.ensure(await co({message:`${e}: how do you want to proceed?`,options:i.map(r=>({value:r,label:Hk[r].label,hint:Hk[r].hint}))}))}review(e,n,i,r){let o=[];if(e.length===0)o.push("routes: none");else for(let s of e){let a=n.has(s.provider)?N.ok("key set"):N.warn("no key");o.push(`${s.capability}: ${s.provider}/${s.model} (${a})`)}o.push(`defaults: modality=${i}, logLevel=${r}`),wg(o.join(`
346
346
  `),"review (secrets redacted)")}printHeadlessGuidance(){this.io.err(["jarvis init needs an interactive terminal.","","On a headless or non-interactive host:"," - run `jarvis init` over an interactive SSH session, or"," - set secrets and defaults non-interactively, e.g.:"," jarvis config set secrets.anthropic <key>"," jarvis config set defaults.modality text"," - relocate the home with the JARVIS_HOME env var if needed.","","Note: configuring a provider route (provider + model together) is interactive","in v0.1 - use `jarvis init` for that. Verify any setup with: jarvis doctor"].join(`
347
347
  `)+`
348
- `)}ensure(e){if(_u(e))throw new lo;return e}};ki();import{randomUUID as i4}from"node:crypto";var kg=class{constructor(e,n,i=ue){this.session=e;this.reader=n;this.io=i}session;reader;io;prompt="you ";labelShown=!1;async run(){try{for await(let e of this.session.events())if(!await this.handle(e))break}finally{this.reader.close(),await this.session.close()}}async handle(e){switch(e.type){case"session.ready":return this.greet(),this.promptAndSend();case"turn.accepted":return this.labelShown=!1,!0;case"state":return e.state==="responding"&&this.showLabel(),!0;case"response.delta":return this.showLabel(),this.io.out(e.text),!0;case"response.done":return this.labelShown&&this.io.out(`
348
+ `)}ensure(e){if(_u(e))throw new lo;return e}};ki();import{randomUUID as o4}from"node:crypto";var kg=class{constructor(e,n,i=ue){this.session=e;this.reader=n;this.io=i}session;reader;io;prompt="you ";labelShown=!1;async run(){try{for await(let e of this.session.events())if(!await this.handle(e))break}finally{this.reader.close(),await this.session.close()}}async handle(e){switch(e.type){case"session.ready":return this.greet(),this.promptAndSend();case"turn.accepted":return this.labelShown=!1,!0;case"state":return e.state==="responding"&&this.showLabel(),!0;case"response.delta":return this.showLabel(),this.io.out(e.text),!0;case"response.done":return this.labelShown&&this.io.out(`
349
349
  `),this.promptAndSend();case"error":return this.labelShown&&this.io.out(`
350
- `),this.renderError(e),this.promptAndSend();default:return!0}}async promptAndSend(){for(;;){let e=await this.reader.next(this.prompt);if(e===null)return!1;let n=e.trim();if(n.length!==0)try{return await this.session.send({type:"input.text",sessionId:this.session.sessionId,commandId:i4(),atMs:Date.now(),text:n}),!0}catch(i){if(i instanceof Le){if(i.reason==="closed")return!1;this.renderSendError(i);continue}throw i}}}greet(){this.io.out(N.dim("jarvis is ready. type a message, or press ctrl-c to exit.")+`
350
+ `),this.renderError(e),this.promptAndSend();default:return!0}}async promptAndSend(){for(;;){let e=await this.reader.next(this.prompt);if(e===null)return!1;let n=e.trim();if(n.length!==0)try{return await this.session.send({type:"input.text",sessionId:this.session.sessionId,commandId:o4(),atMs:Date.now(),text:n}),!0}catch(i){if(i instanceof Le){if(i.reason==="closed")return!1;this.renderSendError(i);continue}throw i}}}greet(){this.io.out(N.dim("jarvis is ready. type a message, or press ctrl-c to exit.")+`
351
351
  `)}showLabel(){this.labelShown||(this.io.out(N.dim("jarvis")+" "),this.labelShown=!0)}renderError(e){if(e.reason==="no_text_route"){this.io.out(N.warn("no brain configured yet - run `jarvis init` to add one.")+`
352
352
  `);return}this.io.out(N.fail(`something went wrong - ${e.message}`)+`
353
353
  `)}renderSendError(e){this.io.out(N.warn(`could not send that (${e.reason}) - ${e.message}`)+`
354
354
  `)}};async function Jk(t){if(!t.stdin.isTTY)return t.io.err(N.dim("jarvis is interactive - run it in a terminal.")+`
355
355
  `),1;let e;try{e=await t.openSession()}catch{return t.io.err(N.fail("could not start jarvis - your config may be invalid. run `jarvis doctor`.")+`
356
- `),1}let n=t.createReader();return await new kg(e,n,t.io).run(),0}import{createInterface as o4}from"node:readline";var ku=class{rl;closed=!1;pending=null;constructor(e,n){this.rl=o4({input:e,output:n}),this.rl.on("line",i=>this.settle(i)),this.rl.on("close",()=>{this.closed=!0,this.settle(null)}),this.rl.on("SIGINT",()=>this.close())}next(e){return this.closed?Promise.resolve(null):new Promise(n=>{this.pending=n,this.rl.setPrompt(e),this.rl.prompt()})}close(){this.closed||(this.closed=!0,this.rl.close())}settle(e){let n=this.pending;this.pending=null,n?.(e)}};var Dn=class extends Error{constructor(e){super(e),this.name="AudioUnavailableError"}};function Kk(t){let e=t.routes?.stt,n=t.routes?.tts;return!e||!n?!1:!!t.secrets?.[e.provider]&&!!t.secrets?.[n.provider]}async function Yk(t){if(!t.stdin.isTTY)return t.io.err(N.dim("jarvis is interactive - run it in a terminal.")+`
356
+ `),1}let n=t.createReader();return await new kg(e,n,t.io).run(),0}import{createInterface as s4}from"node:readline";var ku=class{rl;closed=!1;pending=null;constructor(e,n){this.rl=s4({input:e,output:n}),this.rl.on("line",i=>this.settle(i)),this.rl.on("close",()=>{this.closed=!0,this.settle(null)}),this.rl.on("SIGINT",()=>this.close())}next(e){return this.closed?Promise.resolve(null):new Promise(n=>{this.pending=n,this.rl.setPrompt(e),this.rl.prompt()})}close(){this.closed||(this.closed=!0,this.rl.close())}settle(e){let n=this.pending;this.pending=null,n?.(e)}};var Dn=class extends Error{constructor(e){super(e),this.name="AudioUnavailableError"}};function Kk(t){let e=t.routes?.stt,n=t.routes?.tts;return!e||!n?!1:!!t.secrets?.[e.provider]&&!!t.secrets?.[n.provider]}async function Yk(t){if(!t.stdin.isTTY)return t.io.err(N.dim("jarvis is interactive - run it in a terminal.")+`
357
357
  `),1;if(t.textOnly||!t.voiceConfigured)return t.runText();if(!await t.micAvailable())return t.io.err(N.warn("no microphone detected - check it is plugged in and mic access / privacy is enabled. starting in text mode.")+`
358
358
  `),t.runText();let e;try{e=await t.openVoiceSession()}catch{return t.io.err(N.fail("could not start jarvis - your config may be invalid. run `jarvis doctor`.")+`
359
359
  `),1}try{return await t.runVoice(e),0}catch(n){if(n instanceof Dn)return t.io.err(N.warn("could not start the microphone - check mic access / privacy. starting in text mode.")+`
360
- `),t.runText();throw n}}import{randomUUID as Og}from"node:crypto";function Eg({onlyFirst:t=!1}={}){let r="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(r,t?void 0:"g")}var s4=Eg();function Ig(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return!t.includes("\x1B")&&!t.includes("\x9B")?t:t.replace(s4,"")}var Xk=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Qk=12288,eE=65510,tE=[12288,12288,65281,65376,65504,65510];var rE=4352,nE=262141,Tg=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Eu=(t,e)=>{let n=0,i=Math.floor(t.length/2)-1;for(;n<=i;){let r=Math.floor((n+i)/2),o=r*2;if(e<t[o])i=r-1;else if(e>t[o+1])n=r+1;else return!0}return!1};var iE=19968,[c4,l4]=d4(Tg);function d4(t){let e=t[0],n=t[1];for(let i=0;i<t.length;i+=2){let r=t[i],o=t[i+1];if(iE>=r&&iE<=o)return[r,o];o-r>n-e&&(e=r,n=o)}return[e,n]}var oE=t=>t<161||t>1114109?!1:Eu(Xk,t),sE=t=>t<Qk||t>eE?!1:Eu(tE,t);var aE=t=>t>=c4&&t<=l4?!0:t<rE||t>nE?!1:Eu(Tg,t);function f4(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function fo(t,{ambiguousAsWide:e=!1}={}){return f4(t),sE(t)||aE(t)||e&&oE(t)?2:1}var h4=new Intl.Segmenter,uE=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,p4=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,m4=/^\p{RGI_Emoji}$/v,g4=/^[\d#*]\u20E3$/,v4=/\p{Extended_Pictographic}/gu;function y4(t){if(t.length>50)return!1;if(g4.test(t))return!0;if(t.includes("\u200D")){let e=t.match(v4);return e!==null&&e.length>=2}return!1}function _4(t){return t.replace(p4,"")}function b4(t){return uE.test(t)}function cE(t){return t>=4352&&t<=4447||t>=43360&&t<=43388}function lE(t){return t>=4448&&t<=4519||t>=55216&&t<=55238}function dE(t){return t>=4520&&t<=4607||t>=55243&&t<=55291}function $4(t){return cE(t)||lE(t)||dE(t)}function x4(t,e){let n=[];for(let r of t)uE.test(r)||n.push(r.codePointAt(0));if(n.length===0)return;let i=0;for(let r=0;r<n.length;r++){let o=n[r];if(!$4(o)){if(i===0)return;for(let s=r;s<n.length;s++)i+=fo(n[s],e);return i}if(cE(o)&&lE(n[r+1])){i+=2,r+=dE(n[r+2])?2:1;continue}i+=fo(o,e)}return i}function w4(t,e){let n=0,i=!0;for(let r of t){if(i){i=!1;continue}r>="\uFF00"&&r<="\uFFEF"&&(n+=fo(r.codePointAt(0),e))}return n}function Iu(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:i=!1}=e,r=t;if(!i&&(r.includes("\x1B")||r.includes("\x9B"))&&(r=Ig(r)),r.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(r))return r.length;let o=0,s={ambiguousAsWide:!n};for(let{segment:a}of h4.segment(r)){if(b4(a))continue;if(m4.test(a)||y4(a)){o+=2;continue}let u=_4(a),c=x4(u,s);if(c!==void 0){o+=c;continue}let l=u.codePointAt(0);o+=fo(l,s),o+=w4(u,s)}return o}ki();Ae();function Ag(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}var ho="\x1B[2K\r",S4=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Tu=class{session;capture;playback;io;terminalWidth;ptt;halfDuplex;signal;phase="listening";labelShown=!1;partialShown=!1;statusShown=!1;listenEpoch=0;asideActive=!1;turnStats={};talking;currentTurnId;cleanedUp=!1;onAbort=()=>{this.session.close()};constructor(e){this.session=e.session,this.capture=e.capture,this.playback=e.playback,this.io=e.io??ue,this.terminalWidth=e.terminalWidth??(()=>process.stdout.columns),this.ptt=e.pushToTalk,this.halfDuplex=e.options?.halfDuplex??!1,this.signal=e.signal,this.talking=this.ptt===void 0}async run(){if(this.signal){if(this.signal.aborted){await this.cleanup();return}this.signal.addEventListener("abort",this.onAbort,{once:!0})}try{await this.capture.start({onFrame:(e,n)=>this.handleFrame(e,n),onSpeechStart:()=>this.handleSpeechStart(),onError:e=>this.handleCaptureError(e)})}catch(e){throw await this.cleanup(),new Dn(e instanceof Error?e.message:String(e))}this.ptt?.listen({onStart:()=>{this.talking=!0},onEnd:()=>this.commitPushToTalkTurn()});try{for await(let e of this.session.events())this.handle(e)}finally{await this.cleanup()}}handleFrame(e,n){this.phase==="listening"&&this.talking&&this.sendFrame(e,n)}async sendFrame(e,n){try{await this.session.send({type:"input.audio.frame",sessionId:this.session.sessionId,commandId:Og(),atMs:n,audio:e})}catch(i){if(i instanceof Le&&i.reason==="closed"){this.capture.stop();return}B.debug("dropped an audio frame",{error:i})}}handleSpeechStart(){if(this.phase!=="responding"||this.halfDuplex||this.ptt)return;let e=this.currentTurnId;this.playback.flush(),this.closeOpenLine(),this.toListening(),this.cancelTurn(e,"barge_in")}async cancelTurn(e,n){try{await this.session.send({type:"turn.cancel",sessionId:this.session.sessionId,commandId:Og(),atMs:Date.now(),reason:n,...e!==void 0&&{turnId:e}})}catch{}}commitPushToTalkTurn(){this.talking=!1,this.endAudioInput()}async endAudioInput(){try{await this.session.send({type:"input.audio.end",sessionId:this.session.sessionId,commandId:Og(),atMs:Date.now()})}catch{}}handleCaptureError(e){this.cleanedUp||(this.closeOpenLine(),this.io.out(N.fail(`the microphone stopped - ${e.message}`)+`
360
+ `),t.runText();throw n}}import{randomUUID as Og}from"node:crypto";function Eg({onlyFirst:t=!1}={}){let r="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(r,t?void 0:"g")}var a4=Eg();function Ig(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return!t.includes("\x1B")&&!t.includes("\x9B")?t:t.replace(a4,"")}var Xk=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Qk=12288,eE=65510,tE=[12288,12288,65281,65376,65504,65510];var rE=4352,nE=262141,Tg=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Eu=(t,e)=>{let n=0,i=Math.floor(t.length/2)-1;for(;n<=i;){let r=Math.floor((n+i)/2),o=r*2;if(e<t[o])i=r-1;else if(e>t[o+1])n=r+1;else return!0}return!1};var iE=19968,[l4,d4]=f4(Tg);function f4(t){let e=t[0],n=t[1];for(let i=0;i<t.length;i+=2){let r=t[i],o=t[i+1];if(iE>=r&&iE<=o)return[r,o];o-r>n-e&&(e=r,n=o)}return[e,n]}var oE=t=>t<161||t>1114109?!1:Eu(Xk,t),sE=t=>t<Qk||t>eE?!1:Eu(tE,t);var aE=t=>t>=l4&&t<=d4?!0:t<rE||t>nE?!1:Eu(Tg,t);function h4(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function fo(t,{ambiguousAsWide:e=!1}={}){return h4(t),sE(t)||aE(t)||e&&oE(t)?2:1}var p4=new Intl.Segmenter,uE=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,m4=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,g4=/^\p{RGI_Emoji}$/v,v4=/^[\d#*]\u20E3$/,y4=/\p{Extended_Pictographic}/gu;function _4(t){if(t.length>50)return!1;if(v4.test(t))return!0;if(t.includes("\u200D")){let e=t.match(y4);return e!==null&&e.length>=2}return!1}function b4(t){return t.replace(m4,"")}function $4(t){return uE.test(t)}function cE(t){return t>=4352&&t<=4447||t>=43360&&t<=43388}function lE(t){return t>=4448&&t<=4519||t>=55216&&t<=55238}function dE(t){return t>=4520&&t<=4607||t>=55243&&t<=55291}function x4(t){return cE(t)||lE(t)||dE(t)}function w4(t,e){let n=[];for(let r of t)uE.test(r)||n.push(r.codePointAt(0));if(n.length===0)return;let i=0;for(let r=0;r<n.length;r++){let o=n[r];if(!x4(o)){if(i===0)return;for(let s=r;s<n.length;s++)i+=fo(n[s],e);return i}if(cE(o)&&lE(n[r+1])){i+=2,r+=dE(n[r+2])?2:1;continue}i+=fo(o,e)}return i}function S4(t,e){let n=0,i=!0;for(let r of t){if(i){i=!1;continue}r>="\uFF00"&&r<="\uFFEF"&&(n+=fo(r.codePointAt(0),e))}return n}function Iu(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:i=!1}=e,r=t;if(!i&&(r.includes("\x1B")||r.includes("\x9B"))&&(r=Ig(r)),r.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(r))return r.length;let o=0,s={ambiguousAsWide:!n};for(let{segment:a}of p4.segment(r)){if($4(a))continue;if(g4.test(a)||_4(a)){o+=2;continue}let u=b4(a),c=w4(u,s);if(c!==void 0){o+=c;continue}let l=u.codePointAt(0);o+=fo(l,s),o+=S4(u,s)}return o}ki();Ae();function Ag(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}var ho="\x1B[2K\r",k4=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Tu=class{session;capture;playback;io;terminalWidth;ptt;halfDuplex;signal;phase="listening";labelShown=!1;partialShown=!1;statusShown=!1;listenEpoch=0;asideActive=!1;turnStats={};talking;currentTurnId;cleanedUp=!1;onAbort=()=>{this.session.close()};constructor(e){this.session=e.session,this.capture=e.capture,this.playback=e.playback,this.io=e.io??ue,this.terminalWidth=e.terminalWidth??(()=>process.stdout.columns),this.ptt=e.pushToTalk,this.halfDuplex=e.options?.halfDuplex??!1,this.signal=e.signal,this.talking=this.ptt===void 0}async run(){if(this.signal){if(this.signal.aborted){await this.cleanup();return}this.signal.addEventListener("abort",this.onAbort,{once:!0})}try{await this.capture.start({onFrame:(e,n)=>this.handleFrame(e,n),onSpeechStart:()=>this.handleSpeechStart(),onError:e=>this.handleCaptureError(e)})}catch(e){throw await this.cleanup(),new Dn(e instanceof Error?e.message:String(e))}this.ptt?.listen({onStart:()=>{this.talking=!0},onEnd:()=>this.commitPushToTalkTurn()});try{for await(let e of this.session.events())this.handle(e)}finally{await this.cleanup()}}handleFrame(e,n){this.phase==="listening"&&this.talking&&this.sendFrame(e,n)}async sendFrame(e,n){try{await this.session.send({type:"input.audio.frame",sessionId:this.session.sessionId,commandId:Og(),atMs:n,audio:e})}catch(i){if(i instanceof Le&&i.reason==="closed"){this.capture.stop();return}B.debug("dropped an audio frame",{error:i})}}handleSpeechStart(){if(this.phase!=="responding"||this.halfDuplex||this.ptt)return;let e=this.currentTurnId;this.playback.flush(),this.closeOpenLine(),this.toListening(),this.cancelTurn(e,"barge_in")}async cancelTurn(e,n){try{await this.session.send({type:"turn.cancel",sessionId:this.session.sessionId,commandId:Og(),atMs:Date.now(),reason:n,...e!==void 0&&{turnId:e}})}catch{}}commitPushToTalkTurn(){this.talking=!1,this.endAudioInput()}async endAudioInput(){try{await this.session.send({type:"input.audio.end",sessionId:this.session.sessionId,commandId:Og(),atMs:Date.now()})}catch{}}handleCaptureError(e){this.cleanedUp||(this.closeOpenLine(),this.io.out(N.fail(`the microphone stopped - ${e.message}`)+`
361
361
  `),this.session.close())}handle(e){switch(e.type){case"session.ready":this.greet();return;case"turn.accepted":this.currentTurnId=e.turnId,this.labelShown=!1,this.turnStats={};return;case"transcript.partial":if(e.turnId!==this.currentTurnId)return;this.renderPartial(e.text);return;case"turn.final":if(e.turn.turnId!==this.currentTurnId)return;if(e.turn.disposition==="absorbed"){this.renderAside(e.turn),this.toListening();return}this.renderFinalUser(e.turn),this.turnStats.finalAtMs=e.atMs,this.renderStatus("thinking");return;case"state":e.state==="responding"&&(this.phase="responding",this.asideActive=!1),e.state==="aside"&&(this.asideActive=!0,this.phase==="listening"&&this.renderStatus("listening"));return;case"response.delta":if(this.phase!=="responding")return;this.turnStats.firstTokenAtMs??=e.atMs,this.showLabel(),this.io.out(e.text);return;case"response.audio":if(this.phase!=="responding")return;this.turnStats.firstAudioAtMs===void 0&&(this.turnStats.firstAudioAtMs=e.atMs,this.turnStats.playbackStartAtMs=Date.now(),this.labelShown||this.renderStatus("speaking")),this.playback.play(e.audio);return;case"response.done":if(this.phase!=="responding")return;this.closeOpenLine(),this.turnStats.playbackStartAtMs!==void 0&&this.renderStatus("speaking"),this.awaitPlaybackDrain();return;case"error":{let n=this.currentTurnId;this.playback.flush(),this.closeOpenLine(),this.renderError(e),this.toListening(),this.cancelTurn(n,"user_cancel");return}default:return}}greet(){let e=this.ptt?"jarvis is ready (push-to-talk). press space to talk, again to send.":"jarvis is listening. just speak.",n=this.halfDuplex?" half-duplex: barge-in is off.":"";this.io.out(N.dim(`${e}${n} press ctrl-c to exit.`)+`
362
- `),this.renderStatus("listening")}renderPartial(e){this.io.out(`${ho}you ${N.dim(this.clampPartialToOneRow(e))}`),this.partialShown=!0,this.statusShown=!1}clampPartialToOneRow(e){let n=this.visibleColumns()-5;if(Iu(e)<=n)return e;let i=n-3;if(i<=0)return"...";let r=[...S4.segment(e)],o=r.length,s=0;for(;o>0;){let a=s+Iu(r[o-1].segment);if(a>i)break;s=a,o-=1}return o<r.length?"..."+e.slice(r[o].index):"..."}renderFinalUser(e){this.io.out(`${ho}you ${e.text}
362
+ `),this.renderStatus("listening")}renderPartial(e){this.io.out(`${ho}you ${N.dim(this.clampPartialToOneRow(e))}`),this.partialShown=!0,this.statusShown=!1}clampPartialToOneRow(e){let n=this.visibleColumns()-5;if(Iu(e)<=n)return e;let i=n-3;if(i<=0)return"...";let r=[...k4.segment(e)],o=r.length,s=0;for(;o>0;){let a=s+Iu(r[o-1].segment);if(a>i)break;s=a,o-=1}return o<r.length?"..."+e.slice(r[o].index):"..."}renderFinalUser(e){this.io.out(`${ho}you ${e.text}
363
363
  `),this.partialShown=!1,this.statusShown=!1}renderAside(e){this.io.out(`${ho}${N.dim(`you (aside) ${e.text}`)}
364
364
  `),this.partialShown=!1,this.statusShown=!1}showLabel(){this.labelShown||(this.eraseStatusLine(),this.io.out(N.dim("jarvis")+" "),this.labelShown=!0)}renderStatus(e){this.partialShown||this.labelShown||(this.io.out(ho+N.dim(this.statusText(e))),this.statusShown=!0)}statusText(e){if(e!=="listening"||!this.asideActive)return`${e}...`;let n=this.ptt?"listening (aside - press to talk to resume)":'listening (aside - say "Jarvis" to resume)',i=this.visibleColumns();if(n.length<=i)return n;let r="listening (aside)";return r.length<=i?r:`${e}...`}visibleColumns(){let e=this.terminalWidth();return e!==void 0&&e>0?e:80}eraseStatusLine(){this.statusShown&&(this.io.out(ho),this.statusShown=!1)}renderError(e){if(e.reason==="no_voice_route"){this.io.out(N.warn("no voice configured yet - run `jarvis init` to add speech routes.")+`
365
365
  `);return}if(e.reason==="no_text_route"){this.io.out(N.warn("no brain configured yet - run `jarvis init` to add one.")+`
366
366
  `);return}this.io.out(N.fail(`something went wrong - ${e.message}`)+`
367
367
  `)}closeOpenLine(){if(this.labelShown||this.partialShown){this.io.out(`
368
368
  `),this.labelShown=!1,this.partialShown=!1;return}this.eraseStatusLine()}awaitPlaybackDrain(){let e=this.listenEpoch;this.playback.drained().then(()=>{this.cleanedUp||e!==this.listenEpoch||(this.printTurnSummary(),this.toListening())})}printTurnSummary(){if(B.getLevel()!=="debug")return;let{finalAtMs:e,firstTokenAtMs:n,firstAudioAtMs:i,playbackStartAtMs:r}=this.turnStats,o=[];e!==void 0&&n!==void 0&&o.push(`commit->token ${Ag(n-e)}`),n!==void 0&&i!==void 0&&o.push(`token->audio ${Ag(i-n)}`),r!==void 0&&o.push(`spoke ${Ag(Date.now()-r)}`),o.length!==0&&(this.eraseStatusLine(),this.io.out(N.dim(`turn ${o.join(", ")}`)+`
369
- `))}toListening(){this.listenEpoch++,this.phase="listening",this.labelShown=!1,this.partialShown=!1,this.currentTurnId=void 0,this.renderStatus("listening")}async cleanup(){this.cleanedUp||(this.cleanedUp=!0,this.closeOpenLine(),this.signal?.removeEventListener("abort",this.onAbort),this.ptt?.close(),await this.capture.stop().catch(()=>{}),await this.playback.close().catch(()=>{}),await this.session.close().catch(()=>{}))}};import{emitKeypressEvents as k4}from"node:readline";var Ou=class{constructor(e,n,i=E4){this.input=e;this.onQuit=n;this.prepare=i}input;onQuit;prepare;handlers=null;talking=!1;listening=!1;onKeypress=(e,n)=>{if(n.ctrl&&n.name==="c"){this.onQuit();return}n.name==="space"&&this.toggle()};listen(e){this.listening||(this.listening=!0,this.handlers=e,this.prepare(this.input),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!0),this.input.resume?.(),this.input.on("keypress",this.onKeypress))}close(){this.listening&&(this.listening=!1,this.input.removeListener("keypress",this.onKeypress),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!1),this.input.pause?.(),this.handlers=null)}toggle(){this.talking=!this.talking,this.talking?this.handlers?.onStart():this.handlers?.onEnd()}};function E4(t){k4(t)}var M4={start:"starting...",stop:"stopping...",restart:"restarting...",devices:"listing devices..."};function F4(){try{let t=U4(new URL("../package.json",import.meta.url),"utf8"),e=JSON.parse(t);return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}function V4(t,e){let n=new du(t),i=n.notice();i!==null&&ue.err(`${i}
370
- `),n.isStale(Date.now())&&n.refreshInBackground();let r=!1,o=!1;try{let c=new Ge().resolved();r=Kk(c),o=c.defaults.modality==="text"}catch{}let s=j4(),a=c=>(B.debug("opening interactive session",{project:e.project,capabilities:c}),Dm().openSession({deviceId:s,projectId:e.project,clientCapabilities:c})),u=()=>Jk({stdin:process.stdin,io:ue,openSession:()=>a(["text"]),createReader:()=>new ku(process.stdin,process.stdout)});return Yk({stdin:process.stdin,io:ue,textOnly:e.textOnly||o,voiceConfigured:r,micAvailable:B4,openVoiceSession:()=>a(["text","audio-in","audio-out"]),runVoice:c=>Z4(c,e),runText:u})}async function Z4(t,e){let{DecibriCapture:n,DecibriPlayback:i}=await Promise.resolve().then(()=>(Rg(),zg)),r=new AbortController,o=e.ptt?new Ou(process.stdin,()=>r.abort()):void 0,s=()=>r.abort();process.once("SIGINT",s);try{await new Tu({session:t,capture:new n,playback:new i,io:ue,...o&&{pushToTalk:o},options:{halfDuplex:e.halfDuplex},signal:r.signal}).run()}finally{process.removeListener("SIGINT",s)}}async function B4(){try{let{hasInputDevice:t}=await Promise.resolve().then(()=>(Rg(),zg));return t()}catch(t){return B.debug("audio module unavailable; treating as no microphone",{error:t}),!1}}function G4(t){return{activate:e=>V4(t,e),status:()=>new Tr(t).status(),upgrade:()=>new Tr(t).upgrade(),init:()=>new Su({config:new Ge,probe:new Pn}).run(),doctor:()=>new fu({config:new Ge,probe:new Pn,version:t}).run(),configList:()=>new Ar(new Ge).list(),configGet:e=>new Ar(new Ge).get(e),configSet:(e,n)=>new Ar(new Ge).set(e,n),configUnset:e=>new Ar(new Ge).unset(e),stub:e=>(ue.err(`${M4[e]??`${e}: not implemented yet`}
371
- `),0)}}try{let t=F4();process.exitCode=await aS(process.argv.slice(2),t,G4(t))}catch(t){B.error("jarvis failed",{error:t}),process.exitCode=1}
369
+ `))}toListening(){this.listenEpoch++,this.phase="listening",this.labelShown=!1,this.partialShown=!1,this.currentTurnId=void 0,this.renderStatus("listening")}async cleanup(){this.cleanedUp||(this.cleanedUp=!0,this.closeOpenLine(),this.signal?.removeEventListener("abort",this.onAbort),this.ptt?.close(),await this.capture.stop().catch(()=>{}),await this.playback.close().catch(()=>{}),await this.session.close().catch(()=>{}))}};import{emitKeypressEvents as E4}from"node:readline";var Ou=class{constructor(e,n,i=I4){this.input=e;this.onQuit=n;this.prepare=i}input;onQuit;prepare;handlers=null;talking=!1;listening=!1;onKeypress=(e,n)=>{if(n.ctrl&&n.name==="c"){this.onQuit();return}n.name==="space"&&this.toggle()};listen(e){this.listening||(this.listening=!0,this.handlers=e,this.prepare(this.input),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!0),this.input.resume?.(),this.input.on("keypress",this.onKeypress))}close(){this.listening&&(this.listening=!1,this.input.removeListener("keypress",this.onKeypress),this.input.isTTY&&this.input.setRawMode&&this.input.setRawMode(!1),this.input.pause?.(),this.handlers=null)}toggle(){this.talking=!this.talking,this.talking?this.handlers?.onStart():this.handlers?.onEnd()}};function I4(t){E4(t)}var F4={start:"starting...",stop:"stopping...",restart:"restarting...",devices:"listing devices..."};function V4(){try{let t=j4(new URL("../package.json",import.meta.url),"utf8"),e=JSON.parse(t);return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}function Z4(t,e){let n=new du(t),i=n.notice();i!==null&&ue.err(`${i}
370
+ `),n.isStale(Date.now())&&n.refreshInBackground();let r=!1,o=!1;try{let c=new Ge().resolved();r=Kk(c),o=c.defaults.modality==="text"}catch{}let s=M4(),a=c=>(B.debug("opening interactive session",{project:e.project,capabilities:c}),Dm().openSession({deviceId:s,projectId:e.project,clientCapabilities:c})),u=()=>Jk({stdin:process.stdin,io:ue,openSession:()=>a(["text"]),createReader:()=>new ku(process.stdin,process.stdout)});return Yk({stdin:process.stdin,io:ue,textOnly:e.textOnly||o,voiceConfigured:r,micAvailable:G4,openVoiceSession:()=>a(["text","audio-in","audio-out"]),runVoice:c=>B4(c,e),runText:u})}async function B4(t,e){let{DecibriCapture:n,DecibriPlayback:i}=await Promise.resolve().then(()=>(Rg(),zg)),r=new AbortController,o=e.ptt?new Ou(process.stdin,()=>r.abort()):void 0,s=()=>r.abort();process.once("SIGINT",s);try{await new Tu({session:t,capture:new n,playback:new i,io:ue,...o&&{pushToTalk:o},options:{halfDuplex:e.halfDuplex},signal:r.signal}).run()}finally{process.removeListener("SIGINT",s)}}async function G4(){try{let{hasInputDevice:t}=await Promise.resolve().then(()=>(Rg(),zg));return t()}catch(t){return B.debug("audio module unavailable; treating as no microphone",{error:t}),!1}}function W4(t){return{activate:e=>Z4(t,e),status:()=>new Tr(t).status(),upgrade:()=>new Tr(t).upgrade(),init:()=>new Su({config:new Ge,probe:new Pn}).run(),doctor:()=>new fu({config:new Ge,probe:new Pn,version:t}).run(),configList:()=>new Ar(new Ge).list(),configGet:e=>new Ar(new Ge).get(e),configSet:(e,n)=>new Ar(new Ge).set(e,n),configUnset:e=>new Ar(new Ge).unset(e),stub:e=>(ue.err(`${F4[e]??`${e}: not implemented yet`}
371
+ `),0)}}try{let t=V4();process.exitCode=await aS(process.argv.slice(2),t,W4(t))}catch(t){B.error("jarvis failed",{error:t}),process.exitCode=1}