alkove 0.4.0 → 0.5.0

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.
@@ -30,6 +30,7 @@ export declare class NativeProcessor {
30
30
  focus?: Model;
31
31
  cue?: Model;
32
32
  spot?: Model;
33
+ timbre?: Model;
33
34
  }, options: Value);
34
35
  private part;
35
36
  push(pcm: Float32Array): Record<string, unknown>;
@@ -113,6 +114,7 @@ export declare class NativePipeline {
113
114
  }, options: Value);
114
115
  step(hop: Float32Array, farQuietMs: number): Float32Array;
115
116
  spot(model: Model): void;
117
+ timbre(model: Model): void;
116
118
  raw(hop: Float32Array): void;
117
119
  outs(): PipelineOut[];
118
120
  verified(key: number, same: boolean, score: number): void;
@@ -45,7 +45,6 @@ export declare class Word {
45
45
  export declare const wordOf: (w: Word | WordJSON | string) => Word;
46
46
  export interface CompileOptions {
47
47
  lang?: Lang | Lang[];
48
- chain?: Chain;
49
48
  }
50
49
  export interface Take {
51
50
  score: number;
@@ -36,7 +36,7 @@ export interface AlkExports {
36
36
  alk_lex_free(l: number): void;
37
37
  alk_lex_phonemize(l: number): number;
38
38
  alk_compile(l: number): number;
39
- alk_processor(focus: number, cue: number, spot: number): number;
39
+ alk_processor(focus: number, cue: number, spot: number, timbre: number): number;
40
40
  alk_processor_free(p: number): void;
41
41
  alk_processor_push(p: number, pcm: number, len: number): number;
42
42
  alk_processor_end(p: number): number;
@@ -68,6 +68,7 @@ export interface AlkExports {
68
68
  alk_pipeline_step(p: number, farQuietMs: number): number;
69
69
  alk_pipeline_raw(p: number): void;
70
70
  alk_pipeline_spot(p: number, m: number): void;
71
+ alk_pipeline_timbre(p: number, m: number): number;
71
72
  alk_pipeline_outs(p: number): number;
72
73
  alk_pipeline_pending(p: number): number;
73
74
  alk_pipeline_verified(p: number, key: number, same: number, score: number): void;
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { Alkove, Lex, Spot, Timbre, VoiceprintLearner } from './api';
2
2
  export type { ProcessInput, StreamSource, Usage, UsageOptions } from './api';
3
3
  export type { Enrollment } from './recipes/enroll';
4
4
  export type { Take } from './core/spot/spot';
5
- export type { InterruptOptions, SpeechParams, TurnOptions } from './core/cue';
5
+ export type { SpeechParams, TurnOptions } from './core/cue';
6
6
  export type { Pronunciation, Warning } from './core/lex';
7
7
  export type { Context, Thresholds, WakeEvent, Word, WordJSON } from './core/spot/spot';
8
8
  export { Voiceprint } from './core/timbre';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as t,c as p,d as n,e as s,f as a,g as i,h as c}from"./chunk-CWKQLHLV.js";import{i as e,n as r}from"./chunk-FC4ZSMUX.js";export{n as Alkove,e as AlkoveError,a as Lex,i as Spot,s as Timbre,r as Voiceprint,c as VoiceprintLearner,t as createAgentInput,o as createCallInput,p as createWakeListener};
1
+ import{a as n,b as s,c as a,f as i,g as c}from"./chunk-LB4OLDBE.js";import{f as o,g as t,h as p}from"./chunk-BWNLE4ZO.js";import{i as e,n as r}from"./chunk-SSJ7CLCP.js";export{n as Alkove,e as AlkoveError,a as Lex,i as Spot,s as Timbre,r as Voiceprint,c as VoiceprintLearner,t as createAgentInput,o as createCallInput,p as createWakeListener};
package/dist/loader.d.ts CHANGED
@@ -5,7 +5,6 @@ export interface Config {
5
5
  models?: Partial<Record<ModelName | 'engine', Source>>;
6
6
  modelBaseUrl?: string | URL;
7
7
  assetBaseUrl?: string | URL;
8
- modelDir?: string;
9
8
  }
10
9
  export interface Progress {
11
10
  loaded: number;
@@ -31,6 +31,7 @@ export declare const TIMBRE: {
31
31
  model: string;
32
32
  window: number;
33
33
  min: number;
34
+ max: number;
34
35
  dim: number;
35
36
  };
36
37
  export declare const LEX: {
@@ -0,0 +1 @@
1
+ import{E as W,F as H,a as S,d as R,i as z,w as $,x as D,y as I}from"./chunk-SSJ7CLCP.js";var y=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,r){let t=0;for(;t<e.length;){let n=Math.min(this.size-this.fill,e.length-t);this.buf.set(e.subarray(t,t+n),this.fill),this.fill+=n,t+=n,this.fill===this.size&&(this.fill=0,r(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}};var d=R.chunk,K=["silence","forced","wake"],j=s=>new Uint8Array(s.buffer,s.byteOffset,s.byteLength),v=class{constructor(e,r,t,n={}){this.alk=e;let a={gate:!1,normalize:!0,strength:1,sleep:!0,...n},i={...I,...n.speech},l=(h,c)=>e.x.alk_chain(r.ptr,t.ptr,+a.gate,+a.normalize,+a.sleep,a.strength,i.confidence,i.exitConfidence,i.startSecs,i.stopSecs,h,c),m=n.print?Float32Array.from(n.print):null;this.ptr=m?e.with(j(m),h=>l(h,m.length)):l(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new y(d);mix=new Float32Array(d);focusOut=new Float32Array(d);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let r=this.alk.x;if(!e)r.alk_chain_print(this.ptr,0,0);else{let t=Float32Array.from(e);this.alk.with(j(t),n=>r.alk_chain_print(this.ptr,n,t.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,r){if(this.hops.pending||e.length!==d)throw new RangeError("step() takes whole hops only");return this.hop(e,r)}push(e,r){let t=new Float32Array(Math.floor((this.hops.pending+e.length)/d)*d),n=0;return this.hops.push(e,a=>{t.set(this.hop(a,r),n),n+=d}),t}hop(e,r){let{alk:t,ptr:n}=this,a=t.x;new Float32Array(t.heap,a.alk_chain_hop(n),d).set(e);let i=a.alk_chain_step(n);this.mix.set(new Float32Array(t.heap,i,d));let l=new Float64Array(t.heap,a.alk_chain_events(n),4*a.alk_chain_event_count(n)).slice();for(let m=0;m<l.length;m+=4){let[h,c,u]=[l[m+1],l[m+2],l[m+3]];switch(l[m]){case 0:r({type:"speechstart",start:h});break;case 1:r({type:"speechend",start:h,end:c});break;case 2:r({type:"idle",asleep:h===1,at:c});break;case 3:r({type:"diag",code:"focus.print",level:"info",data:{print:h===1,after:c,why:K[u]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(t.heap,a.alk_chain_focus(n),d)),this.onFocus(this.focusOut,h));break;case 6:this.onCue?.(h,c)}}return this.mix}};var X=new TextEncoder,Z=new TextDecoder;function ee(s){let e=[],r=[],t=0,n=()=>{e.length&&(r.push(Uint8Array.from(e)),t+=e.length,e.length=0)},a=u=>{n(),r.push(u),t+=u.length},i=u=>e.push(u&255,u>>>8&255,u>>>16&255,u>>>24),l=u=>{let k=X.encode(u);i(k.length),a(k)},m=u=>{if(u==null)e.push(0);else if(typeof u=="boolean")e.push(u?2:1);else if(typeof u=="number")e.push(3),a(new Uint8Array(Float64Array.of(u).buffer));else if(typeof u=="string")e.push(4),l(u);else if(u instanceof Uint8Array)e.push(7),i(u.length),a(u.slice());else if(u instanceof Float32Array)e.push(8),i(u.length),a(new Uint8Array(u.slice().buffer));else if(Array.isArray(u)||ArrayBuffer.isView(u)){let k=Array.from(u);e.push(5),i(k.length);for(let f of k)m(f)}else{let k=Object.entries(u).filter(([,f])=>f!==void 0);e.push(6),i(k.length);for(let[f,O]of k)l(f),m(O)}};m(s),n();let h=new Uint8Array(t),c=0;for(let u of r)h.set(u,c),c+=u.length;return h}function re(s){let e=new DataView(s.buffer,s.byteOffset,s.byteLength),r=0,t=()=>(r+=4,e.getUint32(r-4,!0)),n=()=>{let i=t();return r+=i,Z.decode(s.subarray(r-i,r))},a=()=>{switch(s[r++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return r+=8,e.getFloat64(r-8,!0);case 4:return n();case 5:return Array.from({length:t()},a);case 6:return Object.fromEntries(Array.from({length:t()},()=>[n(),a()]));case 7:{let i=t();return r+=i,s.slice(r-i,r)}case 8:{let i=t();return r+=4*i,new Float32Array(s.slice(r-4*i,r).buffer)}default:throw new Error("bad value from the core")}};return a()}function b(s,e){let r=ee(e),t=s.x.alk_value_in(r.length);new Uint8Array(s.heap,t,r.length).set(r)}function p(s,e){let r=re(new Uint8Array(s.heap,s.x.alk_value_out(),s.x.alk_value_len()).slice());if(e>=0)return r;let t=r;throw t.kind==="TypeError"?new TypeError(t.message):t.kind==="RangeError"?new RangeError(t.message):t.kind==="AlkoveError"?new z(t.code,t.message):new Error(t.message)}var o=s=>{if(!s)throw new Error("used after release");return s},_=(s,e,r)=>s.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t=>r(t,e.length)),w=class{constructor(e,r){this.alk=e;this.ptr=e.x.alk_lex(r.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,r){return b(this.alk,{texts:e,lang:r}),p(this.alk,this.alk.x.alk_lex_phonemize(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};function B(s,e,r,t,n){return b(s,{text:r,lang:t,chain:n}),p(s,s.x.alk_compile(e?.handle??0))}var x=class{constructor(e,r,t){this.alk=e;b(e,t),this.ptr=e.x.alk_processor(r.focus?.ptr??0,r.cue?.ptr??0,r.spot?.ptr??0,r.timbre?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:r}=this.alk,t=p(this.alk,e),n=new Float32Array(this.alk.heap,r.alk_processor_audio(o(this.ptr)),r.alk_processor_audio_len(o(this.ptr))).slice(),{start:a,...i}=t;return{start:a,audio:n,...i}}push(e){return this.part(_(this.alk,e,(r,t)=>this.alk.x.alk_processor_push(o(this.ptr),r,t)))}end(){return this.part(this.alk.x.alk_processor_end(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},A=class{constructor(e,r,t,n){this.alk=e;b(e,{words:t,context:n}),this.ptr=e.x.alk_listener(r.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,r){b(this.alk,{words:e,context:r}),p(this.alk,this.alk.x.alk_listener_words(o(this.ptr)))}push(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_listener_push(o(this.ptr),r,t)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},F=class{constructor(e,r,t,n,a){this.alk=e;b(e,{word:t,takes:n,chain:a}),this.ptr=e.x.alk_enroller(r.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_enroller_push(o(this.ptr),r,t)))}result(){return p(this.alk,this.alk.x.alk_enroller_result(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},N=class{constructor(e,r){this.alk=e;this.ptr=e.x.alk_timbre(r.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_timbre_windows(o(this.ptr),r,t)))}embed(e,r){return b(this.alk,{source:r}),p(this.alk,_(this.alk,e,(t,n)=>this.alk.x.alk_timbre_embed(o(this.ptr),t,n)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};function J(s,e){return b(s,e),p(s,s.x.alk_voiceprint())}var M=class{constructor(e,r,t){this.alk=e;b(e,{source:r,start:t}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_learner_learn(o(this.ptr),e.handle,t,n)))}offer(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_learner_offer(o(this.ptr),e.handle,t,n)))}progress(){return p(this.alk,this.state()).progress}ready(){return p(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(o(this.ptr))}voiceprint(e=!1){return p(this.alk,this.alk.x.alk_learner_voiceprint(o(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(o(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},V=class{constructor(e,r,t){this.alk=e;b(e,t),this.ptr=e.x.alk_pipeline(r.focus?.ptr??0,r.cue?.ptr??0,r.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,r){let{alk:t}=this,n=o(this.ptr);new Float32Array(t.heap,t.x.alk_pipeline_hop(n),256).set(e);let a=t.x.alk_pipeline_step(n,r);return this.out.set(new Float32Array(t.heap,a,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(o(this.ptr),e.ptr)}timbre(e){this.alk.x.alk_pipeline_timbre(o(this.ptr),e.ptr)<0&&this.alk.fail("pipeline.timbre")}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(o(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(o(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(o(this.ptr))?p(this.alk,this.alk.x.alk_pipeline_outs(o(this.ptr))):[]}verified(e,r,t){this.alk.x.alk_pipeline_verified(o(this.ptr),e,+r,t)}set(e){b(this.alk,e),p(this.alk,this.alk.x.alk_pipeline_set(o(this.ptr)))}record(e){p(this.alk,this.alk.x.alk_pipeline_record(o(this.ptr),e))}recent(){return p(this.alk,this.alk.x.alk_pipeline_recent(o(this.ptr)))}stats(){return p(this.alk,this.alk.x.alk_pipeline_stats(o(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(o(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(o(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(o(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(o(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(o(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},E=class{constructor(e,r){this.alk=e;b(e,{reference:r}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return b(this.alk,{start:e}),p(this.alk,this.alk.x.alk_coach_learner(o(this.ptr)))}forget(){this.alk.x.alk_coach_forget(o(this.ptr))}window(e,r,t,n){return p(this.alk,_(this.alk,r,(a,i)=>this.alk.x.alk_coach_window(o(this.ptr),e.handle,a,i,t,n)))}verify(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_coach_verify(o(this.ptr),e.handle,t,n)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}};var T=class{constructor(e,r){this.alk=e;this.bytes=r}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let r=this.models.get(e);return r||this.models.set(e,r=this.alk.model(this.bytes(e))),r}stream(e){return this.model(e).session()}chain(e){return new v(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let r=!!e.focus,t={focus:r?this.model("focus"):void 0,cue:r||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0,timbre:r?this.model("timbre"):void 0};return new x(this.alk,t,e)}listener(e,r){return new A(this.alk,this.model("spot"),e,r)}enroller(e,r,t){return new F(this.alk,this.model("spot"),e,r,t)}lex(){return this.lexer??=new w(this.alk,this.model("lex"))}timbre(){return this.voices??=new N(this.alk,this.model("timbre"))}learner(e,r){return new M(this.alk,e,r)}pipeline(e){let r=!!e.chain,t=!!e.words?.length||!!e.enroll,n=new V(this.alk,{focus:r?this.model("focus"):void 0,cue:r?this.model("cue"):void 0,spot:t?this.model("spot"):void 0},e);return r&&n.timbre(this.model("timbre")),n}coach(e){return new E(this.alk,e)}voiceprint(e){return J(this.alk,e)}compile(e,r,t){return B(this.alk,/^\s*\/.+\/\s*$/.test(e)?null:this.lex(),e,r,t)}net(e,r){let t=`${e} ${r??""}`,n=this.calls.get(t);n||this.calls.set(t,n=this.model(e).session(r));let a=n;return{run:(i,l)=>a.call(i,l),reset:()=>a.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}};var g=class extends Error{},C=class s{constructor(e){this.x=e}static async create(e){let r=await WebAssembly.instantiate(e,{});return new s(r.exports)}get heap(){return this.x.memory.buffer}with(e,r){let t=this.x.alk_alloc(e.length);new Uint8Array(this.heap,t,e.length).set(e);try{return r(t,e.length)}finally{this.x.alk_free(t,e.length)}}fail(e){let t=this.x.alk_alloc(512);try{let n=this.x.alk_error(t,512);throw new g(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,t,n))}`)}finally{this.x.alk_free(t,512)}}model(e){return new U(this,e)}},U=class{constructor(e,r){this.alk=e;let t=e.x;this.ptr=e.with(r,(i,l)=>t.alk_model(i,l)),this.ptr||e.fail("model");let n=t.alk_alloc(256),a=i=>new TextDecoder().decode(new Uint8Array(e.heap,n,i));try{this.plans=Array.from({length:t.alk_plans(this.ptr)},(i,l)=>{let m=c=>Array.from({length:t.alk_io_count(this.ptr,l,c)},(u,k)=>{let f=a(t.alk_io_name(this.ptr,l,c,k,n,256)),O=t.alk_io_shape(this.ptr,l,c,k,n,64),L=Array.from(new Uint32Array(e.heap,n,O));return{name:f,dims:L,size:L.reduce((Y,q)=>Y*q,1)}}),h=m(0);return{index:l,name:a(t.alk_plan_name(this.ptr,l,n,256)),inputs:h,outputs:m(1),variable:h[t.alk_variable(this.ptr,l)]?.name??null}})}finally{t.alk_free(n,256)}}ptr;plans;session(e){let r=e===void 0?this.plans[0]:this.plans.find(t=>t.name===e);if(!r)throw new g(`no plan named ${e}`);return new P(this,r)}release(){this.alk.x.alk_model_free(this.ptr)}},P=class{constructor(e,r){this.model=e;this.plan=r;let{alk:t}=e,n=t.x;this.ptr=n.alk_session(e.ptr,r.index),this.ptr||t.fail("session");let a=new TextEncoder;for(let[i,l]of[[r.inputs,n.alk_input],[r.outputs,n.alk_output]])for(let m of i)this.at.set(m.name,{...m,p:t.with(a.encode(m.name),(h,c)=>l(this.ptr,h,c))})}ptr;at=new Map;io(e){let r=this.at.get(e);if(!r)throw new g(`no tensor named ${e}`);return r}f32(e){let r=this.io(e);return new Float32Array(this.model.alk.heap,r.p,r.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,r=this.plan.outputs.map(t=>t.name)){let{alk:t}=this.model,{variable:n}=this.plan;for(let i of this.plan.inputs){let l=e[i.name];if(!l)throw new g(`missing input ${i.name}`);if(i.name===n)t.x.alk_set_len(this.ptr,l.data.length)!==0&&t.fail(i.name);else if(l.data.length!==i.size)throw new g(`${i.name}: ${l.data.length} values for ${i.size}`);this.f32(i.name).set(l.data)}this.run();let a={};for(let i of r)a[i]={data:this.f32(i).slice(),dims:[...this.io(i).dims]};return a}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}};function Q(s){let e=new Map,r=new Map,t=(n,a,i)=>{let l=n.get(a);if(!l)throw new Error(`${i} ${a} is closed, or its worker was started again`);return l};return{embed:(n,a)=>s().timbre().embed(n,a??"raw"),learnerOpen:(n,a)=>{let i=s().learner("raw",a);return e.set(n,i),{progress:i.progress(),ready:i.ready(),voiceprint:i.voiceprint(!0)}},learnerOffer:(n,a)=>{let i=t(e,n,"learner");return{...i.offer(s().timbre(),a),voiceprint:i.voiceprint(!0)}},learnerForget:n=>(e.get(n)?.forget(),null),learnerClose:n=>(e.get(n)?.release(),e.delete(n),null),phonemize:(n,a)=>s().lex().phonemize(n,a),compile:(n,a)=>s().compile(n,a.lang===void 0?[]:[a.lang].flat(),a.chain).word,process:(n,a,i)=>{let l=H(s(),n,{...a,onProgress:i});return{audio:l.audio,raw:l.raw,speech:l.speech,wakes:l.wakes,diag:l.diag,trace:l.trace}},streamOpen:(n,a)=>(r.set(n,new W(s(),a)),null),streamPush:(n,a)=>t(r,n,"stream").push(a),streamEnd:n=>{let a=t(r,n,"stream");return r.delete(n),a.end()}}}var G=class{engine=null;boot=null;bytes=new Map;calls=Q(()=>this.engine);async ready(e){await(this.boot??=(async()=>{let r=await $(S,void 0,new URL("./alkove-engine.wasm",import.meta.url).href),t=await C.create(await WebAssembly.compile(r));this.engine=new T(t,n=>this.bytes.get(n))})().catch(r=>{throw this.boot=null,r}));for(let r of e)this.bytes.has(r)||this.bytes.set(r,await D(r));return this}};export{G as NodeBackend};
package/dist/process.d.ts CHANGED
@@ -5,7 +5,7 @@ import { type Context, type WakeEvent, type Word, type WordJSON } from './core/s
5
5
  import { Voiceprint, type VoiceprintJSON } from './core/timbre';
6
6
  export interface ProcessOptions {
7
7
  focus?: boolean | {
8
- voiceprint?: Voiceprint | VoiceprintJSON | string | null;
8
+ voiceprint?: VoiceprintInput;
9
9
  strength?: number;
10
10
  };
11
11
  cue?: boolean | Partial<SpeechParams>;
@@ -55,6 +55,7 @@ export interface ProcessPart {
55
55
  }
56
56
  export declare function coreOptions(opts: Omit<ProcessOptions, 'onProgress' | 'signal'>, rate?: number): {
57
57
  focus: {
58
+ sample?: number[] | undefined;
58
59
  print: number[] | null;
59
60
  strength: number;
60
61
  } | null;
@@ -73,7 +74,13 @@ export declare function coreOptions(opts: Omit<ProcessOptions, 'onProgress' | 's
73
74
  context: Context;
74
75
  } | null;
75
76
  };
76
- export declare function printOf(p: Voiceprint | VoiceprintJSON | string | null | undefined): Voiceprint | null;
77
+ export type VoiceprintInput = Voiceprint | VoiceprintJSON | string | Float32Array | null;
78
+ export declare function printOf(p: VoiceprintInput | undefined): Voiceprint | null;
79
+ export declare function voiceOf(p: VoiceprintInput | undefined): Promise<{
80
+ print: Voiceprint | VoiceprintJSON | string | null | undefined;
81
+ sample?: Float32Array;
82
+ }>;
83
+ export declare function withVoice<T extends ProcessOptions>(opts: T): Promise<T>;
77
84
  export declare class Processor {
78
85
  readonly opts: Omit<ProcessOptions, 'onProgress' | 'signal'>;
79
86
  private core;
@@ -0,0 +1,19 @@
1
+ import type { AgentInput, AgentOptions, CallInput, CallOptions, InputEvents, Mode, Status, WakeListener, WakeOptions } from './recipes/input';
2
+ export type Handlers = {
3
+ [K in keyof InputEvents]?: (value: InputEvents[K]) => void;
4
+ };
5
+ export interface HookOptions {
6
+ enabled?: boolean;
7
+ on?: Handlers;
8
+ }
9
+ export interface InputState<I> {
10
+ input: I | null;
11
+ status: Status | 'off';
12
+ mode: Mode | null;
13
+ error: Error | null;
14
+ track: MediaStreamTrack | null;
15
+ resume: () => Promise<void>;
16
+ }
17
+ export declare function useAgentInput(options?: Omit<AgentOptions, 'signal'> & HookOptions): InputState<AgentInput>;
18
+ export declare function useCallInput(options?: Omit<CallOptions, 'signal'> & HookOptions): InputState<CallInput>;
19
+ export declare function useWakeListener(options: Omit<WakeOptions, 'signal'> & HookOptions): InputState<WakeListener>;
package/dist/react.js ADDED
@@ -0,0 +1,2 @@
1
+ 'use client';
2
+ import{f as W,g as V,h as F}from"./chunk-BWNLE4ZO.js";import"./chunk-SSJ7CLCP.js";import{useCallback as M,useEffect as h,useLayoutEffect as B,useRef as p,useState as v}from"react";var J=t=>Array.isArray(t)||Object.getPrototypeOf(t)===Object.prototype;function k(t,r){if(Object.is(t,r))return!0;if(typeof t!="object"||typeof r!="object"||!t||!r)return!1;let u=t.toJSON,a=r.toJSON;if(typeof u=="function"||typeof a=="function")return k(typeof u=="function"?u.call(t):t,typeof a=="function"?a.call(r):r);if(!J(t)||!J(r)||Array.isArray(t)!==Array.isArray(r))return!1;let l=Object.keys(t).filter(o=>t[o]!==void 0),S=Object.keys(r).filter(o=>r[o]!==void 0);return l.length===S.length&&l.every(o=>k(t[o],r[o]))}var Q={speechstart:!0,speechend:!0,speechcancel:!0,turn:!0,turnend:!0,interruptstart:!0,interrupt:!0,interruptcancel:!0,mode:!0,status:!0,voiceprint:!0,learn:!0,mic:!0,trackchange:!0,wake:!0,heard:!0,trace:!0,audio:!0,utterance:!0,take:!0,enrolled:!0},X=Object.keys(Q),C=1,D=Promise.resolve(),Y=typeof window>"u"?h:B;function N(t,r,u){let{enabled:a=!0,on:l,...S}=r,o=S,m=p(l),x=p(o),w=Object.fromEntries(Object.entries(o).filter(([n])=>!u.includes(n))),f=p({value:w,version:0}),b=k(f.current.value,w)?f.current.version:f.current.version+1;Y(()=>{m.current=l,x.current=o,b!==f.current.version&&(f.current={value:w,version:b})});let[O,R]=v(null),[P,d]=v("off"),[G,E]=v(null),[K,A]=v(null),[q,H]=v(null),s=p(null),c=p({}),i=p(null),y=M(()=>{let n=!!s.current&&!!m.current?.diag;n&&!i.current?i.current=s.current.on("diag",g=>m.current?.diag?.(g)):!n&&i.current&&(i.current(),i.current=null)},[]);h(()=>{if(!a)return;let n=new AbortController,g=[];d("starting"),A(null);let T=D.then(()=>{if(n.signal.aborted)return;let e={...x.current,signal:n.signal};return c.current={strength:e.strength??C,voiceprint:e.voiceprint??null},t(e)});return D=T.catch(()=>{}),T.then(e=>{if(e){if(n.signal.aborted)return e.dispose();s.current=e,y();for(let I of X)g.push(e.on(I,(z=>m.current?.[I]?.(z))));g.push(e.on("status",d),e.on("mode",I=>E(I.mode)),e.on("trackchange",H)),R(e),d(e.status),E(e.mode)}},e=>{n.signal.aborted||(A(e instanceof Error?e:new Error(String(e))),d("off"))}),()=>{n.abort();for(let e of g)e();i.current?.(),i.current=null,s.current?.dispose(),s.current=null,R(null),d("off"),E(null),H(null),A(null)}},[a,b,t,y]);let U=!!l?.diag;h(y,[O,U,y]);let j=u.includes("strength")?o.strength:void 0,L=u.includes("voiceprint")?o.voiceprint:void 0;h(()=>{let n=s.current;n&&(u.includes("strength")&&(j??C)!==c.current.strength&&(c.current.strength=j??C,n.setStrength(c.current.strength)),u.includes("voiceprint")&&!k(L??null,c.current.voiceprint??null)&&(c.current.voiceprint=L??null,n.setVoiceprint(c.current.voiceprint)))},[O,j,L,u]);let _=M(async()=>{await s.current?.resume()},[]);return{input:O,status:P,mode:G,error:K,get track(){return q??O?.track??null},resume:_}}var Z=["strength","voiceprint"],$=["voiceprint"],tt=[];function ut(t={}){return N(V,t,$)}function st(t={}){return N(W,t,Z)}function ct(t){return N(F,t,tt)}export{ut as useAgentInput,st as useCallInput,ct as useWakeListener};
@@ -7,17 +7,17 @@ export interface RealtimeOptions {
7
7
  pipeline: 'call' | 'agent' | 'wake' | 'enroll';
8
8
  enroll?: {
9
9
  word: WordJSON;
10
- takes: number;
10
+ takes?: number;
11
11
  };
12
12
  verify?: boolean;
13
+ onlyMyVoice?: boolean;
13
14
  chain?: ChainOptions & {
14
15
  levels?: boolean;
15
- near?: boolean | {
16
- gapDb?: number;
17
- };
16
+ near?: boolean;
18
17
  };
19
18
  words?: WordJSON[];
20
19
  context?: Context;
20
+ wake?: boolean;
21
21
  learn?: boolean;
22
22
  keepRecent?: number;
23
23
  trace?: boolean;
@@ -1,11 +1,12 @@
1
- import type { InterruptOptions, SpeechParams, TurnOptions } from '../core/cue';
1
+ import type { TurnOptions } from '../core/cue';
2
2
  import type { Take } from '../core/spot/spot';
3
3
  import { type Context, type WakeEvent, type Word, type WordJSON } from '../core/spot/spot';
4
4
  import type { Warning } from '../core/lex';
5
- import { Voiceprint, type VoiceprintJSON } from '../core/timbre';
5
+ import { Voiceprint } from '../core/timbre';
6
6
  import { type Diag } from '../errors';
7
7
  import { Emitter } from '../events';
8
8
  import { type Lang } from '../manifest';
9
+ import { type VoiceprintInput } from '../process';
9
10
  import { type OutputOptions } from '../realtime/packer';
10
11
  import type { RealtimeOptions } from '../realtime/worker';
11
12
  import { type WorkerLink } from '../runtime/host';
@@ -98,23 +99,14 @@ export interface CommonOptions {
98
99
  track?: MediaStreamTrack;
99
100
  audioContext?: AudioContext;
100
101
  deviceId?: string;
101
- followDefault?: boolean;
102
102
  signal?: AbortSignal;
103
- trace?: boolean;
104
- keepRecent?: number;
105
103
  }
106
104
  export interface FocusOptions extends CommonOptions {
107
- voiceprint?: Voiceprint | VoiceprintJSON | string | null;
108
- learn?: boolean;
109
- farEnd?: MediaStreamTrack | AudioNode | 'manual';
110
- strength?: number;
111
- normalize?: boolean;
112
- stats?: boolean;
113
- speech?: Partial<SpeechParams>;
114
- levels?: boolean;
115
- near?: boolean | {
116
- gapDb?: number;
117
- };
105
+ voiceprint?: VoiceprintInput;
106
+ farEnd?: MediaStreamTrack | AudioNode;
107
+ near?: boolean;
108
+ trace?: boolean;
109
+ keepRecent?: number;
118
110
  }
119
111
  export declare abstract class AlkoveInput extends Emitter<InputEvents> {
120
112
  protected opts: FocusOptions;
@@ -134,12 +126,15 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
134
126
  private _status;
135
127
  private _latency;
136
128
  private _voiceprint;
129
+ protected sample: Float32Array | null;
137
130
  private retryMs;
138
131
  private retryTimer;
139
132
  private started;
140
133
  private counted;
141
134
  private enabled;
142
135
  private printed;
136
+ protected learning: boolean;
137
+ private farCalled;
143
138
  private sender;
144
139
  private stalled;
145
140
  protected spotWords: {
@@ -168,6 +163,7 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
168
163
  get ready(): Promise<void>;
169
164
  private settle;
170
165
  get track(): MediaStreamTrack | null;
166
+ protected currentTrack(): MediaStreamTrack | null;
171
167
  now(): number;
172
168
  protected abstract realtimeOptions(): RealtimeOptions;
173
169
  protected abstract models(): ('focus' | 'cue' | 'spot')[];
@@ -193,6 +189,9 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
193
189
  protected portGiven: boolean;
194
190
  protected appPort(): MessagePort | undefined;
195
191
  protected wantsBackground(): boolean;
192
+ protected learns(): boolean;
193
+ private toBackground;
194
+ private startLearning;
196
195
  protected reference(): Voiceprint | null;
197
196
  private onRealtime;
198
197
  protected onEvent(e: {
@@ -203,8 +202,9 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
203
202
  listen(on: boolean): void;
204
203
  hold(): void;
205
204
  release(): void;
206
- setStrength(s: number): void;
207
- setVoiceprint(p: Voiceprint | VoiceprintJSON | string | null): void;
205
+ setVoiceprint(p: VoiceprintInput): void;
206
+ protected resolveVoice(): Promise<void>;
207
+ private applyPrint;
208
208
  forgetVoiceprint(): void;
209
209
  farEndActive(on: boolean): void;
210
210
  stats(): Promise<{
@@ -230,29 +230,31 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
230
230
  private teardownGraph;
231
231
  spot(words: readonly (Word | WordJSON | string)[], opts?: {
232
232
  context?: Context;
233
- onlyMyVoice?: boolean;
234
233
  }): SpotHandle;
235
234
  enrollWord(text: string, opts?: {
236
235
  lang?: Lang | Lang[];
237
- takes?: number;
238
236
  }): Enrollment;
239
237
  setWords(words: WordJSON[], context: Context): void;
240
238
  dispose(): void;
241
239
  }
242
240
  export interface CallOptions extends FocusOptions {
243
- keepAliveWhenHidden?: boolean;
241
+ onlyMyVoice?: boolean;
242
+ strength?: number;
244
243
  }
245
244
  declare class CallInput extends AlkoveInput {
246
245
  protected opts: CallOptions;
247
246
  protected readonly kind: "call";
248
- private osc;
249
247
  constructor(opts: CallOptions);
250
248
  get track(): MediaStreamTrack;
251
249
  protected get delay16(): number;
252
250
  protected models(): ('focus' | 'cue' | 'spot')[];
253
251
  protected chainOptions(): NonNullable<RealtimeOptions['chain']>;
252
+ protected wantsBackground(): boolean;
253
+ protected reference(): Voiceprint | null;
254
254
  protected realtimeOptions(): RealtimeOptions;
255
+ setStrength(s: number): void;
255
256
  start(): Promise<this>;
257
+ private keepAlive;
256
258
  }
257
259
  export declare class SpotHandle extends Emitter<{
258
260
  wake: WakeEvent;
@@ -264,13 +266,16 @@ export declare class SpotHandle extends Emitter<{
264
266
  }
265
267
  export declare function createCallInput(opts?: CallOptions): Promise<CallInput>;
266
268
  export interface AgentOptions extends FocusOptions {
269
+ onlyMyVoice?: boolean;
267
270
  output?: Partial<OutputOptions> & {
268
271
  port?: MessagePort;
269
272
  };
270
- withTrack?: boolean;
271
- turn?: boolean | Partial<TurnOptions>;
272
- interrupt?: boolean | Partial<InterruptOptions>;
273
- wake?: never;
273
+ turn?: Partial<TurnOptions>;
274
+ wake?: {
275
+ words: readonly (Word | WordJSON | string)[];
276
+ lang?: Lang | Lang[];
277
+ context?: Context;
278
+ };
274
279
  }
275
280
  declare class AgentInput extends AlkoveInput {
276
281
  protected opts: AgentOptions;
@@ -281,7 +286,11 @@ declare class AgentInput extends AlkoveInput {
281
286
  private output;
282
287
  protected get delay16(): number;
283
288
  protected models(): ('focus' | 'cue' | 'spot')[];
289
+ private withTrack;
290
+ get track(): MediaStreamTrack | null;
284
291
  protected connectOutput(): void;
292
+ protected wantsBackground(): boolean;
293
+ protected reference(): Voiceprint | null;
285
294
  protected realtimeOptions(): RealtimeOptions;
286
295
  start(): Promise<this>;
287
296
  }
@@ -289,13 +298,15 @@ export declare function createAgentInput(opts?: AgentOptions): Promise<AgentInpu
289
298
  export interface WakeOptions extends CommonOptions {
290
299
  words: readonly (Word | WordJSON | string)[];
291
300
  context?: Context;
292
- onlyMyVoice?: Voiceprint | VoiceprintJSON | string | null;
301
+ voiceprint?: VoiceprintInput;
302
+ trace?: boolean;
293
303
  }
294
304
  declare class WakeListener extends AlkoveInput {
295
305
  protected opts: WakeOptions & FocusOptions;
296
306
  protected readonly kind: "wake";
297
307
  private words;
298
308
  constructor(opts: WakeOptions & FocusOptions);
309
+ protected resolveVoice(): Promise<void>;
299
310
  protected models(): ('focus' | 'cue' | 'spot')[];
300
311
  protected connectOutput(): void;
301
312
  protected wantsBackground(): boolean;
@@ -305,15 +316,14 @@ declare class WakeListener extends AlkoveInput {
305
316
  }
306
317
  export declare function createWakeListener(opts: WakeOptions): Promise<WakeListener>;
307
318
  declare class EnrollInput extends AlkoveInput {
308
- protected opts: CommonOptions & FocusOptions;
319
+ protected opts: CommonOptions;
309
320
  private word;
310
- private takes;
311
321
  protected readonly kind: "wake";
312
- constructor(opts: CommonOptions & FocusOptions, word: WordJSON, takes: number);
322
+ constructor(opts: CommonOptions, word: WordJSON);
313
323
  protected models(): ('focus' | 'cue' | 'spot')[];
314
324
  protected connectOutput(): void;
315
325
  protected realtimeOptions(): RealtimeOptions;
316
326
  start(): Promise<this>;
317
327
  }
318
- export declare function createEnrollInput(opts: CommonOptions, word: WordJSON, takes: number): Promise<EnrollInput>;
328
+ export declare function createEnrollInput(opts: CommonOptions, word: WordJSON): Promise<EnrollInput>;
319
329
  export type { AgentInput, CallInput, EnrollInput, WakeListener };
package/dist/same.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function same(a: unknown, b: unknown): boolean;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "alkove",
3
- "version": "0.4.0",
4
- "description": "On-device voice input for the web: keep the user's voice, detect speech and wake words. No server, no key.",
3
+ "version": "0.5.0",
4
+ "description": "On-device voice models and SDK for the web: keep the user's voice, detect speech and wake words. No server, no key.",
5
5
  "keywords": [
6
6
  "voice",
7
7
  "speech",
@@ -22,6 +22,7 @@
22
22
  "webrtc",
23
23
  "voice-agent",
24
24
  "on-device",
25
+ "react",
25
26
  "browser",
26
27
  "webassembly",
27
28
  "wasm"
@@ -41,6 +42,10 @@
41
42
  ".": {
42
43
  "types": "./dist/index.d.ts",
43
44
  "default": "./dist/index.js"
45
+ },
46
+ "./react": {
47
+ "types": "./dist/react.d.ts",
48
+ "default": "./dist/react.js"
44
49
  }
45
50
  },
46
51
  "files": [
@@ -48,6 +53,14 @@
48
53
  "LICENSE",
49
54
  "NOTICE"
50
55
  ],
56
+ "peerDependencies": {
57
+ "react": ">=18"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "react": {
61
+ "optional": true
62
+ }
63
+ },
51
64
  "scripts": {
52
65
  "build": "node scripts/build.mjs",
53
66
  "check": "tsc --noEmit",
@@ -56,8 +69,14 @@
56
69
  },
57
70
  "devDependencies": {
58
71
  "@playwright/test": "1.60.0",
72
+ "@testing-library/react": "16.3.3",
59
73
  "@types/node": "^22.10.0",
74
+ "@types/react": "19.3.0",
75
+ "@types/react-dom": "19.3.0",
60
76
  "esbuild": "^0.25.0",
77
+ "jsdom": "30.1.3",
78
+ "react": "19.3.1",
79
+ "react-dom": "19.3.1",
61
80
  "tsx": "^4.23.15",
62
81
  "typescript": "^5.7.0",
63
82
  "vitest": "^3.0.0"
@@ -1 +0,0 @@
1
- import{d as a,e as b,f as c,g as d,h as e}from"./chunk-CWKQLHLV.js";import"./chunk-FC4ZSMUX.js";export{a as Alkove,c as Lex,d as Spot,b as Timbre,e as VoiceprintLearner};
@@ -1,2 +0,0 @@
1
- var e='var ee={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var y=16e3,te=ee,re={chunk:256,print:192,lag:256};var P=n=>`${te[n].name}@${te[n].sha256.slice(0,12)}`,x={model:P("timbre"),window:24e3,min:280,dim:192};var R=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let s=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+s),this.fill),this.fill+=s,r+=s,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}};var T={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};var k=re.chunk,ne=["silence","forced","wake"],se=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),C=class{constructor(e,t,r,s={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...s},i={...T,...s.speech},a=(p,m)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,i.confidence,i.exitConfidence,i.startSecs,i.stopSecs,p,m),u=s.print?Float32Array.from(s.print):null;this.ptr=u?e.with(se(u),p=>a(p,u.length)):a(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new R(k);mix=new Float32Array(k);focusOut=new Float32Array(k);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(se(r),s=>t.alk_chain_print(this.ptr,s,r.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,t){if(this.hops.pending||e.length!==k)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/k)*k),s=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),s),s+=k}),r}hop(e,t){let{alk:r,ptr:s}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(s),k).set(e);let i=o.alk_chain_step(s);this.mix.set(new Float32Array(r.heap,i,k));let a=new Float64Array(r.heap,o.alk_chain_events(s),4*o.alk_chain_event_count(s)).slice();for(let u=0;u<a.length;u+=4){let[p,m,l]=[a[u+1],a[u+2],a[u+3]];switch(a[u]){case 0:t({type:"speechstart",start:p});break;case 1:t({type:"speechend",start:p,end:m});break;case 2:t({type:"idle",asleep:p===1,at:m});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:p===1,after:m,why:ne[l]}});break;case 4:t({type:"diag",code:"focus.reset",level:"info",data:{after:p,why:ne[m]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(s),k)),this.onFocus(this.focusOut,p));break;case 6:this.onCue?.(p,m)}}return this.mix}};var F=class extends Error{constructor(t,r,s){super(r);this.code=t;this.cause=s}name="AlkoveError"};var Ae=new TextEncoder,Me=new TextDecoder;function Fe(n){let e=[],t=[],r=0,s=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{s(),t.push(l),r+=l.length},i=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),a=l=>{let h=Ae.encode(l);i(h.length),o(h)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),a(l);else if(l instanceof Uint8Array)e.push(7),i(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),i(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let h=Array.from(l);e.push(5),i(h.length);for(let f of h)u(f)}else{let h=Object.entries(l).filter(([,f])=>f!==void 0);e.push(6),i(h.length);for(let[f,B]of h)a(f),u(B)}};u(n),s();let p=new Uint8Array(r),m=0;for(let l of t)p.set(l,m),m+=l.length;return p}function Se(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),s=()=>{let i=r();return t+=i,Me.decode(n.subarray(t-i,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return s();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[s(),o()]));case 7:{let i=r();return t+=i,n.slice(t-i,t)}case 8:{let i=r();return t+=4*i,new Float32Array(n.slice(t-4*i,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function b(n,e){let t=Fe(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function d(n,e){let t=Se(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new F(r.code,r.message):new Error(r.message)}var c=n=>{if(!n)throw new Error("used after release");return n},w=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),V=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return b(this.alk,{texts:e,lang:t}),d(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};function ie(n,e,t,r,s){return b(n,{text:t,lang:r,chain:s}),d(n,n.x.alk_compile(e?.handle??0))}var L=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=d(this.alk,e),s=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...i}=r;return{start:o,audio:s,...i}}push(e){return this.part(w(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},U=class{constructor(e,t,r,s){this.alk=e;b(e,{words:r,context:s}),this.ptr=e.x.alk_listener(t.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,t){b(this.alk,{words:e,context:t}),d(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},W=class{constructor(e,t,r,s,o){this.alk=e;b(e,{word:r,takes:s,chain:o}),this.ptr=e.x.alk_enroller(t.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return d(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},I=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return b(this.alk,{source:t}),d(this.alk,w(this.alk,e,(r,s)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,s)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};function oe(n,e){return b(n,e),d(n,n.x.alk_voiceprint())}var z=class{constructor(e,t,r){this.alk=e;b(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,s)))}offer(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,s)))}progress(){return d(this.alk,this.state()).progress}ready(){return d(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return d(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},D=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,s=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(s),256).set(e);let o=r.x.alk_pipeline_step(s,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(c(this.ptr),e.ptr)}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?d(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){b(this.alk,e),d(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){d(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return d(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return d(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},J=class{constructor(e,t){this.alk=e;b(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return b(this.alk,{start:e}),d(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,s){return d(this.alk,w(this.alk,t,(o,i)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,i,r,s)))}verify(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,s)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}};var H=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}stream(e){return this.model(e).session()}chain(e){return new C(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0};return new L(this.alk,r,e)}listener(e,t){return new U(this.alk,this.model("spot"),e,t)}enroller(e,t,r){return new W(this.alk,this.model("spot"),e,t,r)}lex(){return this.lexer??=new V(this.alk,this.model("lex"))}timbre(){return this.voices??=new I(this.alk,this.model("timbre"))}learner(e,t){return new z(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=!!e.words?.length||!!e.enroll;return new D(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:r?this.model("spot"):void 0},e)}coach(e){return new J(this.alk,e)}voiceprint(e){return oe(this.alk,e)}compile(e,t,r){return ie(this.alk,/^\\s*\\/.+\\/\\s*$/.test(e)?null:this.lex(),e,t,r)}net(e,t){let r=`${e} ${t??""}`,s=this.calls.get(r);s||this.calls.set(r,s=this.model(e).session(t));let o=s;return{run:(i,a)=>o.call(i,a),reset:()=>o.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}};var ce=["i","y","\\u0268","u","e","\\xF8","\\u0259","o","\\u025B","\\u0153","\\u0254","a","\\u0251","\\xE6","\\u028C","\\u026A","\\u028A","\\u0250","\\u025C","\\u025B\\u0303","\\u0251\\u0303","\\u0254\\u0303","\\u0250\\u0303","\\u1EBD","\\u0129","\\xF5","\\u0169","j","w","\\u0265","p","b","t","d","k","\\u0261","f","v","s","z","\\u0283","\\u0292","m","n","\\u0272","\\u014B","l","\\u028E","\\u0281","\\u027E","r","\\u0279","x","\\u03B8","\\xF0","\\u03B2","\\u0263","h"].map(n=>n.normalize("NFD"));var q=new Map(ce.map((n,e)=>[n,e+1])),ct=q.get("\\u0259"),Oe={"\\u1D7B":"\\u026A",\\u025A:"\\u0259\\u0279",\\u025D:"\\u025C\\u0279",\\u029D:"j",\\u025F:"\\u0261",c:"k",\\u026B:"l",\\u026C:"l",\\u03C7:"x",\\u0266:"h",\\u028B:"v",\\u0271:"m",\\u027B:"\\u0279",\\u0280:"\\u0281",g:"\\u0261",\\u0258:"\\u0259",\\u0275:"\\xF8",\\u028F:"y",\\u026F:"u",\\u0264:"o",q:"k",\\u0255:"\\u0283",\\u0291:"\\u0292",\\u00E7:"\\u0283",\\u0294:"",\\u0252:"\\u0254",\\u0153\\u0303:"\\u025B\\u0303",\\u0278:"f",\\u0299:"b"},Ee={fr:{\\u0251:"a",\\u00E3:"\\u0251\\u0303",\\u00F5:"\\u0254\\u0303",\\u1EBD:"\\u025B\\u0303",\\u0129:"\\u025B\\u0303",\\u0169:"\\u0254\\u0303",\\u0250\\u0303:"\\u0251\\u0303",\\u0250:"a",\\u00E6:"a",\\u028C:"\\u0153",\\u025C:"\\u0153",\\u026A:"i",\\u028A:"u",\\u0279:"\\u0281",r:"\\u0281",\\u027E:"\\u0281",x:"\\u0281",\\u03B8:"s",\\u00F0:"z",h:"",\\u03B2:"b",\\u0263:"\\u0261",\\u028E:"lj",\\u0268:"i"},es:{\\u026A:"i",\\u028A:"u",\\u025B:"e",\\u0254:"o",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0259:"e",\\u0250:"a",\\u0279:"\\u027E"},it:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0250:"a",\\u0279:"r",x:"k",\\u03B8:"t",h:""},pt:{\\u026A:"i",\\u028A:"u",\\u028A\\u0303:"\\u0169",y:"j",\\u00E3:"\\u0250\\u0303",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0279:"\\u027E"},ca:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"\\u027E",\\u0250:"\\u0259"},ro:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"r",\\u027E:"r"},en:{\\u0250:"\\u0259",r:"\\u0279",x:"k",\\u025B\\u0303:"\\u0251\\u0303"}},Ne=new Set("\\u02C8\\u02CC\\u02D0\\u02D1\\u203F-.|\\u02B2\\u02B0\\u02B7\' "),Pe=[["e","\\u025B"],["o","\\u0254"],["\\xF8","\\u0153","\\u0259"],["i","j"],["u","w"],["y","\\u0265"],["\\u027E","r"]],ae=ce.map((n,e)=>[e+1]);for(let n of Pe){let e=n.map(t=>q.get(t.normalize("NFD")));for(let t of e)for(let r of e)ae[t-1].includes(r)||ae[t-1].push(r)}var le=new Map;function Re(n){let e=le.get(n);if(!e){let t=Object.entries({...Oe,...Ee[n]??{}}).map(([r,s])=>[r.normalize("NFD"),s.normalize("NFD")]);le.set(n,e=new Map(t))}return e}function ue(n){let e=[];for(let t of n.normalize("NFD")){if(/\\p{M}/u.test(t)){t==="\\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function pe(n,e=""){let t=Re(e),r=[];for(let s of ue(n.replace(/\\([^)]*\\)/g," ").replace(/\u200D/g,"").replace(/\\s+/g," ")))if(!Ne.has(s))for(let o of ue(t.get(s)??s)){o=t.get(o)??o;let i=q.get(o);if(!i)return null;r[r.length-1]!==i&&r.push(i)}return r}var $=class n{constructor(e,t,r,s,o,i,a=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=s;this.calibrated=o;this.chain=i;this.warnings=a}warnings;toJSON(){return{alkove:"word",spot:P("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==P("spot"))return null;let r=t.phonemes.map(s=>({...s,ids:pe(s.ipa,s.lang)??[]})).filter(s=>s.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},O=n=>{if(n instanceof $)return n;let e=$.fromJSON(n);if(!e)throw new F("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e};var A=class extends Error{},j=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let s=this.x.alk_error(r,512);throw new A(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,s))}`)}finally{this.x.alk_free(r,512)}}model(e){return new G(this,e)}},G=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(i,a)=>r.alk_model(i,a)),this.ptr||e.fail("model");let s=r.alk_alloc(256),o=i=>new TextDecoder().decode(new Uint8Array(e.heap,s,i));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(i,a)=>{let u=m=>Array.from({length:r.alk_io_count(this.ptr,a,m)},(l,h)=>{let f=o(r.alk_io_name(this.ptr,a,m,h,s,256)),B=r.alk_io_shape(this.ptr,a,m,h,s,64),Z=Array.from(new Uint32Array(e.heap,s,B));return{name:f,dims:Z,size:Z.reduce((_e,xe)=>_e*xe,1)}}),p=u(0);return{index:a,name:o(r.alk_plan_name(this.ptr,a,s,256)),inputs:p,outputs:u(1),variable:p[r.alk_variable(this.ptr,a)]?.name??null}})}finally{r.alk_free(s,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new A(`no plan named ${e}`);return new K(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},K=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,s=r.x;this.ptr=s.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[i,a]of[[t.inputs,s.alk_input],[t.outputs,s.alk_output]])for(let u of i)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(p,m)=>a(this.ptr,p,m))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new A(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:s}=this.plan;for(let i of this.plan.inputs){let a=e[i.name];if(!a)throw new A(`missing input ${i.name}`);if(i.name===s)r.x.alk_set_len(this.ptr,a.data.length)!==0&&r.fail(i.name);else if(a.data.length!==i.size)throw new A(`${i.name}: ${a.data.length} values for ${i.size}`);this.f32(i.name).set(a.data)}this.run();let o={};for(let i of t)o[i]={data:this.f32(i).slice(),dims:[...this.io(i).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}};var Te=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},E=class n{constructor(e,t="focus",r=x.model,s=[]){this.centers=e;this.source=t;this.model=r;this.windows=s;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let s of this.centers)for(let o of t){let i=Te(s.id,o.id);i>r.score&&(r={score:i,mine:s.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:Ce(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==x.model)return null;let r=t.centers.map(s=>({embedding:Float32Array.from(s.embedding),id:Float32Array.from(s.id),seconds:s.seconds}));return new n(r,t.source,t.model,t.windows?Ve(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}};function Ce(n){let e=new Uint8Array(n.length*2*(x.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let i of[o.embedding,o.id]){let a=1e-9;for(let u of i)a=Math.max(a,Math.abs(u));t.setFloat32(r,a/127,!0),r+=4;for(let u of i)t.setInt8(r++,Math.round(u/a*127))}let s="";for(let o of e)s+=String.fromCharCode(o);return btoa(s)}function Ve(n){let e=atob(n),t=Uint8Array.from(e,i=>i.charCodeAt(0)),r=new DataView(t.buffer),s=[],o=0;for(;o+2*(x.dim+4)<=t.length;){let i=[];for(let a=0;a<2;a++){let u=r.getFloat32(o,!0);o+=4;let p=new Float32Array(x.dim);for(let m=0;m<p.length;m++)p[m]=r.getInt8(o++)*u;i.push(p)}s.push({embedding:i[0],id:i[1],seconds:x.window/y})}return s}function he(n,e){let t=n[0]?.length??0,r=n.length,s=t*r*2,o=new Uint8Array(44+s),i=new DataView(o.buffer),a=(p,m)=>[...m].forEach((l,h)=>i.setUint8(p+h,l.charCodeAt(0)));a(0,"RIFF"),i.setUint32(4,36+s,!0),a(8,"WAVE"),a(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,r,!0),i.setUint32(24,e,!0),i.setUint32(28,e*r*2,!0),i.setUint16(32,r*2,!0),i.setUint16(34,16,!0),a(36,"data"),i.setUint32(40,s,!0);let u=44;for(let p=0;p<t;p++)for(let m=0;m<r;m++){let l=Math.max(-1,Math.min(1,n[m][p]));i.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}function Le(n,e=y){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},s=Ue(r.voiceprint)?.embedding,o=n.spot?.words.map(O)??[];return{focus:t?{print:s?Array.from(s):null,strength:r.strength??1}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...T,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(i=>i.toJSON()),context:n.spot?.context??"anywhere"}:null}}function Ue(n){return n?n instanceof E?n:E.fromJSON(n):null}var N=class{constructor(e,t={}){this.opts=t;this.core=e.processor(Le(t))}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},X=16e3;function me(n,e,t={}){let{onProgress:r,signal:s,...o}=t,i=new N(n,o),a=[];try{for(let h=0;h<e.length;h+=X)s?.throwIfAborted(),a.push(i.push(e.subarray(h,Math.min(e.length,h+X)))),r?.({done:Math.min(e.length,h+X),total:e.length});a.push(i.end())}finally{i.release()}let u=new Float32Array(e.length),p=0;for(let h of a)u.set(h.audio.subarray(0,u.length-p),p),p+=h.audio.length;let m=e,l=a.reduce((h,f)=>({speech:[...h.speech,...f.speech],wakes:[...h.wakes,...f.wakes],diag:[...h.diag,...f.diag],trace:f.trace||h.trace?{focus:[...h.trace?.focus??[],...f.trace?.focus??[]],cue:[...h.trace?.cue??[],...f.trace?.cue??[]],spot:[...h.trace?.spot??[],...f.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?u:e,raw:m,...l,toWav(h="audio"){return he(h==="both"?[m,this.audio]:[h==="raw"?m:this.audio],y)}}}function de(n){let e=new Map,t=new Map,r=(s,o,i)=>{let a=s.get(o);if(!a)throw new Error(`${i} ${o} is closed, or its worker was started again`);return a};return{embed:(s,o)=>n().timbre().embed(s,o??"raw"),learnerOpen:(s,o)=>{let i=n().learner("raw",o);return e.set(s,i),{progress:i.progress(),ready:i.ready(),voiceprint:i.voiceprint(!0)}},learnerOffer:(s,o)=>{let i=r(e,s,"learner");return{...i.offer(n().timbre(),o),voiceprint:i.voiceprint(!0)}},learnerForget:s=>(e.get(s)?.forget(),null),learnerClose:s=>(e.get(s)?.release(),e.delete(s),null),phonemize:(s,o)=>n().lex().phonemize(s,o),compile:(s,o)=>n().compile(s,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,process:(s,o,i)=>{let a=me(n(),s,{...o,onProgress:i});return{audio:a.audio,raw:a.raw,speech:a.speech,wakes:a.wakes,diag:a.diag,trace:a.trace}},streamOpen:(s,o)=>(t.set(s,new N(n(),o)),null),streamPush:(s,o)=>r(t,s,"stream").push(o),streamEnd:s=>{let o=r(t,s,"stream");return t.delete(s),o.end()}}}var S=256,Ot=S+2,fe=-1;var ke=new Map,v=null,g=(n,e=[])=>self.postMessage(n,e);async function We(n){v=new H(await j.create(n),e=>{let t=ke.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var Ie=100,ze=125,_=new Map;function we(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&typeof r?.start=="number"&&typeof r.end=="number"&&(r.start+=t,r.end+=t),n.events.push(e)}var ye=n=>n.map(e=>O(e).toJSON()),ve=n=>n?{word:O(n.word).toJSON(),takes:n.takes}:null;function De(n,e,t,r){let s=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=v.pipeline({chain:s?e.chain??{}:null,verify:!!(e.verify&&t),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:ye(e.words??[]),context:e.context??"anywhere",enroll:ve(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1}),i={id:n,port:null,closed:!1,timer:setInterval(()=>je(i),Ie),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:t,out:r,recordId:null};return t&&e.verify&&t.addEventListener("message",a=>{a.data.type!=="verified"||i.closed||(i.p.verified(a.data.key,a.data.same,a.data.score),Q(i))}),_.set(n,i),i}function be(n,e,t){n.out?n.out.postMessage(e,t):g({...e,kind:e.type,type:"pcm",input:n.id},t)}function Q(n){for(let e of n.p.outs())switch(e[0]){case"event":we(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":be(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":be(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":g({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function Je(n,e){let t=!v.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function He(n,e,t){let r=new Float32Array(e),s=r.subarray(0,S);if(r[S+1]===fe){n.p.raw(s),Q(n),t.postMessage(e,[e]);return}let o=performance.now(),i=n.p.step(s,r[S]),a=performance.now()-o;r.set(i),t.postMessage(e,[e]),Q(n),$e(n,a)}function $e(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>S/y*1e3&&t.slow++,t.n<ze)return;let r=n.p.chained;we(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function je(n){n.events.length&&(g({type:"events",input:n.id,list:n.events}),n.events=[])}var ge=de(()=>v),M=new Map,Qe=(n,e)=>g({type:"event",input:n,event:e});function Be(n,e,t,r){let s=M.get(n);if(!s)return;let o=performance.now(),i=s.coach.window(v.timbre(),e,t,r),a=Math.round(performance.now()-o);for(let u of i)u[0]==="print"?s.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=a),Qe(n,u[1]))}function qe({id:n,method:e,args:t,progress:r}){switch(e){case"process":return ge.process(t[0],t[1],r?s=>g({type:"progress",id:n,p:s}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"streamOpen":case"streamPush":case"streamEnd":return ge[e](...t);case"learner":{let s=M.get(t[0]);if(!s)throw new Error("no learning port for this input");return{progress:s.coach.learner(t[1]??null)}}case"forget":return M.get(t[0])?.coach.forget(),null;case"record":{let s=_.get(t[0]);if(!s)throw new Error("no input");s.p.record(t[1]),s.recordId=n;return}case"recent":return _.get(t[0])?.p.recent()??null;case"stats":return _.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function Y(n){let e=_.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),_.delete(n)),M.get(n)?.port.close(),M.get(n)?.coach.release(),M.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await We(e.module),g({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))ke.set(t,new Uint8Array(r));g({type:"reply",id:e.id,result:!0});break;case"realtime":{Y(e.input);let t=De(e.input,e.opts,e.bg??null,e.out??null);e.bg&&(e.bg.onmessage=r=>{r.data.type==="print"&&!t.closed&&t.p.set({print:r.data.embedding})}),g({type:"reply",id:e.id,result:!0});break}case"worklet":{let t=_.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=s=>{t.closed||(s.data instanceof ArrayBuffer?He(t,s.data,r):typeof s.data?.clock=="number"&&(t.shift=s.data.clock/y-t.p.time))};break}case"rt-port":{Y(e.input);let t={coach:v.coach(e.ref??null),port:e.port};M.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?Be(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(v.timbre(),r.data.pcm)})};break}case"set":{let t=_.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:ye(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=ve(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"words"in e||"enroll"in e&&e.enroll?Je(t,()=>{t.p.spot(v.model("spot")),t.p.set(r)}):t.p.set(r),Q(t);break}case"dispose":Y(e.input);break;case"call":{let t=qe(e);t!==void 0&&g({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?g({type:"reply",id:e.id,error:{message:r,code:t?.code}}):g({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};\n',t=`var R=.6931471803691238,q=19082149292705877e-26,N=1.4426950408889634;var F=new DataView(new ArrayBuffer(8));function P(r){return F.setUint32(0,r+1023<<20),F.setUint32(4,0),F.getFloat64(0)}function _(r){if(r!==r)return r;if(r>709.782712893384)return 1/0;if(r<-745.1332191019411)return 0;let t=Math.round(r*N),e=r-t*R,s=t*q,i=e-s,n=i*i,o=i-n*(.16666666666666602+n*(-.0027777777777015593+n*(6613756321437934e-20+n*(-16533902205465252e-22+n*41381367970572385e-24)))),a=1-(s-i*o/(2-o)-e),h=t>>1;return a*P(h)*P(t-h)}var T=1.5707963267341256,W=6077100506506192e-26,H=.6366197723675814;function y(r){let t=r*r;return r+r*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function b(r){let t=r*r,e=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),s=.5*t,i=1-s;return i+(1-i-s+t*e)}function k(r){let t=Math.round(r*H);return[t&3,r-t*T-t*W]}function x(r){let[t,e]=k(r);return t===0?y(e):t===1?b(e):t===2?-y(e):-b(e)}function I(r){let[t,e]=k(r);return t===0?b(e):t===1?-y(e):t===2?-b(e):y(e)}var l=24,M=128,m=class r{constructor(t,e,s=!1){this.inRate=t;this.outRate=e;if(this.identity=t===e,s&&(this.t=l),this.identity)return;this.ratio=t/e;let i=this.half,n=.9/Math.max(1,this.ratio),o=new Float32Array((M+1)*l);for(let a=0;a<=M;a++){let h=a/M,u=0;for(let p=0;p<l;p++){let v=p-(i-1)-h,f=n*v,L=f===0?1:x(Math.PI*f)/(Math.PI*f),O=.42+.5*I(Math.PI*v/i)+.08*I(2*Math.PI*v/i);o[a*l+p]=L*O,u+=o[a*l+p]}for(let p=0;p<l;p++)o[a*l+p]/=u}this.table=o}static HALF=l/2;identity;ratio=1;half=l/2;table=new Float32Array(0);work=new Float32Array(0);histLen=l;t=l/2;push(t,e){if(this.identity){for(let h=0;h<t.length;h++)e(t[h]);return}if(this.work.length<l+8+t.length){let h=new Float32Array(l+8+t.length);h.set(this.work.subarray(0,this.histLen)),this.work=h}let s=this.work;s.set(t,this.histLen);let i=this.histLen+t.length,n=i-1-this.half,o=this.t;for(;o<=n;){let h=Math.floor(o),u=Math.round((o-h)*M)*l,p=h-(this.half-1),v=0;for(let f=0;f<l;f++)v+=s[p+f]*this.table[u+f];e(v),o+=this.ratio}let a=Math.floor(o)-(this.half-1);s.copyWithin(0,a,i),this.histLen=i-a,this.t=o-a}static all(t,e,s){if(e===s)return t;let i=new r(e,s,!0),n=Math.round(t.length*s/e),o=new Float32Array(n),a=0,h=u=>{a<n&&(o[a++]=u)};return i.push(t,h),i.push(new Float32Array(Math.ceil(l*i.ratio)+16),h),o}};var c=256,A=c+2,D=-1,d=16e3,z=2,Q=250,U=1e4,V=400,E=1e4,B=16e4,C=6e4,K=.005,Y=10,G=.003,w=class{buf;start=0;size=0;lost=0;constructor(t){this.buf=new Float32Array(t)}push(t){this.size===this.buf.length&&(this.lost+=this.size,this.start=this.size=0),this.buf[(this.start+this.size)%this.buf.length]=t,this.size++}pull(t,e){for(let s=0;s<e;s++)t[s]=this.buf[(this.start+s)%this.buf.length];this.skip(e)}skip(t){this.start=(this.start+t)%this.buf.length,this.size-=t}peak(t){let e=0;for(let s=0;s<t;s++)e=Math.max(e,Math.abs(this.buf[(this.start+s)%this.buf.length]));return e}},g=class{constructor(t,e,s,i,n=!1){this.rate=t;this.delay16=e;this.now=s;this.emit=i;n&&(this.tap={down:new m(t,d),in16:new w(4096),hop:new Float32Array(A)}),this.fade=1-_(-1/(Y/1e3*t)),this.floor=Math.round(c*(t/d)),this.raw=new Float32Array(Math.max(1,this.latency))}mode="raw";send=null;down;up;in16=new w(4096);out;hop=new Float32Array(A);epoch=0;raw;rawPos=0;mix=0;fade;debt=0;floor;starvedAt=0;windowStart=0;windowStarved=0;sent=0;received=0;inFlight=0;retryMs=E;retryAt=0;activatedAt=0;stopped=!1;quanta=0;stats={min:1/0,max:0,dropped:0};mins=[];windowMin=1/0;farActive=0;farQuietMs=1/0;frames=0;silence=new Float32Array(0);tap=null;onActivate=null;get latency(){let t=this.rate===d?0:m.HALF+m.HALF*(this.rate/d);return Math.round((z*c+this.delay16)*(this.rate/d)+t)}get latencyMs(){return(this.latency+this.debt)/this.rate*1e3}connect(t){this.send=t,this.activate()}pause(t){t?this.mode==="active"&&(this.mode="raw"):this.mode==="raw"&&!this.stopped&&!this.retryAt&&this.send&&this.activate()}stop(){this.stopped=!0,this.mode="raw",this.retryAt=0}activate(){this.down=new m(this.rate,d),this.up=new m(d,this.rate),this.in16=new w(4096),this.out=new w(Math.ceil(this.rate*2));let t=Math.round(z*c*(this.rate/d));for(let e=0;e<t;e++)this.out.push(0);this.epoch++,this.inFlight=0,this.debt=0,this.starvedAt=0,this.windowStart=this.now(),this.windowStarved=0,this.activatedAt=this.now(),this.stopped=!1,this.mode="active",this.onActivate?.(Math.round(this.frames*d/this.rate))}receive(t){this.received++,!(t[c+1]!==this.epoch||this.mode!=="active")&&(this.inFlight>0&&this.inFlight--,this.up.push(t.subarray(0,c),e=>this.out.push(e)))}fail(){this.now()-this.activatedAt>C&&(this.retryMs=E),this.mode="raw",this.retryAt=this.now()+this.retryMs,this.retryMs=Math.min(2*this.retryMs,B),this.emit({type:"overload",queueMs:Math.round(this.out.size/this.rate*1e3),sent:this.sent,received:this.received})}process(t,e,s){let i=s.length;this.frames+=i,this.listenFar(e,i),(!t||!t.length)&&(t=this.silence.length===i?this.silence:this.silence=new Float32Array(i));let n=this.raw,o=n.length;if(this.mode==="raw"&&this.retryAt&&this.now()>=this.retryAt&&this.send&&(this.retryAt=0,this.activate(),this.emit({type:"retry"})),this.mode==="active"){for(this.down.push(t,a=>this.in16.push(a));this.in16.size>=c;)this.in16.pull(this.hop,c),this.hop[c]=this.farQuietMs,this.hop[c+1]=this.epoch,this.send(this.hop),this.inFlight++,this.sent++;this.drain(s)}else this.tap&&this.tapRaw(t);for(let a=0;a<i;a++){let h=t[a]??0,u=n[this.rawPos];n[this.rawPos]=h,this.rawPos=(this.rawPos+1)%o,this.mix+=((this.mode==="active"?1:0)-this.mix)*this.fade,s[a]=this.mode==="active"||this.mix>1e-4?this.mix*(this.mode==="active"?s[a]:0)+(1-this.mix)*u:u}this.mode==="active"&&this.track()}tapRaw(t){let e=this.tap;for(e.down.push(t,s=>e.in16.push(s));e.in16.size>=c;)e.in16.pull(e.hop,c),this.send&&!this.stopped?(e.hop[c]=this.farQuietMs,e.hop[c+1]=D,this.send(e.hop)):this.emit({type:"raw",pcm:e.hop.slice(0,c)})}drain(t){let e=t.length,s=this.out;if(s.lost&&(this.debt=Math.max(0,this.debt-s.lost),s.lost=0),s.size>=e){this.debt>=e&&s.size>=2*e&&this.lowWater()-e>=this.floor&&s.peak(e)<K&&(s.skip(e),this.debt-=e,this.stats.dropped+=e),s.pull(t,e),this.starvedAt&&(this.windowStarved+=this.now()-this.starvedAt,this.starvedAt=0);return}if(t.fill(0),!this.sent)return;this.debt+=e;let i=this.now();this.starvedAt||(this.starvedAt=i),i-this.windowStart>U&&(this.windowStart=i,this.windowStarved=0),(i-this.starvedAt>=Q||this.windowStarved+(i-this.starvedAt)>=V)&&this.fail()}lowWater(){return Math.min(this.windowMin,...this.mins)}track(){let t=this.out.size;this.windowMin=Math.min(this.windowMin,t),this.stats.min=Math.min(this.stats.min,t),this.stats.max=Math.max(this.stats.max,t);let e=Math.round(this.rate/128);if(++this.quanta%e===0&&(this.mins.push(this.windowMin),this.mins.length>2&&this.mins.shift(),this.windowMin=1/0),this.quanta%(2*e)===0){let s=i=>Math.round(i/this.rate*1e3);this.emit({type:"timing",queueMs:[s(this.stats.min),s(this.stats.max)],debtMs:s(this.debt),droppedMs:s(this.stats.dropped),latencyMs:Math.round(this.latencyMs)}),this.stats={min:1/0,max:0,dropped:0}}}listenFar(t,e){let s=e/this.rate*1e3,i=this.farActive>0;if(t&&t.length){let n=0;for(let o=0;o<t.length;o++)n+=t[o]*t[o];i||=Math.sqrt(n/t.length)>G}this.farQuietMs=i?0:this.farQuietMs+s}setFarActive(t){this.farActive=t?1:0,t&&(this.farQuietMs=0)}};var S=class extends AudioWorkletProcessor{core;worker=null;pool=[];dead=!1;constructor(t){super(),this.core=new g(sampleRate,t.processorOptions.delay16,()=>Date.now(),e=>this.port.postMessage(e),!!t.processorOptions.tapRaw),this.port.postMessage({type:"latency",ms:this.core.latencyMs}),this.port.onmessage=e=>{let s=e.data;s.type==="connect"?(this.worker=s.port,this.worker.onmessage=i=>{if(!(i.data instanceof ArrayBuffer))return this.core.pause(!!i.data?.pause);let n=i.data;this.core.receive(new Float32Array(n)),this.pool.push(n)},this.core.onActivate=i=>this.worker.postMessage({clock:i}),this.core.connect(i=>{let n=this.pool.pop()??new ArrayBuffer(A*4);new Float32Array(n).set(i),this.worker.postMessage(n,[n])}),this.port.postMessage({type:"latency",ms:this.core.latencyMs})):s.type==="stop"?this.core.stop():s.type==="far"?this.core.setFarActive(!!s.on):s.type==="dispose"&&(this.dead=!0)}}process(t,e){if(this.dead)return!1;let s=e[0]?.[0];if(!s)return!0;this.core.process(t[0]?.[0]??null,t[1]?.[0]??null,s);for(let i=1;i<(e[0]?.length??0);i++)e[0][i].set(s);return!0}};registerProcessor("alkove",S);
2
- `;export{e as WORKER,t as WORKLET};