@lunora/angular 1.0.0-alpha.60 → 1.0.0-alpha.62

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.
package/dist/index.d.mts CHANGED
@@ -1301,8 +1301,24 @@ interface MicrophoneConfig {
1301
1301
  interruptChunks: number;
1302
1302
  /** RMS above which the user is considered to be barging in while the agent speaks. */
1303
1303
  interruptThreshold: number;
1304
- /** `true` while `status === "speaking"` — gates barge-in detection. */
1305
- isSpeaking: () => boolean;
1304
+ /**
1305
+ * `true` from the moment a turn is committed until it completes — the whole
1306
+ * `thinking` + `speaking` window, not just the audible half.
1307
+ *
1308
+ * It gates BOTH branches below, and the wider span is the point. Gated only
1309
+ * on "audibly speaking", turn detection kept running through the entire
1310
+ * STT+LLM window after a `commit`: room noise at the (deliberately low)
1311
+ * `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
1312
+ * `commit`, and the DO refused it with "a turn is already in progress" —
1313
+ * a refusal that returns before draining the audio buffer, so the PCM
1314
+ * captured since the first commit leaked into the next utterance.
1315
+ *
1316
+ * A genuine barge-in still works in that window: it routes through the
1317
+ * `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
1318
+ * `interruptThreshold` — an order of magnitude above `silenceThreshold` —
1319
+ * and `interrupt` is exactly what the DO tells the client to send.
1320
+ */
1321
+ isTurnActive: () => boolean;
1306
1322
  /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1307
1323
  onAudio: (pcm: Uint8Array) => void;
1308
1324
  /** A barge-in was detected (RMS spike while the agent is speaking). */
package/dist/index.d.ts CHANGED
@@ -1301,8 +1301,24 @@ interface MicrophoneConfig {
1301
1301
  interruptChunks: number;
1302
1302
  /** RMS above which the user is considered to be barging in while the agent speaks. */
1303
1303
  interruptThreshold: number;
1304
- /** `true` while `status === "speaking"` — gates barge-in detection. */
1305
- isSpeaking: () => boolean;
1304
+ /**
1305
+ * `true` from the moment a turn is committed until it completes — the whole
1306
+ * `thinking` + `speaking` window, not just the audible half.
1307
+ *
1308
+ * It gates BOTH branches below, and the wider span is the point. Gated only
1309
+ * on "audibly speaking", turn detection kept running through the entire
1310
+ * STT+LLM window after a `commit`: room noise at the (deliberately low)
1311
+ * `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
1312
+ * `commit`, and the DO refused it with "a turn is already in progress" —
1313
+ * a refusal that returns before draining the audio buffer, so the PCM
1314
+ * captured since the first commit leaked into the next utterance.
1315
+ *
1316
+ * A genuine barge-in still works in that window: it routes through the
1317
+ * `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
1318
+ * `interruptThreshold` — an order of magnitude above `silenceThreshold` —
1319
+ * and `interrupt` is exactly what the DO tells the client to send.
1320
+ */
1321
+ isTurnActive: () => boolean;
1306
1322
  /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1307
1323
  onAudio: (pcm: Uint8Array) => void;
1308
1324
  /** A barge-in was detected (RMS spike while the agent is speaking). */
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{agent as t}from"./packem_shared/agent-CsE5xjQK.mjs";import{agentChat as m}from"./packem_shared/agentChat-kyvh-ktM.mjs";import{agentState as f}from"./packem_shared/agentState-B4sPm-HF.mjs";import{agentToolEvents as n}from"./packem_shared/agentToolEvents-CzZN-jQB.mjs";import{auth as i,authGate as u}from"./packem_shared/auth-BgwruT_M.mjs";import{LUNORA_CLIENT as c,injectLunoraClient as s,provideLunora as l}from"./packem_shared/LUNORA_CLIENT-B0toApHY.mjs";import{connectionStatus as L}from"./packem_shared/connectionStatus-UhmuwzMa.mjs";import{flag as v,flags as y}from"./packem_shared/flag-CwhMtUIL.mjs";import{hydratePreloaded as C}from"./packem_shared/hydratePreloaded-CduDQN77.mjs";import{liveQuery as S}from"./packem_shared/liveQuery-BTIv0WUM.mjs";import{mutate as I}from"./packem_shared/mutate-BZvLQLyu.mjs";import{mutator as P}from"./packem_shared/mutator-DjG1yGk8.mjs";import{infiniteQuery as b,paginatedQuery as j}from"./packem_shared/infiniteQuery-DmFYbw44.mjs";import{presence as K}from"./packem_shared/presence-DqzvJjBN.mjs";import{rateLimit as R}from"./packem_shared/rateLimit-B3h9qzh-.mjs";import{runAction as _}from"./packem_shared/runAction-BfiPq4Xz.mjs";import{stream as q}from"./packem_shared/stream-AffQZjVg.mjs";import{subscription as z}from"./packem_shared/subscription-TT5Jlxw0.mjs";import{voiceAgent as D}from"./packem_shared/voiceAgent-BZZoKTSV.mjs";import{SKIP as H}from"@lunora/client/query";export{c as LUNORA_CLIENT,H as SKIP,t as agent,m as agentChat,f as agentState,n as agentToolEvents,i as auth,u as authGate,L as connectionStatus,v as flag,y as flags,C as hydratePreloaded,b as infiniteQuery,s as injectLunoraClient,S as liveQuery,I as mutate,P as mutator,j as paginatedQuery,K as presence,l as provideLunora,R as rateLimit,_ as runAction,q as stream,z as subscription,D as voiceAgent};
1
+ import{agent as t}from"./packem_shared/agent-CsE5xjQK.mjs";import{agentChat as m}from"./packem_shared/agentChat-kyvh-ktM.mjs";import{agentState as f}from"./packem_shared/agentState-B4sPm-HF.mjs";import{agentToolEvents as n}from"./packem_shared/agentToolEvents-CzZN-jQB.mjs";import{auth as i,authGate as u}from"./packem_shared/auth-BgwruT_M.mjs";import{LUNORA_CLIENT as c,injectLunoraClient as s,provideLunora as l}from"./packem_shared/LUNORA_CLIENT-B0toApHY.mjs";import{connectionStatus as L}from"./packem_shared/connectionStatus-UhmuwzMa.mjs";import{flag as v,flags as y}from"./packem_shared/flag-CwhMtUIL.mjs";import{hydratePreloaded as C}from"./packem_shared/hydratePreloaded-CduDQN77.mjs";import{liveQuery as S}from"./packem_shared/liveQuery-BTIv0WUM.mjs";import{mutate as I}from"./packem_shared/mutate-BZvLQLyu.mjs";import{mutator as P}from"./packem_shared/mutator-DjG1yGk8.mjs";import{infiniteQuery as b,paginatedQuery as j}from"./packem_shared/infiniteQuery-CWifTPMf.mjs";import{presence as K}from"./packem_shared/presence-DqzvJjBN.mjs";import{rateLimit as R}from"./packem_shared/rateLimit-B3h9qzh-.mjs";import{runAction as _}from"./packem_shared/runAction-BfiPq4Xz.mjs";import{stream as q}from"./packem_shared/stream-AffQZjVg.mjs";import{subscription as z}from"./packem_shared/subscription-TT5Jlxw0.mjs";import{voiceAgent as D}from"./packem_shared/voiceAgent-BCA6dkvc.mjs";import{SKIP as H}from"@lunora/client/query";export{c as LUNORA_CLIENT,H as SKIP,t as agent,m as agentChat,f as agentState,n as agentToolEvents,i as auth,u as authGate,L as connectionStatus,v as flag,y as flags,C as hydratePreloaded,b as infiniteQuery,s as injectLunoraClient,S as liveQuery,I as mutate,P as mutator,j as paginatedQuery,K as presence,l as provideLunora,R as rateLimit,_ as runAction,q as stream,z as subscription,D as voiceAgent};
@@ -0,0 +1 @@
1
+ import{computed as O,inject as V,DestroyRef as z,signal as L}from"@angular/core";import{initialPages as v,derivePaginationStatus as U,applyLoadMore as tt,rebalance as et}from"@lunora/client/pagination";import{resolveLunoraClient as G}from"./LUNORA_CLIENT-B0toApHY.mjs";import{s as H,a as nt}from"./platform-R29Vk-0v.mjs";const rt=/["\\\u0000-\u001F\uD800-\uDFFF]/,J=t=>rt.test(t)?JSON.stringify(t):`"${t}"`,$=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return J(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let n="[";for(let s=0;s<t.length;s++)s>0&&(n+=","),n+=$(t[s]);return n+"]"}const r=Object.getPrototypeOf(t);if(r!==null&&r!==Object.prototype){const n=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=t,i=Object.keys(o).sort();let c="{",e=!0;for(const n of i){const s=o[n];s!==void 0&&(e?e=!1:c+=",",c+=J(n),c+=":",c+=$(s))}return c+"}"},D=t=>{let r="";for(let i=0;i<t.length;i+=32768)r+=String.fromCharCode(...t.subarray(i,i+32768));return btoa(r)},l="$lunora.wire$",W=64,q="__proto__",ot=t=>{if(t===null||typeof t!="object")return!1;const r=Object.getPrototypeOf(t);return r===null||r===Object.prototype},S=(t,r=0)=>{if(r>W)throw new RangeError(`wire-codec: value nesting exceeds the ${W}-level limit`);if(t===void 0)return[l,"undefined"];if(t===null)return null;const o=typeof t;if(o==="bigint")return[l,"bigint",t.toString()];if(o==="number"){const e=t;return Number.isNaN(e)?[l,"nan"]:e===1/0?[l,"inf"]:e===-1/0?[l,"-inf"]:e}if(o!=="object")return t;if(t instanceof Date)return[l,"date",S(t.getTime(),r+1)];if(t instanceof Error){const e=t,n={};for(const u of Object.keys(e)){if(e[u]===void 0)continue;const y=S(e[u],r+1);u===q?Object.defineProperty(n,u,{configurable:!0,enumerable:!0,value:y,writable:!0}):n[u]=y}const s=[l,"error",e.name,e.message,n];return e.cause!==void 0&&s.push(S(e.cause,r+1)),s}if(t instanceof URL)return[l,"url",t.href];if(t instanceof Map)return[l,"map",[...t.entries()].map(([e,n])=>[S(e,r+1),S(n,r+1)])];if(t instanceof Set)return[l,"set",[...t].map(e=>S(e,r+1))];if(t instanceof ArrayBuffer)return[l,"bytes",D(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){const e=t,n=e.constructor.name,s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[l,"bytes",D(s)]:[l,"bytes",D(s),n]}if(Array.isArray(t)){const e=t.map(n=>S(n,r+1));return e.length>0&&e[0]===l?[l,"arr",e]:e}if(!ot(t)){const e=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const i=t,c={};for(const e of Object.keys(i)){const n=i[e];if(n===void 0)continue;const s=S(n,r+1);e===q?Object.defineProperty(c,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):c[e]=s}return c},st=t=>$(S(t)),K=(t,r)=>`${t}::${st(r)}`,M=(t,r)=>({...r,paginationOpts:{cursor:t.lower,endCursor:t.upper,numItems:t.numItems}}),Q=(t,r,o,i)=>{const c=G(o.client),e=o.destroyRef===void 0&&i===void 0,{initialNumItems:n,shardKey:s}=o,u=t.__lunoraRef,y=r==="skip"?{}:r,a=L(v(n)),E=L([]),B=L("LoadingFirstPage"),A=L(void 0),R=new Map,m=new Map,C=new Set,N=()=>{const b=a().map(f=>{const g=K(u,M(f,y));return m.get(g)});E.set(b);const{status:P}=U(r==="skip",b);B.set(P)},Y=(w,b)=>{const P=f=>K(u,M(f,y));for(const f of b){const g=P(f);if(m.has(g))continue;const p=w.find(d=>d.lower===f.lower);if(p){const d=m.get(P(p));d&&m.set(g,d)}}},Z=w=>{const b=new Set;for(const f of w)b.add(K(u,M(f,y)));for(const[f,g]of R)b.has(g.currentKey)||(g.unsub(),R.delete(f),m.delete(g.currentKey));const P=new Set([...R.values()].map(f=>f.currentKey));for(const f of w){const g=M(f,y),p=K(u,g);if(P.has(p))continue;const d={currentKey:p,unsub:void 0};C.add(p);const x=c.subscribe(t,g,j=>{if(m.set(d.currentKey,j),C.delete(d.currentKey),A.set(void 0),N(),C.size===0){const h=a(),k=et(h,E());k&&(Y(h,k),a.set(k),F(k),N())}},{onError:j=>{C.delete(p),A.set(j);const h=a(),k=h.at(-1);h.length>1&&k&&!m.has(p)&&K(u,M(k,y))===p&&(a.set(h.slice(0,-1)),F(a())),N(),o.onError?.(j)},shardKey:s});d.unsub=x,R.set(p,d),P.add(p)}};let I=!1,_=!1;const F=w=>{if(I){_=!0;return}I=!0;try{let b=w;do _=!1,Z(b),b=a();while(_)}finally{I=!1}};r!=="skip"&&H(e)&&F(a()),N();const T=()=>{for(const w of R.values())w.unsub();R.clear(),m.clear()};return i===void 0?(o.destroyRef??V(z)).onDestroy(T):i(T),{error:A,loadMore:w=>{if(r==="skip")return;const{nextCursor:b,status:P}=U(!1,E());if(P!=="CanLoadMore")return;const f=tt(a(),b,w);if(!f)return;const g=a().at(-1),p=f.at(-2);if(g&&p){const d=K(u,M(g,y)),x=K(u,M(p,y)),j=R.get(d);if(j&&d!==x){const h=m.get(d);h&&m.set(x,h),j.unsub(),R.delete(d),m.delete(d)}}A.set(void 0),a.set(f),F(a()),N()},pageResults:E,status:B}},X=(t,r,o)=>{if(typeof r!="function")return Q(t,r,o);const i=G(o.client),c=o.destroyRef===void 0,e=o.destroyRef??V(z),n=L(void 0);return H(c)&&nt(r,{destroyRef:e,injector:o.injector},(s,u)=>{const y=[];n.set(Q(t,s,{...o,client:i},a=>y.push(a))),u(()=>{for(const a of y)a()})}),{error:O(()=>n()?.error()),loadMore:s=>{n()?.loadMore(s)},pageResults:O(()=>n()?.pageResults()??[]),status:O(()=>n()?.status()??"LoadingFirstPage")}},yt=(t,r,o)=>{const i=X(t,r,o),c=O(()=>i.pageResults().flatMap(n=>n?.page??[])),e=O(()=>{const n=i.status();return n==="LoadingFirstPage"||n==="LoadingMore"});return{error:i.error,isLoading:e,loadMore:i.loadMore,results:c,status:i.status}},dt=(t,r,o)=>{const{initialNumItems:i}=o,c=X(t,r,o),e=O(()=>c.pageResults().flatMap(a=>a?[a.page]:[])),n=O(()=>c.status()==="LoadingFirstPage"),s=O(()=>c.status()==="CanLoadMore"),u=O(()=>c.status()==="LoadingMore"),y=a=>{c.loadMore(a??i)};return{error:c.error,fetchNextPage:y,hasNextPage:s,isFetchingNextPage:u,isLoading:n,pages:e,status:c.status}};export{dt as infiniteQuery,yt as paginatedQuery};
@@ -0,0 +1 @@
1
+ import{inject as B,DestroyRef as K,signal as T}from"@angular/core";import{resolveLunoraClient as V}from"./LUNORA_CLIENT-B0toApHY.mjs";import{o as q}from"./platform-R29Vk-0v.mjs";const D="/_lunora/ws",j="/_lunora/voice/",J=4001,L=e=>e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e,G=e=>{const r=e.startsWith("agents:")?e.slice(7):e;return r.endsWith("Voice")?r.slice(0,-5):r},X=(e,r)=>{if(r===void 0||r==="")return L(e);if(r.endsWith(D))return r.slice(0,-D.length);try{return new URL(r).origin}catch{return L(e)}},z=e=>{const r=X(e.httpUrl,e.wsUrl),s=r.endsWith("/")?r.slice(0,-1):r,i=new URLSearchParams({threadKey:e.threadKey});return`${s}${j}${encodeURIComponent(e.agent)}?${i.toString()}`},Q=(e,r)=>{if(r?.code===J)return new Error(`${e}: authentication token expired — refresh the credential and start a new call`)},Y=(e,r,s)=>{const i=e.currentIdentity();return e.onAuthTokenChange(()=>{e.currentIdentity()!==i&&s(new Error(`${r}: the signed-in identity changed during the call — the session was ended; start a new call`))})},Z=16e3,ee=e=>{if(e.length===0)return 0;let r=0;for(const s of e)r+=s*s;return Math.sqrt(r/e.length)},te=(e,r)=>{const s=r/Z,i=s>1?Math.floor(e.length/s):e.length,k=new ArrayBuffer(i*2),l=new DataView(k);for(let u=0;u<i;u+=1){const y=e[Math.floor(u*s)]??0,d=Math.max(-1,Math.min(1,y));l.setInt16(u*2,d<0?d*32768:d*32767,!0)}return new Uint8Array(k)},ne=async e=>{const r=globalThis,s=r.navigator?.mediaDevices?.getUserMedia.bind(r.navigator.mediaDevices),i=r.AudioContext??r.webkitAudioContext;if(!s||!i)throw new Error("voiceAgent: microphone capture requires getUserMedia + AudioContext (no browser audio available)");const k=await s({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),l=new i,u=l.createMediaStreamSource(k),y=l.createScriptProcessor(4096,1,1);let d=!1,m=!1,c=0,g=0;return y.onaudioprocess=p=>{const h=p.inputBuffer.getChannelData(0),a=d?0:ee(h);if(e.onLevel(a),d)return;if(e.onAudio(te(h,l.sampleRate)),e.isTurnActive()){g=a>=e.interruptThreshold?g+1:0,g>=e.interruptChunks&&(g=0,e.onInterrupt());return}g=0;const v=h.length/l.sampleRate*1e3;if(a>=e.silenceThreshold){m=!0,c=0;return}m&&(c+=v,c>=e.silenceDurationMs&&(m=!1,c=0,e.onSilence()))},u.connect(y),y.connect(l.destination),{setMuted:p=>{d=p},stop:()=>{y.disconnect(),u.disconnect();for(const p of k.getTracks())p.stop();l.close()}}},re=()=>{const e=globalThis,r=e.AudioContext??e.webkitAudioContext;if(!r)throw new Error("voiceAgent: audio playback requires AudioContext (no browser audio available)");const s=new r,i=new Set;let k=0,l=Promise.resolve(),u=0;const y=async(c,g)=>{if(g!==u)return;let p;try{p=await s.decodeAudioData(c.buffer)}catch{return}if(g!==u)return;const h=s.createBufferSource();h.buffer=p,h.connect(s.destination);const a=Math.max(s.currentTime,k);h.start(a),k=a+p.duration,i.add(h),h.onended=()=>{i.delete(h)}},d=c=>{const g=Uint8Array.from(c),p=u;l=l.then(()=>y(g,p))},m=()=>{u+=1;for(const c of i)try{c.stop()}catch{}i.clear(),k=s.currentTime};return{enqueue:d,interrupt:m,stop:()=>{m(),s.close()}}},F=1,se=.01,oe=1200,ae=.15,ie=3,de=e=>{const{createMicrophone:r=ne,createSpeaker:s=re,createSocket:i,interruptChunks:k=ie,interruptThreshold:l=ae,silenceDurationMs:u=oe,silenceThreshold:y=se,threadKey:d,voice:m}=e,c=V(e.client),g=e.destroyRef===void 0,p=e.destroyRef??B(K),h=q(g),a=T("idle"),v=T(!1),_=T(""),S=T(""),x=T(0),R=T(!1),w=T(void 0);let o,b=!1;const M=t=>{const n=o?.socket;return n?.readyState===F?(n.send(JSON.stringify(t)),!0):!1},E=()=>{const t=o;if(o=void 0,t){t.unwatchIdentity?.(),t.microphone?.stop(),t.speaker?.stop(),t.socket.onmessage=null,t.socket.onerror=null,t.socket.onclose=null;try{t.socket.close()}catch{}}b=!1,v.set(!1),a.set("idle"),x.set(0)},W=E,N=t=>{const n=o;switch(t.type){case"assistant_delta":{n&&(n.speaking=!0),a.set("speaking"),S.update(I=>I+t.text);break}case"assistant_done":{n&&(n.awaitingTurn=!1,n.speaking=!1),S.set(t.text),a.set("listening");break}case"error":{n&&(n.awaitingTurn=!1,n.speaking=!1),w.set(new Error(t.message)),a.set("listening");break}case"interrupted":{n&&(n.awaitingTurn=!1,n.speaking=!1,n.suppressAudio=!1),n?.speaker?.interrupt(),a.set("listening");break}case"ready":{n&&(n.audioFormat=t.audioFormat,n.suppressAudio=!1),v.set(!0),a.set("listening");break}case"user_transcript":{n&&(n.suppressAudio=!1),_.set(t.text),S.set(""),a.set("thinking");break}}},O=t=>{const n=o;!n||n.suppressAudio||(n.speaker??=s({audioFormat:n.audioFormat}),n.speaking=!0,a.set("speaking"),n.speaker.enqueue(t))},P=async()=>{if(o||b)return;b=!0,w.set(void 0),_.set(""),S.set("");let t;try{const n=z({agent:G(m.__lunoraRef),httpUrl:c.url,threadKey:typeof d=="function"?d():d,wsUrl:c.wsUrl}),I=i??(f=>{const C=c.getWebSocketImpl();if(!C)throw new Error("voiceAgent: no WebSocket implementation available (pass createSocket explicitly)");return new C(f)}),A=h(()=>I(n));A.binaryType="arraybuffer",t={audioFormat:"mp3",microphone:void 0,socket:A,speaker:void 0,speaking:!1,awaitingTurn:!1,suppressAudio:!1,unwatchIdentity:void 0},o=t,t.unwatchIdentity=Y(c,"voiceAgent",f=>{o===t&&(w.set(f),E())}),A.onmessage=f=>{if(typeof f.data=="string"){try{N(JSON.parse(f.data))}catch{}return}O(new Uint8Array(f.data))},A.onerror=()=>{w.set(new Error("voiceAgent: voice socket error"))},A.onclose=f=>{if(o!==t)return;const C=Q("voiceAgent",f);C&&w.set(C),E()};const U=await h(async()=>r({interruptChunks:k,interruptThreshold:l,isTurnActive:()=>(o?.speaking??!1)||(o?.awaitingTurn??!1),onAudio:f=>{A.readyState===F&&A.send(f)},onInterrupt:()=>{M({type:"interrupt"}),o?.speaker?.interrupt(),o&&(o.awaitingTurn=!1,o.speaking=!1,o.suppressAudio=!0),a.set("listening")},onLevel:f=>{x.set(f)},onSilence:()=>{M({type:"commit"}),o&&(o.awaitingTurn=!0),a.set("thinking")},silenceDurationMs:u,silenceThreshold:y}));o===t?(t.microphone=U,R.set(!1),t.speaking||a.set("listening")):U.stop()}catch(n){o===t&&(w.set(n instanceof Error?n:new Error(String(n))),E())}finally{b=!1}},H=()=>{const t=!R();return o?.microphone?.setMuted(t),R.set(t),t},$=t=>{M({text:t,type:"text"})&&(o&&(o.awaitingTurn=!0),a.set("thinking"))};return p.onDestroy(E),{audioLevel:x.asReadonly(),connected:v.asReadonly(),endCall:W,error:w.asReadonly(),interimTranscript:S.asReadonly(),isMuted:R.asReadonly(),sendText:$,startCall:P,status:a.asReadonly(),toggleMute:H,transcript:_.asReadonly()}};export{de as voiceAgent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/angular",
3
- "version": "1.0.0-alpha.60",
3
+ "version": "1.0.0-alpha.62",
4
4
  "description": "Angular reactive adapter for Lunora — signal-based live queries and mutations",
5
5
  "keywords": [
6
6
  "angular",
@@ -53,8 +53,8 @@
53
53
  "access": "public"
54
54
  },
55
55
  "dependencies": {
56
- "@lunora/client": "1.0.0-alpha.76",
57
- "@lunora/ratelimit": "1.0.0-alpha.38",
56
+ "@lunora/client": "1.0.0-alpha.79",
57
+ "@lunora/ratelimit": "1.0.0-alpha.39",
58
58
  "@visulima/storage-client": "1.0.2"
59
59
  },
60
60
  "peerDependencies": {
@@ -1 +0,0 @@
1
- import{computed as R,inject as Q,DestroyRef as V,signal as L}from"@angular/core";import{initialPages as Z,derivePaginationStatus as U,applyLoadMore as v,rebalance as tt}from"@lunora/client/pagination";import{resolveLunoraClient as z}from"./LUNORA_CLIENT-B0toApHY.mjs";import{s as G,a as et}from"./platform-R29Vk-0v.mjs";const nt=/["\\\u0000-\u001F\uD800-\uDFFF]/,J=t=>nt.test(t)?JSON.stringify(t):`"${t}"`,$=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return J(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let r="[";for(let s=0;s<t.length;s++)s>0&&(r+=","),r+=$(t[s]);return r+"]"}const n=Object.getPrototypeOf(t);if(n!==null&&n!==Object.prototype){const r=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=t,i=Object.keys(o).sort();let c="{",e=!0;for(const r of i){const s=o[r];s!==void 0&&(e?e=!1:c+=",",c+=J(r),c+=":",c+=$(s))}return c+"}"},D=t=>{let n="";for(let i=0;i<t.length;i+=32768)n+=String.fromCharCode(...t.subarray(i,i+32768));return btoa(n)},d="$lunora.wire$",W=64,rt="__proto__",ot=t=>{if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===null||n===Object.prototype},S=(t,n=0)=>{if(n>W)throw new RangeError(`wire-codec: value nesting exceeds the ${W}-level limit`);if(t===void 0)return[d,"undefined"];if(t===null)return null;const o=typeof t;if(o==="bigint")return[d,"bigint",t.toString()];if(o==="number"){const e=t;return Number.isNaN(e)?[d,"nan"]:e===1/0?[d,"inf"]:e===-1/0?[d,"-inf"]:e}if(o!=="object")return t;if(t instanceof Date)return[d,"date",S(t.getTime(),n+1)];if(t instanceof Error){const e=t,r={};for(const u of Object.keys(e))e[u]!==void 0&&(r[u]=S(e[u],n+1));const s=[d,"error",e.name,e.message,r];return e.cause!==void 0&&s.push(S(e.cause,n+1)),s}if(t instanceof URL)return[d,"url",t.href];if(t instanceof Map)return[d,"map",[...t.entries()].map(([e,r])=>[S(e,n+1),S(r,n+1)])];if(t instanceof Set)return[d,"set",[...t].map(e=>S(e,n+1))];if(t instanceof ArrayBuffer)return[d,"bytes",D(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){const e=t,r=e.constructor.name,s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return r==="Uint8Array"?[d,"bytes",D(s)]:[d,"bytes",D(s),r]}if(Array.isArray(t)){const e=t.map(r=>S(r,n+1));return e.length>0&&e[0]===d?[d,"arr",e]:e}if(!ot(t)){const e=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const i=t,c={};for(const e of Object.keys(i)){const r=i[e];if(r===void 0)continue;const s=S(r,n+1);e===rt?Object.defineProperty(c,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):c[e]=s}return c},st=t=>$(S(t)),K=(t,n)=>`${t}::${st(n)}`,M=(t,n)=>({...n,paginationOpts:{cursor:t.lower,endCursor:t.upper,numItems:t.numItems}}),q=(t,n,o,i)=>{const c=z(o.client),e=o.destroyRef===void 0&&i===void 0,{initialNumItems:r,shardKey:s}=o,u=t.__lunoraRef,p=n==="skip"?{}:n,a=L(Z(r)),E=L([]),B=L("LoadingFirstPage"),A=L(void 0),k=new Map,m=new Map,C=new Set,N=()=>{const b=a().map(f=>{const l=K(u,M(f,p));return m.get(l)});E.set(b);const{status:P}=U(n==="skip",b);B.set(P)},X=(w,b)=>{const P=f=>K(u,M(f,p));for(const f of b){const l=P(f);if(m.has(l))continue;const g=w.find(y=>y.lower===f.lower);if(g){const y=m.get(P(g));y&&m.set(l,y)}}},Y=w=>{const b=new Set;for(const f of w)b.add(K(u,M(f,p)));for(const[f,l]of k)b.has(l.currentKey)||(l.unsub(),k.delete(f),m.delete(l.currentKey));const P=new Set([...k.values()].map(f=>f.currentKey));for(const f of w){const l=M(f,p),g=K(u,l);if(P.has(g))continue;const y={currentKey:g,unsub:void 0};C.add(g);const x=c.subscribe(t,l,O=>{if(m.set(y.currentKey,O),C.delete(y.currentKey),A.set(void 0),N(),C.size===0){const h=a(),j=tt(h,E());j&&(X(h,j),a.set(j),F(j),N())}},{onError:O=>{C.delete(g),A.set(O);const h=a(),j=h.at(-1);h.length>1&&j&&!m.has(g)&&K(u,M(j,p))===g&&(a.set(h.slice(0,-1)),F(a())),N(),o.onError?.(O)},shardKey:s});y.unsub=x,k.set(g,y),P.add(g)}};let I=!1,_=!1;const F=w=>{if(I){_=!0;return}I=!0;try{let b=w;do _=!1,Y(b),b=a();while(_)}finally{I=!1}};n!=="skip"&&G(e)&&F(a()),N();const T=()=>{for(const w of k.values())w.unsub();k.clear(),m.clear()};return i===void 0?(o.destroyRef??Q(V)).onDestroy(T):i(T),{error:A,loadMore:w=>{if(n==="skip")return;const{nextCursor:b,status:P}=U(!1,E());if(P!=="CanLoadMore")return;const f=v(a(),b,w);if(!f)return;const l=a().at(-1),g=f.at(-2);if(l&&g){const y=K(u,M(l,p)),x=K(u,M(g,p)),O=k.get(y);if(O&&y!==x){const h=m.get(y);h&&m.set(x,h),O.unsub(),k.delete(y),m.delete(y)}}A.set(void 0),a.set(f),F(a()),N()},pageResults:E,status:B}},H=(t,n,o)=>{if(typeof n!="function")return q(t,n,o);const i=z(o.client),c=o.destroyRef===void 0,e=o.destroyRef??Q(V),r=L(void 0);return G(c)&&et(n,{destroyRef:e,injector:o.injector},(s,u)=>{const p=[];r.set(q(t,s,{...o,client:i},a=>p.push(a))),u(()=>{for(const a of p)a()})}),{error:R(()=>r()?.error()),loadMore:s=>{r()?.loadMore(s)},pageResults:R(()=>r()?.pageResults()??[]),status:R(()=>r()?.status()??"LoadingFirstPage")}},yt=(t,n,o)=>{const i=H(t,n,o),c=R(()=>i.pageResults().flatMap(r=>r?.page??[])),e=R(()=>{const r=i.status();return r==="LoadingFirstPage"||r==="LoadingMore"});return{error:i.error,isLoading:e,loadMore:i.loadMore,results:c,status:i.status}},dt=(t,n,o)=>{const{initialNumItems:i}=o,c=H(t,n,o),e=R(()=>c.pageResults().flatMap(a=>a?[a.page]:[])),r=R(()=>c.status()==="LoadingFirstPage"),s=R(()=>c.status()==="CanLoadMore"),u=R(()=>c.status()==="LoadingMore"),p=a=>{c.loadMore(a??i)};return{error:c.error,fetchNextPage:p,hasNextPage:s,isFetchingNextPage:u,isLoading:r,pages:e,status:c.status}};export{dt as infiniteQuery,yt as paginatedQuery};
@@ -1 +0,0 @@
1
- import{inject as B,DestroyRef as K,signal as S}from"@angular/core";import{resolveLunoraClient as q}from"./LUNORA_CLIENT-B0toApHY.mjs";import{o as V}from"./platform-R29Vk-0v.mjs";const L="/_lunora/ws",j="/_lunora/voice/",J=4001,I=e=>e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e,G=e=>{const s=e.startsWith("agents:")?e.slice(7):e;return s.endsWith("Voice")?s.slice(0,-5):s},X=(e,s)=>{if(s===void 0||s==="")return I(e);if(s.endsWith(L))return s.slice(0,-L.length);try{return new URL(s).origin}catch{return I(e)}},z=e=>{const s=X(e.httpUrl,e.wsUrl),o=s.endsWith("/")?s.slice(0,-1):s,i=new URLSearchParams({threadKey:e.threadKey});return`${o}${j}${encodeURIComponent(e.agent)}?${i.toString()}`},Q=(e,s)=>{if(s?.code===J)return new Error(`${e}: authentication token expired — refresh the credential and start a new call`)},Y=16e3,Z=e=>{if(e.length===0)return 0;let s=0;for(const o of e)s+=o*o;return Math.sqrt(s/e.length)},ee=(e,s)=>{const o=s/Y,i=o>1?Math.floor(e.length/o):e.length,g=new ArrayBuffer(i*2),u=new DataView(g);for(let c=0;c<i;c+=1){const m=e[Math.floor(c*o)]??0,d=Math.max(-1,Math.min(1,m));u.setInt16(c*2,d<0?d*32768:d*32767,!0)}return new Uint8Array(g)},te=async e=>{const s=globalThis,o=s.navigator?.mediaDevices?.getUserMedia.bind(s.navigator.mediaDevices),i=s.AudioContext??s.webkitAudioContext;if(!o||!i)throw new Error("voiceAgent: microphone capture requires getUserMedia + AudioContext (no browser audio available)");const g=await o({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),u=new i,c=u.createMediaStreamSource(g),m=u.createScriptProcessor(4096,1,1);let d=!1,y=!1,l=0,f=0;return m.onaudioprocess=p=>{const h=p.inputBuffer.getChannelData(0),r=d?0:Z(h);if(e.onLevel(r),d)return;if(e.onAudio(ee(h,u.sampleRate)),e.isSpeaking()){f=r>=e.interruptThreshold?f+1:0,f>=e.interruptChunks&&(f=0,e.onInterrupt());return}f=0;const v=h.length/u.sampleRate*1e3;if(r>=e.silenceThreshold){y=!0,l=0;return}y&&(l+=v,l>=e.silenceDurationMs&&(y=!1,l=0,e.onSilence()))},c.connect(m),m.connect(u.destination),{setMuted:p=>{d=p},stop:()=>{m.disconnect(),c.disconnect();for(const p of g.getTracks())p.stop();u.close()}}},ne=()=>{const e=globalThis,s=e.AudioContext??e.webkitAudioContext;if(!s)throw new Error("voiceAgent: audio playback requires AudioContext (no browser audio available)");const o=new s,i=new Set;let g=0,u=Promise.resolve(),c=0;const m=async(l,f)=>{if(f!==c)return;let p;try{p=await o.decodeAudioData(l.buffer)}catch{return}if(f!==c)return;const h=o.createBufferSource();h.buffer=p,h.connect(o.destination);const r=Math.max(o.currentTime,g);h.start(r),g=r+p.duration,i.add(h),h.onended=()=>{i.delete(h)}},d=l=>{const f=Uint8Array.from(l),p=c;u=u.then(()=>m(f,p))},y=()=>{c+=1;for(const l of i)try{l.stop()}catch{}i.clear(),g=o.currentTime};return{enqueue:d,interrupt:y,stop:()=>{y(),o.close()}}},F=1,se=.01,oe=1200,re=.15,ae=3,ue=e=>{const{createMicrophone:s=te,createSpeaker:o=ne,createSocket:i,interruptChunks:g=ae,interruptThreshold:u=re,silenceDurationMs:c=oe,silenceThreshold:m=se,threadKey:d,voice:y}=e,l=q(e.client),f=e.destroyRef===void 0,p=e.destroyRef??B(K),h=V(f),r=S("idle"),v=S(!1),_=S(""),E=S(""),x=S(0),R=S(!1),w=S(void 0);let a,T=!1;const M=t=>{const n=a?.socket;return n?.readyState===F?(n.send(JSON.stringify(t)),!0):!1},b=()=>{const t=a;if(a=void 0,t){t.microphone?.stop(),t.speaker?.stop(),t.socket.onmessage=null,t.socket.onerror=null,t.socket.onclose=null;try{t.socket.close()}catch{}}T=!1,v.set(!1),r.set("idle"),x.set(0)},W=b,N=t=>{const n=a;switch(t.type){case"assistant_delta":{n&&(n.speaking=!0),r.set("speaking"),E.update(U=>U+t.text);break}case"assistant_done":{n&&(n.speaking=!1),E.set(t.text),r.set("listening");break}case"error":{n&&(n.speaking=!1),w.set(new Error(t.message)),r.set("listening");break}case"interrupted":{n&&(n.speaking=!1,n.suppressAudio=!1),n?.speaker?.interrupt(),r.set("listening");break}case"ready":{n&&(n.audioFormat=t.audioFormat,n.suppressAudio=!1),v.set(!0),r.set("listening");break}case"user_transcript":{n&&(n.suppressAudio=!1),_.set(t.text),E.set(""),r.set("thinking");break}}},O=t=>{const n=a;!n||n.suppressAudio||(n.speaker??=o({audioFormat:n.audioFormat}),n.speaking=!0,r.set("speaking"),n.speaker.enqueue(t))},P=async()=>{if(a||T)return;T=!0,w.set(void 0),_.set(""),E.set("");let t;try{const n=z({agent:G(y.__lunoraRef),httpUrl:l.url,threadKey:typeof d=="function"?d():d,wsUrl:l.wsUrl}),U=i??(k=>{const C=l.getWebSocketImpl();if(!C)throw new Error("voiceAgent: no WebSocket implementation available (pass createSocket explicitly)");return new C(k)}),A=h(()=>U(n));A.binaryType="arraybuffer",t={audioFormat:"mp3",microphone:void 0,socket:A,speaker:void 0,speaking:!1,suppressAudio:!1},a=t,A.onmessage=k=>{if(typeof k.data=="string"){try{N(JSON.parse(k.data))}catch{}return}O(new Uint8Array(k.data))},A.onerror=()=>{w.set(new Error("voiceAgent: voice socket error"))},A.onclose=k=>{if(a!==t)return;const C=Q("voiceAgent",k);C&&w.set(C),b()};const D=await h(async()=>s({interruptChunks:g,interruptThreshold:u,isSpeaking:()=>a?.speaking??!1,onAudio:k=>{A.readyState===F&&A.send(k)},onInterrupt:()=>{M({type:"interrupt"}),a?.speaker?.interrupt(),a&&(a.speaking=!1,a.suppressAudio=!0),r.set("listening")},onLevel:k=>{x.set(k)},onSilence:()=>{M({type:"commit"}),r.set("thinking")},silenceDurationMs:c,silenceThreshold:m}));a===t?(t.microphone=D,R.set(!1),t.speaking||r.set("listening")):D.stop()}catch(n){a===t&&(w.set(n instanceof Error?n:new Error(String(n))),b())}finally{T=!1}},H=()=>{const t=!R();return a?.microphone?.setMuted(t),R.set(t),t},$=t=>{M({text:t,type:"text"})&&r.set("thinking")};return p.onDestroy(b),{audioLevel:x.asReadonly(),connected:v.asReadonly(),endCall:W,error:w.asReadonly(),interimTranscript:E.asReadonly(),isMuted:R.asReadonly(),sendText:$,startCall:P,status:r.asReadonly(),toggleMute:H,transcript:_.asReadonly()}};export{ue as voiceAgent};