@neuvybe/jarvis 0.14.2 → 0.14.3

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 +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -74,7 +74,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
74
74
  `,{mode:384}),AE(r,384)}};function j_(t){switch(t){case"debug":case"info":case"warn":case"error":return t;default:return}}He();var DE="<set>",jE=new Set(["upgrade.auto"]),UE=new Set(["version"]),LE=new Set(["__proto__","prototype","constructor"]),Ze=class{home;constructor(e=Ke){this.home=e}freshResolver(){return new dr(this.home)}resolved(){return this.freshResolver().resolved()}list(){return this.redact(this.freshResolver().resolved())}get(e){return ME(this.list(),this.parsePath(e))}set(e,n){let i=this.parsePath(e);this.assertMutable(e);let r=this.freshResolver(),o=structuredClone(r.resolved());FE(o,i,this.coerce(e,n)),r.save(this.validate(o,e))}unset(e){let n=this.parsePath(e);this.assertMutable(e);let i=this.freshResolver(),r=structuredClone(i.resolved());if(!VE(r,n))throw new Error(`nothing to unset: '${e}' is not set`);i.save(this.validate(r,e))}write(e){dr.persist(this.home,e)}validate(e,n){let i=lr.safeParse(e);if(i.success)return i.data;let r=i.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join("; "),o=n.startsWith("routes.")?" A route needs both a provider and a model - run 'jarvis init' to configure one.":"";throw new Error(`'${n}' would make the config invalid (${r}).${o}`)}coerce(e,n){if(jE.has(e)){if(n==="true")return!0;if(n==="false")return!1;throw new Error(`'${e}' expects 'true' or 'false', got '${n}'`)}return n}assertMutable(e){if(UE.has(e))throw new Error(`'${e}' is managed by Jarvis and cannot be changed`)}parsePath(e){let n=e.split(".");if(e.length===0||n.some(i=>i.length===0||LE.has(i)))throw new Error(`invalid config path: '${e}'`);return n}redact(e){let n=structuredClone(e);if(n.secrets)for(let i of Object.keys(n.secrets))n.secrets[i]=DE;return n}};function ME(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")return;n=n[i]}return n}function FE(t,e,n){let i=t;for(let r=0;r<e.length-1;r++){let o=e[r],s=i[o];(s===null||typeof s!="object")&&(i[o]={}),i=i[o]}i[e[e.length-1]]=n}function VE(t,e){let n=t;for(let r=0;r<e.length-1;r++){let o=n[e[r]];if(o===null||typeof o!="object")return!1;n=o}let i=e[e.length-1];return i in n?(delete n[i],!0):!1}var Fs=class extends Error{constructor(e){super(`text stream idle for ${e}ms`),this.name="IdleTimeoutError"}};async function*L_(t,e={}){let{signal:n,idleTimeoutMs:i}=e,r=t.getReader(),o=new TextDecoder,s="",a=[];try{for(;;){let{value:u,done:c}=await ZE(r,n,i);if(c)break;s+=o.decode(u,{stream:!0});let l;for(;(l=s.indexOf(`
75
75
  `))!==-1;){let d=s.slice(0,l);if(s=s.slice(l+1),d.endsWith("\r")&&(d=d.slice(0,-1)),d===""){a.length>0&&(yield a.join(`
76
76
  `),a=[]);continue}if(d.startsWith(":"))continue;let f=d.indexOf(":");if((f===-1?d:d.slice(0,f))!=="data")continue;let m=f===-1?"":d.slice(f+1);m.startsWith(" ")&&(m=m.slice(1)),a.push(m)}}}finally{r.cancel().catch(()=>{})}}function ZE(t,e,n){return e?.aborted?Promise.reject(U_(e)):new Promise((i,r)=>{let o=!1,s=c=>{o||(o=!0,u!==void 0&&clearTimeout(u),e?.removeEventListener("abort",a),c())},a=()=>s(()=>r(U_(e))),u=n!==void 0?setTimeout(()=>s(()=>r(new Fs(n))),n):void 0;e?.addEventListener("abort",a,{once:!0}),t.read().then(c=>s(()=>i(c)),c=>s(()=>r(BE(c))))})}function U_(t){let e=t?.reason;return e instanceof Error?e:new Error("text stream aborted")}function BE(t){return t instanceof Error?t:new Error(String(t))}var Zt=class extends Error{status;constructor(e,n){super(e),this.status=n,this.name="TextAdapterError"}};var Zs=3e4,GE=4096,WE="https://api.anthropic.com/v1/messages",qE="2023-06-01",JE="https://api.openai.com/v1/chat/completions",Vs=class{key;fetchImpl;idleTimeoutMs;constructor(e,n=fetch,i=Zs){this.key=e,this.fetchImpl=n,this.idleTimeoutMs=i}async*stream(e){let{url:n,init:i}=this.buildRequest(e),r=await this.fetchImpl(n,{...i,signal:e.signal});if(!r.ok)throw new Zt(`text provider request failed (HTTP ${r.status})`,r.status);if(!r.body)throw new Zt("text provider response had no body");for await(let o of L_(r.body,{signal:e.signal,idleTimeoutMs:this.idleTimeoutMs})){if(this.isDone(o))return;let s=this.decode(o);s&&(yield s)}}},pi=class extends Vs{buildRequest(e){let n={model:e.model,max_tokens:GE,stream:!0,messages:e.messages.map(i=>({role:i.role,content:i.content})),...e.system!==void 0&&{system:e.system}};return{url:WE,init:{method:"POST",headers:{"x-api-key":this.key,"anthropic-version":qE,"content-type":"application/json"},body:JSON.stringify(n)}}}isDone(){return!1}decode(e){let n=an(M_(e));if(!n)return null;if(n.type==="error")throw new Zt(`anthropic stream error: ${F_(n.error)}`);if(n.type==="content_block_delta"){let i=an(n.delta);if(i?.type==="text_delta"&&typeof i.text=="string")return{type:"text",text:i.text}}return null}},mi=class extends Vs{buildRequest(e){let n=e.system!==void 0?[{role:"system",content:e.system},...e.messages]:e.messages,i={model:e.model,stream:!0,messages:n};return{url:JE,init:{method:"POST",headers:{Authorization:`Bearer ${this.key}`,"content-type":"application/json"},body:JSON.stringify(i)}}}isDone(e){return e==="[DONE]"}decode(e){let n=an(M_(e));if(!n)return null;if(n.error)throw new Zt(`openai stream error: ${F_(n.error)}`);let i=HE(n.choices),r=i?an(i[0])?.delta:void 0,o=an(r)?.content;return typeof o=="string"&&o.length>0?{type:"text",text:o}:null}};function M_(t){try{return JSON.parse(t)}catch{return}}function an(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function HE(t){return Array.isArray(t)?t:void 0}function F_(t){let e=an(t)?.message;return typeof e=="string"?e:"unknown error"}var hi=class{fetchImpl;idleTimeoutMs;constructor(e=fetch,n=Zs){this.fetchImpl=e,this.idleTimeoutMs=n}textAdapter(e,n){switch(e.provider){case"anthropic":return new pi(n,this.fetchImpl,this.idleTimeoutMs);case"openai":return new mi(n,this.fetchImpl,this.idleTimeoutMs);default:throw new Error(`no text adapter for provider '${e.provider}'`)}}};import{randomUUID as am}from"node:crypto";var De=class extends Error{commandId;reason;constructor(e,n,i){super(i??`send rejected (${n}) for command ${e}`),this.commandId=e,this.reason=n,this.name="SessionSendError"}};var V_="You are Jarvis, a voice-first personal agent and a continuous, trusted collaborator - not a disposable chat assistant. You help with software engineering work. Be concise, direct, and technical; skip filler and preamble. When you are unsure, say so plainly rather than guessing. You reason and explain; you do not yet take actions or use tools, so propose the next steps for the human to run rather than claiming to have run them.",gi=class{adapter;model;systemPrompt;history=[];constructor(e,n,i=V_){this.adapter=e,this.model=n,this.systemPrompt=i}async*run(e,n){if(e.trim()==="")return;let i=this.assemble(e),r="";for await(let o of this.adapter.stream({model:this.model,system:this.systemPrompt,messages:i,...n!==void 0&&{signal:n}}))r+=o.text,yield o;this.history.push({role:"user",content:e},{role:"assistant",content:r})}historySnapshot(){return[...this.history]}assemble(e){return[...this.history,{role:"user",content:e}]}};var Bs=class{buffer=[];pending=null;closed=!1;push(e){if(this.closed)return;let n=this.pending;if(n){this.pending=null,n({value:e,done:!1});return}this.buffer.push(e)}close(){if(this.closed)return;this.closed=!0;let e=this.pending;e&&(this.pending=null,e({value:void 0,done:!0}))}async*drain(){for(;;){if(this.buffer.length>0){yield this.buffer.shift();continue}if(this.closed)return;let e=await new Promise(n=>{this.pending=n});if(e.done)return;yield e.value}}};var KE=new Set([".","!","?"]),YE=new Set([",",";",":"]),Z_={minClauseLength:12},vi=class{buffer="";minClauseLength;constructor(e=Z_){this.minClauseLength=e.minClauseLength}push(e){this.buffer+=e;let n=[];for(let i=this.findBoundary();i!==-1;i=this.findBoundary()){let r=this.buffer.slice(0,i+1).trim();this.buffer=this.buffer.slice(i+1).replace(/^\s+/,""),r.length>0&&n.push(r)}return n}flush(){let e=this.buffer.trim();return this.buffer="",e.length>0?[e]:[]}findBoundary(){for(let e=0;e<this.buffer.length;e++){let n=this.buffer[e];if(n===`
77
- `)return e;let i=e+1<this.buffer.length?this.buffer[e+1]:"";if(i!==""&&/\s/.test(i)&&(KE.has(n)||YE.has(n)&&e+1>=this.minClauseLength))return e}return-1}};var yi=class{nextId=1;timers=new Map;now(){return Date.now()}setTimer(e,n){let i=this.nextId++,r=setTimeout(()=>{this.timers.delete(i),n()},e);return this.timers.set(i,r),i}clearTimer(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}};var Ep=class{size;rev;cos;sin;constructor(e){if(e<2||(e&e-1)!==0)throw new Error(`Radix2Fft size must be a power of two >= 2, got ${e}`);this.size=e;let n=Math.log2(e);this.rev=new Uint32Array(e);for(let r=0;r<e;r++){let o=0;for(let s=0;s<n;s++)o|=(r>>s&1)<<n-1-s;this.rev[r]=o}let i=e>>1;this.cos=new Float64Array(i),this.sin=new Float64Array(i);for(let r=0;r<i;r++){let o=2*Math.PI*r/e;this.cos[r]=Math.cos(o),this.sin[r]=Math.sin(o)}}transform(e,n,i){let r=this.size,o=this.rev;for(let s=0;s<r;s++){let a=o[s];if(a>s){let u=e[s];e[s]=e[a],e[a]=u;let c=n[s];n[s]=n[a],n[a]=c}}for(let s=2;s<=r;s<<=1){let a=s>>1,u=r/s;for(let c=0;c<r;c+=s)for(let l=0;l<a;l++){let d=l*u,f=this.cos[d],p=i?this.sin[d]:-this.sin[d],m=c+l,y=m+a,S=e[y]*f-n[y]*p,k=e[y]*p+n[y]*f;e[y]=e[m]-S,n[y]=n[m]-k,e[m]+=S,n[m]+=k}}if(i){let s=1/r;for(let a=0;a<r;a++)e[a]*=s,n[a]*=s}}};function XE(t){let e=1;for(;e<t;)e<<=1;return e}var Gs=class{n;bins;m;fft;chirpCos;chirpSin;bRe;bIm;aRe;aIm;constructor(e){if(e<2)throw new Error(`PowerSpectrum length must be >= 2, got ${e}`);this.n=e,this.bins=(e>>1)+1,this.m=XE(2*e-1),this.fft=new Ep(this.m),this.chirpCos=new Float64Array(e),this.chirpSin=new Float64Array(e);for(let n=0;n<e;n++){let i=n*n%(2*e),r=Math.PI*i/e;this.chirpCos[n]=Math.cos(r),this.chirpSin[n]=Math.sin(r)}this.bRe=new Float64Array(this.m),this.bIm=new Float64Array(this.m);for(let n=0;n<e;n++){let i=this.chirpCos[n],r=this.chirpSin[n];this.bRe[n]=i,this.bIm[n]=r,n!==0&&(this.bRe[this.m-n]=i,this.bIm[this.m-n]=r)}this.fft.transform(this.bRe,this.bIm,!1),this.aRe=new Float64Array(this.m),this.aIm=new Float64Array(this.m)}computePower(e,n){let{n:i,m:r,aRe:o,aIm:s}=this;o.fill(0),s.fill(0);for(let a=0;a<i;a++){let u=e[a];o[a]=u*this.chirpCos[a],s[a]=-u*this.chirpSin[a]}this.fft.transform(o,s,!1);for(let a=0;a<r;a++){let u=o[a],c=s[a],l=this.bRe[a],d=this.bIm[a];o[a]=u*l-c*d,s[a]=u*d+c*l}this.fft.transform(o,s,!0);for(let a=0;a<this.bins;a++){let u=o[a],c=s[a];n[a]=u*u+c*c}}};var Tp=16e3,at=400,QE=160,wt=80,_i=(at>>1)+1,B_=1e-10,eT=1e-7,G_=32768,je=Tp*8,fr=800,Op=wt;function W_(t){let i=27/Math.log(6.4);return t>=1e3?15+Math.log(t/1e3)*i:3*t/200}function tT(t){let i=Math.log(6.4)/27;return t>=15?1e3*Math.exp(i*(t-15)):200*t/3}function q_(t,e,n){let i=new Float64Array(n),r=n>1?(e-t)/(n-1):0;for(let o=0;o<n;o++)i[o]=t+o*r;return n>1&&(i[n-1]=e),i}function rT(){let t=W_(0),e=W_(Tp/2),n=q_(t,e,wt+2),i=new Float64Array(wt+2);for(let a=0;a<n.length;a++)i[a]=tT(n[a]);let r=q_(0,Tp/2,_i),o=new Float64Array(wt+1);for(let a=0;a<wt+1;a++)o[a]=i[a+1]-i[a];let s=[];for(let a=0;a<wt;a++){let u=2/(i[a+2]-i[a]),c=new Float64Array(_i),l=_i,d=0;for(let f=0;f<_i;f++){let p=-(i[a]-r[f])/o[a],m=(i[a+2]-r[f])/o[a+1],y=Math.max(0,Math.min(p,m))*u;c[f]=y,y>0&&(f<l&&(l=f),d=f+1)}l>d&&(l=d=0),s.push({lo:l,hi:d,weights:c.slice(l,d)})}return s}function nT(){let t=new Float64Array(at);for(let e=0;e<at;e++)t[e]=.5-.5*Math.cos(2*Math.PI*e/at);return t}var $i=class{hann=nT();filters=rT();spectrum=new Gs(at);padded=new Float64Array(je+at);frame=new Float64Array(at);power=new Float64Array(_i);logBuf=new Float64Array(wt*fr);fromPcm16(e){return this.window(e),this.normalize(),this.reflectPad(),this.melSpectrogram()}window(e){let n=this.padded,i=at/2,r=e.length;if(r>=je){let o=r-je;for(let s=0;s<je;s++)n[i+s]=e[o+s]/G_}else{let o=je-r;for(let s=0;s<o;s++)n[i+s]=0;for(let s=0;s<r;s++)n[i+o+s]=e[s]/G_}}normalize(){let e=this.padded,n=at/2,i=je,r=0;for(let a=0;a<i;a++)r+=e[n+a];r/=i;let o=0;for(let a=0;a<i;a++){let u=e[n+a]-r;o+=u*u}o/=i;let s=1/Math.sqrt(o+eT);for(let a=0;a<i;a++)e[n+a]=(e[n+a]-r)*s}reflectPad(){let e=this.padded,n=at/2,i=je;for(let r=0;r<n;r++)e[r]=e[n+(n-r)],e[n+i+r]=e[n+(i-2-r)]}melSpectrogram(){let{padded:e,frame:n,power:i,hann:r,filters:o,logBuf:s}=this;for(let l=0;l<fr;l++){let d=l*QE;for(let f=0;f<at;f++)n[f]=e[d+f]*r[f];this.spectrum.computePower(n,i);for(let f=0;f<wt;f++){let{lo:p,hi:m,weights:y}=o[f],S=0;for(let k=p;k<m;k++)S+=y[k-p]*i[k];s[f*fr+l]=Math.log10(S<B_?B_:S)}}let a=-1/0;for(let l of s)l>a&&(a=l);let u=a-8,c=new Float32Array(wt*fr);for(let l=0;l<s.length;l++){let d=s[l]<u?u:s[l];c[l]=(d+4)/4}return c}};var Ws={silenceEnergyThreshold:.02,shortSilenceMs:600,longSilenceMs:1400,reopenGraceMs:400,stopSecsMs:12e3,holdCues:["hold on","give me a sec","give me a second","one moment","actually","wait","let me think"],commitCues:["that's it","go ahead","what do you think"]},bi=class{clock;config;telemetry=null;phase="listening";inSilence=!1;silenceStartedAt=null;firstSpeechAt=null;budgetOwner="baseline";armedBudgetMs=null;lastRawPartial="";lastNormPartial="";commitCb;silenceTimer=null;graceTimer=null;stopTimer=null;constructor(e,n={}){this.clock=e,this.config={...Ws,...n}}onAudioFrame(e){this.phase==="committed"||this.phase==="disposed"||(J_(e,this.config.silenceEnergyThreshold)?this.handleSpeech():this.handleSilence())}onPartial(e){if(!(this.phase==="committed"||this.phase==="disposed")){if(this.lastRawPartial=e.trim(),this.lastNormPartial=iT(e),Pp(this.lastNormPartial,this.config.commitCues)){this.commit("lexical");return}Pp(this.lastNormPartial,this.config.holdCues)&&(this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1)}}onCommit(e){this.commitCb=e}attachTelemetry(e){this.telemetry=e}dispose(){this.phase="disposed",this.clearAllTimers()}handleSpeech(){this.firstSpeechAt===null&&(this.firstSpeechAt=this.clock.now(),this.stopTimer=this.clock.setTimer(this.config.stopSecsMs,()=>this.commit("stop_cap"))),this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1}handleSilence(){this.firstSpeechAt===null||this.phase!=="listening"||this.inSilence||(this.inSilence=!0,this.silenceStartedAt=this.clock.now(),this.budgetOwner="baseline",this.armedBudgetMs=this.silenceBudgetMs(),this.silenceTimer=this.clock.setTimer(this.armedBudgetMs,()=>this.onSilenceBudgetElapsed()),this.onSilenceDetected())}silenceBudgetMs(){return this.isCompleteSounding()?this.config.shortSilenceMs:this.config.longSilenceMs}onSilenceDetected(){}canRefineBudget(){return this.phase==="listening"&&this.inSilence}rearmSilence(e){if(this.phase!=="listening"||!this.inSilence||this.silenceStartedAt===null)return;e!==this.armedBudgetMs&&(this.budgetOwner="smart_turn"),this.armedBudgetMs=e,this.clearSilenceTimer();let n=e-(this.clock.now()-this.silenceStartedAt);n<=0?this.onSilenceBudgetElapsed():this.silenceTimer=this.clock.setTimer(n,()=>this.onSilenceBudgetElapsed())}onSilenceBudgetElapsed(){this.silenceTimer=null,this.phase==="listening"&&(this.phase="tentative",this.graceTimer=this.clock.setTimer(this.config.reopenGraceMs,()=>{this.graceTimer=null,this.commit(this.budgetOwner)}))}isCompleteSounding(){return/[.!?]$/.test(this.lastRawPartial)?!0:Pp(this.lastNormPartial,this.config.commitCues)}commit(e){this.phase==="committed"||this.phase==="disposed"||(this.phase="committed",this.clearAllTimers(),this.telemetry?.endpointerCommitted(e,this.inSilence?this.silenceStartedAt:null),this.commitCb?.())}clearSilenceTimer(){this.silenceTimer!==null&&(this.clock.clearTimer(this.silenceTimer),this.silenceTimer=null)}clearGraceTimer(){this.graceTimer!==null&&(this.clock.clearTimer(this.graceTimer),this.graceTimer=null)}clearAllTimers(){this.clearSilenceTimer(),this.clearGraceTimer(),this.stopTimer!==null&&(this.clock.clearTimer(this.stopTimer),this.stopTimer=null)}};function J_(t,e){let n=Math.floor(t.byteLength/2);if(n===0)return!1;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0;for(let o=0;o<n;o++){let s=i.getInt16(o*2,!0)/32768;r+=s*s}return Math.sqrt(r/n)>=e}function iT(t){return t.toLowerCase().replace(/[.,!?;:]+$/g,"").trim()}function Pp(t,e){return e.some(n=>oT(t,n))}function oT(t,e){if(!t.endsWith(e))return!1;let n=t.length-e.length-1;return n<0||t[n]===" "}var H_={...Ws,commitThreshold:.65,holdThreshold:.35},xi=class extends bi{smartConfig;inference;buffer=new Int16Array(je*2);bufferLen=0;silenceEpoch=0;degraded=!1;smartDisposed=!1;constructor(e,n,i={}){super(e,i),this.smartConfig={...H_,...i},this.inference=n}onAudioFrame(e){this.appendToBuffer(e),super.onAudioFrame(e)}dispose(){this.smartDisposed=!0,this.bufferLen=0,super.dispose()}onSilenceDetected(){if(this.silenceEpoch+=1,this.degraded||this.smartDisposed)return;let e=this.silenceEpoch,n=this.snapshotBuffer();this.runInference(n,e)}async runInference(e,n){let i=this.clock.now(),r;try{r=await this.inference.infer(e)}catch(s){let a=this.degraded;this.degraded=!0,!a&&!this.smartDisposed&&this.telemetry?.smartTurnDegraded(this.clock.now()-i,s);return}let o=this.clock.now()-i;if(this.smartDisposed||n!==this.silenceEpoch||!this.canRefineBudget()){this.telemetry?.smartTurnResolved(r,o,"stale");return}r>=this.smartConfig.commitThreshold?(this.telemetry?.smartTurnResolved(r,o,"shorten"),this.rearmSilence(this.smartConfig.shortSilenceMs)):r<=this.smartConfig.holdThreshold?(this.telemetry?.smartTurnResolved(r,o,"extend"),this.rearmSilence(this.smartConfig.longSilenceMs)):this.telemetry?.smartTurnResolved(r,o,"inconclusive")}appendToBuffer(e){let n=e.byteLength>>1;if(n===0)return;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n>je?n-je:0,o=n-r;if(this.bufferLen+o>this.buffer.length){let s=Math.min(this.bufferLen,je);this.buffer.copyWithin(0,this.bufferLen-s,this.bufferLen),this.bufferLen=s}for(let s=r;s<n;s++)this.buffer[this.bufferLen++]=i.getInt16(s*2,!0)}snapshotBuffer(){let e=Math.max(0,this.bufferLen-je);return this.buffer.slice(e,this.bufferLen)}};import{existsSync as vb}from"node:fs";import{createRequire as ST}from"node:module";import{dirname as kT,join as yb,sep as _b}from"node:path";import{fileURLToPath as IT,pathToFileURL as ET}from"node:url";import{existsSync as sT}from"node:fs";import{fileURLToPath as aT}from"node:url";var wi="smart-turn-v3.1-cpu.onnx",Cp="JARVIS_SMART_TURN_MODEL_PATH";function uT(t){return[new URL(`../../assets/${wi}`,t),new URL(`./assets/${wi}`,t),new URL(`../assets/${wi}`,t)].map(e=>aT(e))}function Ap(t={}){let e=t.baseUrl??import.meta.url,n=t.exists??sT,i="envPath"in t?t.envPath:process.env[Cp];if(i&&n(i))return i;let r=uT(e);for(let o of r)if(n(o))return o;throw new Error(`smart-turn model '${wi}' not found. Tried: ${r.join(", ")}. Set ${Cp} to override.`)}var om="ort-wasm-simd-threaded.wasm",Ei=class{logMel;modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;constructor(e={}){this.logMel=e.logMel??new $i,this.modelPath=e.modelPath}async infer(e){if(this.disposed)throw new Error("SmartTurnRunner is disposed");let n=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let r=this.logMel.fromPcm16(e),o=new i.Tensor("float32",r,[1,Op,fr]),s=await n.run({input_features:o});if(this.disposed)throw new Error("SmartTurnRunner is disposed");let a=n.outputNames[0],c=s[a].data[0];if(!Number.isFinite(c))throw new Error("smart-turn produced a non-finite output");return c<0?0:c>1?1:c}prewarm(){this.disposed||this.ensureSession().catch(()=>{})}async dispose(){this.disposed=!0;let e=this.session;this.session=null,this.sessionPromise=null,this.ort=null,e&&await e.release()}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.load(),this.sessionPromise)}async load(){let e=await TT();this.ort=e,e.env.wasm.numThreads=1,e.env.wasm.wasmPaths=PT();let n=this.modelPath??Ap(),i=await e.InferenceSession.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SmartTurnRunner is disposed");return this.session=i,i}};async function TT(){let t=await Promise.resolve().then(()=>(gb(),hb));return t.default??t}function OT(t){return[new URL("./",t),new URL("../",t)].map(e=>IT(e))}function PT(t=import.meta.url){for(let e of OT(t))if(vb(yb(e,om)))return $b(e);try{let e=kT(ST(t).resolve("onnxruntime-web"));if(vb(yb(e,om)))return $b(e)}catch{}throw new Error(`ort-web WASM runtime '${om}' not found beside the bundle or in node_modules`)}function $b(t){return ET(t.endsWith(_b)?t:t+_b).href}var bb="21m00Tcm4TlvDq8ikWAM",sm={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:bb}}};He();var ta=class{turnId;openedAtMs;log;terminal=!1;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,n,i=te){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)})}committed(e,n){this.commitAtMs===null&&(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}completed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn summary",{turnId:this.turnId,decider:this.decider,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}))}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}};var xb=16e3,wb="pcm_s16le",ra=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new ta(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),this.asrStream=e.asrEngine.open({sampleRate:xb,encoding:wb,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))}async finalizeAndRespond(e){let n;try{n=await this.asrStream.end()}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}if(this.settled)return;if(this.timeline.asrFinalResolved(this.deps.clock.now(),n.text.length),n.text.trim()===""){this.finishBlank();return}this.phase="responding";let i=this.buildUserTurn(n.text,e);this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:i,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"});try{await this.respond(i.text)}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}this.settled||this.finishDone()}async respond(e){let n=!1,i=!1,r=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:xb,encoding:wb});this.ttsStream=r,r.onAudio(o=>{this.settled||(i||(i=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:o}))}),r.onError(o=>this.finishError("turn_failed",o));for await(let o of this.deps.reasoner.run(e,this.reasonAbort.signal)){if(this.settled)return;n||(n=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:o.text});for(let s of this.deps.segmenter.push(o.text))r.pushText(s)}if(!this.settled){for(let o of this.deps.segmenter.flush())r.pushText(o);await r.end()}}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}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.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}}}};var pn=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Ti=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},na=class{deps;sessionId;deviceId;projectId;queue=new Bs;closed=!1;eventsConsumed=!1;inFlight=!1;reasoner=null;turnAbort=null;voiceTurn=null;voiceTurnFailed=!1;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newSegmenter;voiceIdentity;smartTurnInference=null;constructor(e,n,i){this.deps=i,this.sessionId=e,this.deviceId=n.deviceId,this.projectId=n.projectId,this.clock=i.clock??new yi,this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Ei),this.newTurnController=i.createTurnController??(r=>new xi(r,this.ensureSmartTurnInference())),this.newSegmenter=i.createSegmenter??(()=>new vi),this.voiceIdentity=i.voiceIdentity??sm,this.emit({type:"session.ready"})}async send(e){let{commandId:n}=e;if(this.closed)throw new De(n,"closed");if(e.sessionId!==this.sessionId)throw new De(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 De(n,"unsupported");default:throw new De(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();let e=this.smartTurnInference;if(this.smartTurnInference=null,this.queue.close(),e)return e.dispose().catch(()=>{})}return Promise.resolve()}acceptTextInput(e){if(e.text.trim().length===0)throw new De(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new De(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=am();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 pn?"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 De(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=am();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}this.voiceTurn=new ra({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:r=>this.emit(r),onComplete:()=>this.completeVoiceTurn()}),this.smartTurnInference?.prewarm?.(),this.voiceTurn.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.endAudio(e.atMs)}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 pn?"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 Ti("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 Ti("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 Ti(`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}ensureReasoner(){if(this.reasoner)return this.reasoner;let e=this.deps.configService.resolved(),n=e.routes?.text;if(!n)throw new pn("no text model is configured - run 'jarvis init' to set routes.text");let i=e.secrets?.[n.provider];if(!i)throw new pn(`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 gi(r,n.model,this.deps.systemPrompt),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:am(),atMs:Date.now()})}};function ia(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function um(t){return typeof t=="string"?t:""}var CT=new Set(["error","auth_error","quota_exceeded","rate_limited"]);function oa(t){let e=t.message_type;return typeof e=="string"&&(CT.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function Sb(t){return Buffer.from(t).toString("base64")}function kb(t){return new Uint8Array(Buffer.from(t,"base64"))}function sa(t,e){return new Error(`${t} connection error: ${e.message}`)}var Ib="wss://api.elevenlabs.io/v1/speech-to-text/realtime",Oi=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-scribe";constructor(e,n,i,r=Ib){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpoint=r}open(e){return new cm(this.apiKey,this.socketFactory,this.model,this.endpoint,e)}},cm=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(AT(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=oa(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:um(n.text),isFinal:!1,startMs:0});return}if(r==="committed_transcript"||r==="committed_transcript_with_timestamps"){let o=um(n.text);o.length>0&&this.committed.push(o),this.endPending&&this.resolveEnd()}}handleError(e){if(this.closed)return;let n=sa("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:Sb(e),commit:n,sample_rate:this.opts.sampleRate}))}sendCommit(){this.sendChunk(new Uint8Array(0),!0)}teardown(){this.closed||(this.closed=!0,this.socket.close())}};function AT(t,e,n){let i=new URL(t);i.searchParams.set("model_id",e),i.searchParams.set("audio_format",zT(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 zT(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}import{randomUUID as NT}from"node:crypto";var Eb="wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/multi-stream-input",RT={stability:.5,similarity_boost:.75,use_speaker_boost:!0},Pi=class{apiKey;socketFactory;model;endpointTemplate;id="elevenlabs-flash";constructor(e,n,i,r=Eb){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpointTemplate=r}speak(e){return new lm(this.apiKey,this.socketFactory,this.model,this.endpointTemplate,this.id,e)}},lm=class{socket;contextId=NT();opened=!1;cancelled=!1;closed=!1;flushRequested=!1;pending=[];audioCb;errorCb;endPending=null;constructor(e,n,i,r,o,s){let a=DT(s.voice,o);this.socket=n(jT(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.flushRequested)){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.flushRequested=!0,this.opened&&this.sendFlush()})}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.flushRequested&&this.sendFlush()}}handleMessage(e){if(this.cancelled||this.closed)return;let n=ia(e);if(!n)return;let i=oa(n);if(i){this.handleError(new Error(`stream error (${i})`));return}typeof n.audio=="string"&&n.audio.length>0&&this.audioCb?.(kb(n.audio)),n.isFinal===!0&&this.resolveEnd()}handleError(e){if(this.closed)return;let n=sa("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:RT,context_id:this.contextId}))}sendText(e){let n=e.endsWith(" ")?e:`${e} `;this.socket.send(JSON.stringify({text:n,context_id:this.contextId}))}sendFlush(){this.socket.send(JSON.stringify({context_id:this.contextId,text:"",flush:!0}))}sendCloseContext(){this.socket.send(JSON.stringify({context_id:this.contextId,close_context:!0}))}teardown(){this.closed||(this.closed=!0,this.socket.close())}};function DT(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 jT(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",UT(i)),r.searchParams.set("auto_mode","true"),r.toString()}function UT(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var oP=qe(xx(),1),sP=qe(ha(),1),aP=qe(gn(),1),uP=qe(bm(),1),cP=qe(Sm(),1),lP=qe(Pm(),1),Am=qe(_a(),1),dP=qe(Px(),1);var zm=(t,e)=>{let n=new Am.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(fP(r)))},onError:i=>{n.on("error",i)},onClose:i=>{n.on("close",()=>i())}}};function fP(t){return Array.isArray(t)?Buffer.concat(t).toString("utf8"):Buffer.isBuffer(t)?t.toString("utf8"):Buffer.from(t).toString("utf8")}var Ui=class{socketFactory;constructor(e=zm){this.socketFactory=e}asrEngine(e,n){if(e.provider==="elevenlabs")return new Oi(n,this.socketFactory,e.model);throw new Error(`no stt adapter for provider '${e.provider}'`)}ttsEngine(e,n){if(e.provider==="elevenlabs")return new Pi(n,this.socketFactory,e.model);throw new Error(`no tts adapter for provider '${e.provider}'`)}};var mP="jarvis-core",hP="0.1.0-dev",Nm=class{deps;constructor(e){this.deps=e}describe(){return Promise.resolve({name:mP,version:hP})}openSession(e){let n=pP();return te.debug("core opened session",{sessionId:n,capabilities:e.clientCapabilities}),Promise.resolve(new na(n,e,this.deps))}};function Rm(t={}){let e=new dr;te.setLevel(e.logLevel),te.debug("core created",{logLevel:e.logLevel});let n={configService:t.configService??new Ze,registry:t.registry??new hi(t.fetchImpl),voiceRegistry:t.voiceRegistry??new Ui(t.voiceSocketFactory),...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.createSegmenter!==void 0&&{createSegmenter:t.createSegmenter},...t.clock!==void 0&&{clock:t.clock}};return new Nm(n)}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 gP(t){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":t.message:"network error"}var vP=async(t,e,n)=>{let i=await e("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${t}`},signal:n});return ba(i.status)},yP=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)},_P=async(t,e,n)=>{let i=await e("https://api.deepgram.com/v1/projects",{headers:{Authorization:`Token ${t}`},signal:n});return ba(i.status)},$P=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)},bP={elevenlabs:{capabilities:["stt","tts"],defaultModel:{stt:"scribe_v2_realtime",tts:"eleven_flash_v2_5"},keyEnv:"ELEVENLABS_API_KEY",probe:$P},anthropic:{capabilities:["text"],defaultModel:{text:"claude-opus-4-8"},keyEnv:"ANTHROPIC_API_KEY",probe:yP},openai:{capabilities:["text","stt","tts","embedding"],defaultModel:{text:"gpt-4o",stt:"whisper-1",tts:"tts-1",embedding:"text-embedding-3-small"},keyEnv:"OPENAI_API_KEY",probe:vP},deepgram:{capabilities:["stt"],defaultModel:{stt:"nova-2"},keyEnv:"DEEPGRAM_API_KEY",probe:_P}},xn=class{fetchImpl;timeoutMs=3e3;providers;constructor(e=fetch){this.fetchImpl=e,this.providers=bP}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:gP(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 ht=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 ht{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Li=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 xa(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as kP}from"node:events";import jm from"node:child_process";import Pt from"node:path";import Sa from"node:fs";import B from"node:process";import{stripVTControlCharacters as IP}from"node:util";import{stripVTControlCharacters as xP}from"node:util";var Mi=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=>xa(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 p=d.map(m=>o(n.styleOptionTerm(n.optionTerm(m)),n.styleOptionDescription(n.optionDescription(m))));s=s.concat(this.formatItemList(f,p,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 p=d.map(m=>o(n.styleSubcommandTerm(n.subcommandTerm(m)),n.styleSubcommandDescription(n.subcommandDescription(m))));s=s.concat(this.formatItemList(f,p,n))}),s.join(`
77
+ `)return e;let i=e+1<this.buffer.length?this.buffer[e+1]:"";if(i!==""&&/\s/.test(i)&&(KE.has(n)||YE.has(n)&&e+1>=this.minClauseLength))return e}return-1}};var yi=class{nextId=1;timers=new Map;now(){return Date.now()}setTimer(e,n){let i=this.nextId++,r=setTimeout(()=>{this.timers.delete(i),n()},e);return this.timers.set(i,r),i}clearTimer(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}};var Ep=class{size;rev;cos;sin;constructor(e){if(e<2||(e&e-1)!==0)throw new Error(`Radix2Fft size must be a power of two >= 2, got ${e}`);this.size=e;let n=Math.log2(e);this.rev=new Uint32Array(e);for(let r=0;r<e;r++){let o=0;for(let s=0;s<n;s++)o|=(r>>s&1)<<n-1-s;this.rev[r]=o}let i=e>>1;this.cos=new Float64Array(i),this.sin=new Float64Array(i);for(let r=0;r<i;r++){let o=2*Math.PI*r/e;this.cos[r]=Math.cos(o),this.sin[r]=Math.sin(o)}}transform(e,n,i){let r=this.size,o=this.rev;for(let s=0;s<r;s++){let a=o[s];if(a>s){let u=e[s];e[s]=e[a],e[a]=u;let c=n[s];n[s]=n[a],n[a]=c}}for(let s=2;s<=r;s<<=1){let a=s>>1,u=r/s;for(let c=0;c<r;c+=s)for(let l=0;l<a;l++){let d=l*u,f=this.cos[d],p=i?this.sin[d]:-this.sin[d],m=c+l,y=m+a,S=e[y]*f-n[y]*p,k=e[y]*p+n[y]*f;e[y]=e[m]-S,n[y]=n[m]-k,e[m]+=S,n[m]+=k}}if(i){let s=1/r;for(let a=0;a<r;a++)e[a]*=s,n[a]*=s}}};function XE(t){let e=1;for(;e<t;)e<<=1;return e}var Gs=class{n;bins;m;fft;chirpCos;chirpSin;bRe;bIm;aRe;aIm;constructor(e){if(e<2)throw new Error(`PowerSpectrum length must be >= 2, got ${e}`);this.n=e,this.bins=(e>>1)+1,this.m=XE(2*e-1),this.fft=new Ep(this.m),this.chirpCos=new Float64Array(e),this.chirpSin=new Float64Array(e);for(let n=0;n<e;n++){let i=n*n%(2*e),r=Math.PI*i/e;this.chirpCos[n]=Math.cos(r),this.chirpSin[n]=Math.sin(r)}this.bRe=new Float64Array(this.m),this.bIm=new Float64Array(this.m);for(let n=0;n<e;n++){let i=this.chirpCos[n],r=this.chirpSin[n];this.bRe[n]=i,this.bIm[n]=r,n!==0&&(this.bRe[this.m-n]=i,this.bIm[this.m-n]=r)}this.fft.transform(this.bRe,this.bIm,!1),this.aRe=new Float64Array(this.m),this.aIm=new Float64Array(this.m)}computePower(e,n){let{n:i,m:r,aRe:o,aIm:s}=this;o.fill(0),s.fill(0);for(let a=0;a<i;a++){let u=e[a];o[a]=u*this.chirpCos[a],s[a]=-u*this.chirpSin[a]}this.fft.transform(o,s,!1);for(let a=0;a<r;a++){let u=o[a],c=s[a],l=this.bRe[a],d=this.bIm[a];o[a]=u*l-c*d,s[a]=u*d+c*l}this.fft.transform(o,s,!0);for(let a=0;a<this.bins;a++){let u=o[a],c=s[a];n[a]=u*u+c*c}}};var Tp=16e3,at=400,QE=160,wt=80,_i=(at>>1)+1,B_=1e-10,eT=1e-7,G_=32768,je=Tp*8,fr=800,Op=wt;function W_(t){let i=27/Math.log(6.4);return t>=1e3?15+Math.log(t/1e3)*i:3*t/200}function tT(t){let i=Math.log(6.4)/27;return t>=15?1e3*Math.exp(i*(t-15)):200*t/3}function q_(t,e,n){let i=new Float64Array(n),r=n>1?(e-t)/(n-1):0;for(let o=0;o<n;o++)i[o]=t+o*r;return n>1&&(i[n-1]=e),i}function rT(){let t=W_(0),e=W_(Tp/2),n=q_(t,e,wt+2),i=new Float64Array(wt+2);for(let a=0;a<n.length;a++)i[a]=tT(n[a]);let r=q_(0,Tp/2,_i),o=new Float64Array(wt+1);for(let a=0;a<wt+1;a++)o[a]=i[a+1]-i[a];let s=[];for(let a=0;a<wt;a++){let u=2/(i[a+2]-i[a]),c=new Float64Array(_i),l=_i,d=0;for(let f=0;f<_i;f++){let p=-(i[a]-r[f])/o[a],m=(i[a+2]-r[f])/o[a+1],y=Math.max(0,Math.min(p,m))*u;c[f]=y,y>0&&(f<l&&(l=f),d=f+1)}l>d&&(l=d=0),s.push({lo:l,hi:d,weights:c.slice(l,d)})}return s}function nT(){let t=new Float64Array(at);for(let e=0;e<at;e++)t[e]=.5-.5*Math.cos(2*Math.PI*e/at);return t}var $i=class{hann=nT();filters=rT();spectrum=new Gs(at);padded=new Float64Array(je+at);frame=new Float64Array(at);power=new Float64Array(_i);logBuf=new Float64Array(wt*fr);fromPcm16(e){return this.window(e),this.normalize(),this.reflectPad(),this.melSpectrogram()}window(e){let n=this.padded,i=at/2,r=e.length;if(r>=je){let o=r-je;for(let s=0;s<je;s++)n[i+s]=e[o+s]/G_}else{let o=je-r;for(let s=0;s<o;s++)n[i+s]=0;for(let s=0;s<r;s++)n[i+o+s]=e[s]/G_}}normalize(){let e=this.padded,n=at/2,i=je,r=0;for(let a=0;a<i;a++)r+=e[n+a];r/=i;let o=0;for(let a=0;a<i;a++){let u=e[n+a]-r;o+=u*u}o/=i;let s=1/Math.sqrt(o+eT);for(let a=0;a<i;a++)e[n+a]=(e[n+a]-r)*s}reflectPad(){let e=this.padded,n=at/2,i=je;for(let r=0;r<n;r++)e[r]=e[n+(n-r)],e[n+i+r]=e[n+(i-2-r)]}melSpectrogram(){let{padded:e,frame:n,power:i,hann:r,filters:o,logBuf:s}=this;for(let l=0;l<fr;l++){let d=l*QE;for(let f=0;f<at;f++)n[f]=e[d+f]*r[f];this.spectrum.computePower(n,i);for(let f=0;f<wt;f++){let{lo:p,hi:m,weights:y}=o[f],S=0;for(let k=p;k<m;k++)S+=y[k-p]*i[k];s[f*fr+l]=Math.log10(S<B_?B_:S)}}let a=-1/0;for(let l of s)l>a&&(a=l);let u=a-8,c=new Float32Array(wt*fr);for(let l=0;l<s.length;l++){let d=s[l]<u?u:s[l];c[l]=(d+4)/4}return c}};var Ws={silenceEnergyThreshold:.02,shortSilenceMs:600,longSilenceMs:1400,reopenGraceMs:400,stopSecsMs:12e3,holdCues:["hold on","give me a sec","give me a second","one moment","actually","wait","let me think"],commitCues:["that's it","go ahead","what do you think"]},bi=class{clock;config;telemetry=null;phase="listening";inSilence=!1;silenceStartedAt=null;firstSpeechAt=null;budgetOwner="baseline";armedBudgetMs=null;lastRawPartial="";lastNormPartial="";commitCb;silenceTimer=null;graceTimer=null;stopTimer=null;constructor(e,n={}){this.clock=e,this.config={...Ws,...n}}onAudioFrame(e){this.phase==="committed"||this.phase==="disposed"||(J_(e,this.config.silenceEnergyThreshold)?this.handleSpeech():this.handleSilence())}onPartial(e){if(!(this.phase==="committed"||this.phase==="disposed")){if(this.lastRawPartial=e.trim(),this.lastNormPartial=iT(e),Pp(this.lastNormPartial,this.config.commitCues)){this.commit("lexical");return}Pp(this.lastNormPartial,this.config.holdCues)&&(this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1)}}onCommit(e){this.commitCb=e}attachTelemetry(e){this.telemetry=e}dispose(){this.phase="disposed",this.clearAllTimers()}handleSpeech(){this.firstSpeechAt===null&&(this.firstSpeechAt=this.clock.now(),this.stopTimer=this.clock.setTimer(this.config.stopSecsMs,()=>this.commit("stop_cap"))),this.clearSilenceTimer(),this.phase==="tentative"&&(this.clearGraceTimer(),this.phase="listening"),this.inSilence=!1}handleSilence(){this.firstSpeechAt===null||this.phase!=="listening"||this.inSilence||(this.inSilence=!0,this.silenceStartedAt=this.clock.now(),this.budgetOwner="baseline",this.armedBudgetMs=this.silenceBudgetMs(),this.silenceTimer=this.clock.setTimer(this.armedBudgetMs,()=>this.onSilenceBudgetElapsed()),this.onSilenceDetected())}silenceBudgetMs(){return this.isCompleteSounding()?this.config.shortSilenceMs:this.config.longSilenceMs}onSilenceDetected(){}canRefineBudget(){return this.phase==="listening"&&this.inSilence}rearmSilence(e){if(this.phase!=="listening"||!this.inSilence||this.silenceStartedAt===null)return;e!==this.armedBudgetMs&&(this.budgetOwner="smart_turn"),this.armedBudgetMs=e,this.clearSilenceTimer();let n=e-(this.clock.now()-this.silenceStartedAt);n<=0?this.onSilenceBudgetElapsed():this.silenceTimer=this.clock.setTimer(n,()=>this.onSilenceBudgetElapsed())}onSilenceBudgetElapsed(){this.silenceTimer=null,this.phase==="listening"&&(this.phase="tentative",this.graceTimer=this.clock.setTimer(this.config.reopenGraceMs,()=>{this.graceTimer=null,this.commit(this.budgetOwner)}))}isCompleteSounding(){return/[.!?]$/.test(this.lastRawPartial)?!0:Pp(this.lastNormPartial,this.config.commitCues)}commit(e){this.phase==="committed"||this.phase==="disposed"||(this.phase="committed",this.clearAllTimers(),this.telemetry?.endpointerCommitted(e,this.inSilence?this.silenceStartedAt:null),this.commitCb?.())}clearSilenceTimer(){this.silenceTimer!==null&&(this.clock.clearTimer(this.silenceTimer),this.silenceTimer=null)}clearGraceTimer(){this.graceTimer!==null&&(this.clock.clearTimer(this.graceTimer),this.graceTimer=null)}clearAllTimers(){this.clearSilenceTimer(),this.clearGraceTimer(),this.stopTimer!==null&&(this.clock.clearTimer(this.stopTimer),this.stopTimer=null)}};function J_(t,e){let n=Math.floor(t.byteLength/2);if(n===0)return!1;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0;for(let o=0;o<n;o++){let s=i.getInt16(o*2,!0)/32768;r+=s*s}return Math.sqrt(r/n)>=e}function iT(t){return t.toLowerCase().replace(/[.,!?;:]+$/g,"").trim()}function Pp(t,e){return e.some(n=>oT(t,n))}function oT(t,e){if(!t.endsWith(e))return!1;let n=t.length-e.length-1;return n<0||t[n]===" "}var H_={...Ws,commitThreshold:.65,holdThreshold:.35},xi=class extends bi{smartConfig;inference;buffer=new Int16Array(je*2);bufferLen=0;silenceEpoch=0;degraded=!1;smartDisposed=!1;constructor(e,n,i={}){super(e,i),this.smartConfig={...H_,...i},this.inference=n}onAudioFrame(e){this.appendToBuffer(e),super.onAudioFrame(e)}dispose(){this.smartDisposed=!0,this.bufferLen=0,super.dispose()}onSilenceDetected(){if(this.silenceEpoch+=1,this.degraded||this.smartDisposed)return;let e=this.silenceEpoch,n=this.snapshotBuffer();this.runInference(n,e)}async runInference(e,n){let i=this.clock.now(),r;try{r=await this.inference.infer(e)}catch(s){let a=this.degraded;this.degraded=!0,!a&&!this.smartDisposed&&this.telemetry?.smartTurnDegraded(this.clock.now()-i,s);return}let o=this.clock.now()-i;if(this.smartDisposed||n!==this.silenceEpoch||!this.canRefineBudget()){this.telemetry?.smartTurnResolved(r,o,"stale");return}r>=this.smartConfig.commitThreshold?(this.telemetry?.smartTurnResolved(r,o,"shorten"),this.rearmSilence(this.smartConfig.shortSilenceMs)):r<=this.smartConfig.holdThreshold?(this.telemetry?.smartTurnResolved(r,o,"extend"),this.rearmSilence(this.smartConfig.longSilenceMs)):this.telemetry?.smartTurnResolved(r,o,"inconclusive")}appendToBuffer(e){let n=e.byteLength>>1;if(n===0)return;let i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n>je?n-je:0,o=n-r;if(this.bufferLen+o>this.buffer.length){let s=Math.min(this.bufferLen,je);this.buffer.copyWithin(0,this.bufferLen-s,this.bufferLen),this.bufferLen=s}for(let s=r;s<n;s++)this.buffer[this.bufferLen++]=i.getInt16(s*2,!0)}snapshotBuffer(){let e=Math.max(0,this.bufferLen-je);return this.buffer.slice(e,this.bufferLen)}};import{existsSync as vb}from"node:fs";import{createRequire as ST}from"node:module";import{dirname as kT,join as yb,sep as _b}from"node:path";import{fileURLToPath as IT,pathToFileURL as ET}from"node:url";import{existsSync as sT}from"node:fs";import{fileURLToPath as aT}from"node:url";var wi="smart-turn-v3.1-cpu.onnx",Cp="JARVIS_SMART_TURN_MODEL_PATH";function uT(t){return[new URL(`../../assets/${wi}`,t),new URL(`./assets/${wi}`,t),new URL(`../assets/${wi}`,t)].map(e=>aT(e))}function Ap(t={}){let e=t.baseUrl??import.meta.url,n=t.exists??sT,i="envPath"in t?t.envPath:process.env[Cp];if(i&&n(i))return i;let r=uT(e);for(let o of r)if(n(o))return o;throw new Error(`smart-turn model '${wi}' not found. Tried: ${r.join(", ")}. Set ${Cp} to override.`)}var om="ort-wasm-simd-threaded.wasm",Ei=class{logMel;modelPath;sessionPromise=null;session=null;ort=null;disposed=!1;constructor(e={}){this.logMel=e.logMel??new $i,this.modelPath=e.modelPath}async infer(e){if(this.disposed)throw new Error("SmartTurnRunner is disposed");let n=await this.ensureSession(),i=this.ort;if(!i)throw new Error("onnxruntime-web failed to load");let r=this.logMel.fromPcm16(e),o=new i.Tensor("float32",r,[1,Op,fr]),s=await n.run({input_features:o});if(this.disposed)throw new Error("SmartTurnRunner is disposed");let a=n.outputNames[0],c=s[a].data[0];if(!Number.isFinite(c))throw new Error("smart-turn produced a non-finite output");return c<0?0:c>1?1:c}prewarm(){this.disposed||this.ensureSession().catch(()=>{})}async dispose(){this.disposed=!0;let e=this.session;this.session=null,this.sessionPromise=null,this.ort=null,e&&await e.release()}ensureSession(){return this.sessionPromise?this.sessionPromise:(this.sessionPromise=this.load(),this.sessionPromise)}async load(){let e=await TT();this.ort=e,e.env.wasm.numThreads=1,e.env.wasm.wasmPaths=PT();let n=this.modelPath??Ap(),i=await e.InferenceSession.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all",executionMode:"sequential"});if(this.disposed)throw await i.release(),new Error("SmartTurnRunner is disposed");return this.session=i,i}};async function TT(){let t=await Promise.resolve().then(()=>(gb(),hb));return t.default??t}function OT(t){return[new URL("./",t),new URL("../",t)].map(e=>IT(e))}function PT(t=import.meta.url){for(let e of OT(t))if(vb(yb(e,om)))return $b(e);try{let e=kT(ST(t).resolve("onnxruntime-web"));if(vb(yb(e,om)))return $b(e)}catch{}throw new Error(`ort-web WASM runtime '${om}' not found beside the bundle or in node_modules`)}function $b(t){return ET(t.endsWith(_b)?t:t+_b).href}var bb="21m00Tcm4TlvDq8ikWAM",sm={id:"jarvis-primary",engineVoice:{"elevenlabs-flash":{kind:"preset",voiceId:bb}}};He();var ta=class{turnId;openedAtMs;log;terminal=!1;decider=null;silenceOnsetAtMs=null;commitAtMs=null;asrFinalAtMs=null;transcriptLength=null;firstDeltaAtMs=null;firstAudioAtMs=null;constructor(e,n,i=te){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)})}committed(e,n){this.commitAtMs===null&&(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}completed(e){this.terminal||(this.terminal=!0,this.log.debug("voice turn summary",{turnId:this.turnId,decider:this.decider,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}))}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}};var xb=16e3,wb="pcm_s16le",ra=class{deps;asrStream;ttsStream=null;reasonAbort=new AbortController;phase="capturing";settled=!1;finalizing=!1;lastFrameAtMs;timeline;constructor(e){this.deps=e,this.lastFrameAtMs=e.startMs,this.timeline=new ta(e.turnId,e.clock.now()),e.controller.attachTelemetry?.(this.timeline),this.asrStream=e.asrEngine.open({sampleRate:xb,encoding:wb,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))}async finalizeAndRespond(e){let n;try{n=await this.asrStream.end()}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}if(this.settled)return;if(this.timeline.asrFinalResolved(this.deps.clock.now(),n.text.length),n.text.trim()===""){this.finishBlank();return}this.phase="responding";let i=this.buildUserTurn(n.text,e);this.deps.emit({type:"turn.final",turnId:this.deps.turnId,turn:i,...this.deps.commandId!==void 0&&{commandId:this.deps.commandId}}),this.deps.emit({type:"state",turnId:this.deps.turnId,state:"responding"});try{await this.respond(i.text)}catch(r){if(this.settled)return;this.finishError("turn_failed",r);return}this.settled||this.finishDone()}async respond(e){let n=!1,i=!1,r=this.deps.ttsEngine.speak({voice:this.deps.voice,sampleRate:xb,encoding:wb});this.ttsStream=r,r.onAudio(o=>{this.settled||(i||(i=!0,this.timeline.firstTtsAudio(this.deps.clock.now())),this.deps.emit({type:"response.audio",turnId:this.deps.turnId,audio:o}))}),r.onError(o=>this.finishError("turn_failed",o));for await(let o of this.deps.reasoner.run(e,this.reasonAbort.signal)){if(this.settled)return;n||(n=!0,this.timeline.firstReasonerDelta(this.deps.clock.now())),this.deps.emit({type:"response.delta",turnId:this.deps.turnId,text:o.text});for(let s of this.deps.segmenter.push(o.text))r.pushText(s)}if(!this.settled){for(let o of this.deps.segmenter.flush())r.pushText(o);await r.end()}}finishBlank(){this.settled||(this.settled=!0,this.timeline.blank(this.deps.clock.now()),this.deps.onComplete())}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.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}}}};var pn=class extends Error{constructor(e){super(e),this.name="ReasonerUnavailableError"}},Ti=class extends Error{constructor(e){super(e),this.name="VoiceUnavailableError"}},na=class{deps;sessionId;deviceId;projectId;queue=new Bs;closed=!1;eventsConsumed=!1;inFlight=!1;reasoner=null;turnAbort=null;voiceTurn=null;voiceTurnFailed=!1;voiceEngines=null;clock;newTurnController;newSmartTurnInference;newSegmenter;voiceIdentity;smartTurnInference=null;constructor(e,n,i){this.deps=i,this.sessionId=e,this.deviceId=n.deviceId,this.projectId=n.projectId,this.clock=i.clock??new yi,this.newSmartTurnInference=i.createSmartTurnInference??(()=>new Ei),this.newTurnController=i.createTurnController??(r=>new xi(r,this.ensureSmartTurnInference())),this.newSegmenter=i.createSegmenter??(()=>new vi),this.voiceIdentity=i.voiceIdentity??sm,this.emit({type:"session.ready"})}async send(e){let{commandId:n}=e;if(this.closed)throw new De(n,"closed");if(e.sessionId!==this.sessionId)throw new De(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 De(n,"unsupported");default:throw new De(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();let e=this.smartTurnInference;if(this.smartTurnInference=null,this.queue.close(),e)return e.dispose().catch(()=>{})}return Promise.resolve()}acceptTextInput(e){if(e.text.trim().length===0)throw new De(e.commandId,"invalid","input.text requires non-empty text");if(this.inFlight)throw new De(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=am();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 pn?"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 De(e.commandId,"backpressured","a turn is already in progress (one turn at a time in v0.1)");this.inFlight=!0;let n=am();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}this.voiceTurn=new ra({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:r=>this.emit(r),onComplete:()=>this.completeVoiceTurn()}),this.smartTurnInference?.prewarm?.(),this.voiceTurn.pushFrame(e.audio,e.atMs)}endAudioInput(e){if(this.voiceTurnFailed){this.resetVoiceFailure();return}this.voiceTurn?.endAudio(e.atMs)}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 pn?"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 Ti("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 Ti("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 Ti(`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}ensureReasoner(){if(this.reasoner)return this.reasoner;let e=this.deps.configService.resolved(),n=e.routes?.text;if(!n)throw new pn("no text model is configured - run 'jarvis init' to set routes.text");let i=e.secrets?.[n.provider];if(!i)throw new pn(`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 gi(r,n.model,this.deps.systemPrompt),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:am(),atMs:Date.now()})}};function ia(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}}function um(t){return typeof t=="string"?t:""}var CT=new Set(["error","auth_error","quota_exceeded","rate_limited"]);function oa(t){let e=t.message_type;return typeof e=="string"&&(CT.has(e)||e.endsWith("_error"))?e:typeof t.error=="string"&&t.error.length>0?"error":null}function Sb(t){return Buffer.from(t).toString("base64")}function kb(t){return new Uint8Array(Buffer.from(t,"base64"))}function sa(t,e){return new Error(`${t} connection error: ${e.message}`)}var Ib="wss://api.elevenlabs.io/v1/speech-to-text/realtime",Oi=class{apiKey;socketFactory;model;endpoint;id="elevenlabs-scribe";constructor(e,n,i,r=Ib){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpoint=r}open(e){return new cm(this.apiKey,this.socketFactory,this.model,this.endpoint,e)}},cm=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(AT(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=oa(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:um(n.text),isFinal:!1,startMs:0});return}if(r==="committed_transcript"||r==="committed_transcript_with_timestamps"){let o=um(n.text);o.length>0&&this.committed.push(o),this.endPending&&this.resolveEnd()}}handleError(e){if(this.closed)return;let n=sa("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:Sb(e),commit:n,sample_rate:this.opts.sampleRate}))}sendCommit(){this.sendChunk(new Uint8Array(0),!0)}teardown(){this.closed||(this.closed=!0,this.socket.close())}};function AT(t,e,n){let i=new URL(t);i.searchParams.set("model_id",e),i.searchParams.set("audio_format",zT(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 zT(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}import{randomUUID as NT}from"node:crypto";var Eb="wss://api.elevenlabs.io/v1/text-to-speech/{voice_id}/multi-stream-input",RT={stability:.5,similarity_boost:.75,use_speaker_boost:!0},Pi=class{apiKey;socketFactory;model;endpointTemplate;id="elevenlabs-flash";constructor(e,n,i,r=Eb){this.apiKey=e,this.socketFactory=n,this.model=i,this.endpointTemplate=r}speak(e){return new lm(this.apiKey,this.socketFactory,this.model,this.endpointTemplate,this.id,e)}},lm=class{socket;contextId=NT();opened=!1;cancelled=!1;closed=!1;endRequested=!1;closeContextSent=!1;pending=[];audioCb;errorCb;endPending=null;constructor(e,n,i,r,o,s){let a=DT(s.voice,o);this.socket=n(jT(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=oa(n);if(i){this.handleError(new Error(`stream error (${i})`));return}typeof n.audio=="string"&&n.audio.length>0&&this.audioCb?.(kb(n.audio)),(n.isFinal===!0||n.is_final===!0)&&this.resolveEnd()}handleError(e){if(this.closed)return;let n=sa("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:RT,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())}};function DT(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 jT(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",UT(i)),r.searchParams.set("auto_mode","true"),r.toString()}function UT(t){return t.encoding==="pcm_s16le"?`pcm_${t.sampleRate}`:"pcm_16000"}var oP=qe(xx(),1),sP=qe(ha(),1),aP=qe(gn(),1),uP=qe(bm(),1),cP=qe(Sm(),1),lP=qe(Pm(),1),Am=qe(_a(),1),dP=qe(Px(),1);var zm=(t,e)=>{let n=new Am.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(fP(r)))},onError:i=>{n.on("error",i)},onClose:i=>{n.on("close",()=>i())}}};function fP(t){return Array.isArray(t)?Buffer.concat(t).toString("utf8"):Buffer.isBuffer(t)?t.toString("utf8"):Buffer.from(t).toString("utf8")}var Ui=class{socketFactory;constructor(e=zm){this.socketFactory=e}asrEngine(e,n){if(e.provider==="elevenlabs")return new Oi(n,this.socketFactory,e.model);throw new Error(`no stt adapter for provider '${e.provider}'`)}ttsEngine(e,n){if(e.provider==="elevenlabs")return new Pi(n,this.socketFactory,e.model);throw new Error(`no tts adapter for provider '${e.provider}'`)}};var mP="jarvis-core",hP="0.1.0-dev",Nm=class{deps;constructor(e){this.deps=e}describe(){return Promise.resolve({name:mP,version:hP})}openSession(e){let n=pP();return te.debug("core opened session",{sessionId:n,capabilities:e.clientCapabilities}),Promise.resolve(new na(n,e,this.deps))}};function Rm(t={}){let e=new dr;te.setLevel(e.logLevel),te.debug("core created",{logLevel:e.logLevel});let n={configService:t.configService??new Ze,registry:t.registry??new hi(t.fetchImpl),voiceRegistry:t.voiceRegistry??new Ui(t.voiceSocketFactory),...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.createSegmenter!==void 0&&{createSegmenter:t.createSegmenter},...t.clock!==void 0&&{clock:t.clock}};return new Nm(n)}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 gP(t){return t instanceof Error?t.name==="TimeoutError"||t.name==="AbortError"?"request timed out":t.message:"network error"}var vP=async(t,e,n)=>{let i=await e("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${t}`},signal:n});return ba(i.status)},yP=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)},_P=async(t,e,n)=>{let i=await e("https://api.deepgram.com/v1/projects",{headers:{Authorization:`Token ${t}`},signal:n});return ba(i.status)},$P=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)},bP={elevenlabs:{capabilities:["stt","tts"],defaultModel:{stt:"scribe_v2_realtime",tts:"eleven_flash_v2_5"},keyEnv:"ELEVENLABS_API_KEY",probe:$P},anthropic:{capabilities:["text"],defaultModel:{text:"claude-opus-4-8"},keyEnv:"ANTHROPIC_API_KEY",probe:yP},openai:{capabilities:["text","stt","tts","embedding"],defaultModel:{text:"gpt-4o",stt:"whisper-1",tts:"tts-1",embedding:"text-embedding-3-small"},keyEnv:"OPENAI_API_KEY",probe:vP},deepgram:{capabilities:["stt"],defaultModel:{stt:"nova-2"},keyEnv:"DEEPGRAM_API_KEY",probe:_P}},xn=class{fetchImpl;timeoutMs=3e3;providers;constructor(e=fetch){this.fetchImpl=e,this.providers=bP}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:gP(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 ht=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 ht{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Li=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 xa(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as kP}from"node:events";import jm from"node:child_process";import Pt from"node:path";import Sa from"node:fs";import B from"node:process";import{stripVTControlCharacters as IP}from"node:util";import{stripVTControlCharacters as xP}from"node:util";var Mi=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=>xa(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 p=d.map(m=>o(n.styleOptionTerm(n.optionTerm(m)),n.styleOptionDescription(n.optionDescription(m))));s=s.concat(this.formatItemList(f,p,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 p=d.map(m=>o(n.styleSubcommandTerm(n.subcommandTerm(m)),n.styleSubcommandDescription(n.subcommandDescription(m))));s=s.concat(this.formatItemList(f,p,n))}),s.join(`
78
78
  `)}displayWidth(e){return xP(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,`
79
79
  `+" ".repeat(n+u)),s+a+" ".repeat(u)+d.replace(/\n/g,`
80
80
  ${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(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neuvybe/jarvis",
3
- "version": "0.14.2",
3
+ "version": "0.14.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Jarvis - a voice-first personal agent (CLI).",