@lunora/svelte 1.0.0-alpha.111 → 1.0.0-alpha.113
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 +18 -2
- package/dist/index.d.ts +18 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/infiniteQuery-BFYk6edW.mjs +1 -0
- package/dist/packem_shared/voiceAgent-KSChAXsW.mjs +1 -0
- package/package.json +4 -4
- package/dist/packem_shared/infiniteQuery-CwF_9I0J.mjs +0 -1
- package/dist/packem_shared/voiceAgent-C1ouI6ls.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1051,8 +1051,24 @@ interface MicrophoneConfig {
|
|
|
1051
1051
|
interruptChunks: number;
|
|
1052
1052
|
/** RMS above which the user is considered to be barging in while the agent speaks. */
|
|
1053
1053
|
interruptThreshold: number;
|
|
1054
|
-
/**
|
|
1055
|
-
|
|
1054
|
+
/**
|
|
1055
|
+
* `true` from the moment a turn is committed until it completes — the whole
|
|
1056
|
+
* `thinking` + `speaking` window, not just the audible half.
|
|
1057
|
+
*
|
|
1058
|
+
* It gates BOTH branches below, and the wider span is the point. Gated only
|
|
1059
|
+
* on "audibly speaking", turn detection kept running through the entire
|
|
1060
|
+
* STT+LLM window after a `commit`: room noise at the (deliberately low)
|
|
1061
|
+
* `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
|
|
1062
|
+
* `commit`, and the DO refused it with "a turn is already in progress" —
|
|
1063
|
+
* a refusal that returns before draining the audio buffer, so the PCM
|
|
1064
|
+
* captured since the first commit leaked into the next utterance.
|
|
1065
|
+
*
|
|
1066
|
+
* A genuine barge-in still works in that window: it routes through the
|
|
1067
|
+
* `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
|
|
1068
|
+
* `interruptThreshold` — an order of magnitude above `silenceThreshold` —
|
|
1069
|
+
* and `interrupt` is exactly what the DO tells the client to send.
|
|
1070
|
+
*/
|
|
1071
|
+
isTurnActive: () => boolean;
|
|
1056
1072
|
/** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
|
|
1057
1073
|
onAudio: (pcm: Uint8Array) => void;
|
|
1058
1074
|
/** A barge-in was detected (RMS spike while the agent is speaking). */
|
package/dist/index.d.ts
CHANGED
|
@@ -1051,8 +1051,24 @@ interface MicrophoneConfig {
|
|
|
1051
1051
|
interruptChunks: number;
|
|
1052
1052
|
/** RMS above which the user is considered to be barging in while the agent speaks. */
|
|
1053
1053
|
interruptThreshold: number;
|
|
1054
|
-
/**
|
|
1055
|
-
|
|
1054
|
+
/**
|
|
1055
|
+
* `true` from the moment a turn is committed until it completes — the whole
|
|
1056
|
+
* `thinking` + `speaking` window, not just the audible half.
|
|
1057
|
+
*
|
|
1058
|
+
* It gates BOTH branches below, and the wider span is the point. Gated only
|
|
1059
|
+
* on "audibly speaking", turn detection kept running through the entire
|
|
1060
|
+
* STT+LLM window after a `commit`: room noise at the (deliberately low)
|
|
1061
|
+
* `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
|
|
1062
|
+
* `commit`, and the DO refused it with "a turn is already in progress" —
|
|
1063
|
+
* a refusal that returns before draining the audio buffer, so the PCM
|
|
1064
|
+
* captured since the first commit leaked into the next utterance.
|
|
1065
|
+
*
|
|
1066
|
+
* A genuine barge-in still works in that window: it routes through the
|
|
1067
|
+
* `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
|
|
1068
|
+
* `interruptThreshold` — an order of magnitude above `silenceThreshold` —
|
|
1069
|
+
* and `interrupt` is exactly what the DO tells the client to send.
|
|
1070
|
+
*/
|
|
1071
|
+
isTurnActive: () => boolean;
|
|
1056
1072
|
/** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
|
|
1057
1073
|
onAudio: (pcm: Uint8Array) => void;
|
|
1058
1074
|
/** A barge-in was detected (RMS spike while the agent is speaking). */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{action as t}from"./packem_shared/action-SjeZUGhX.mjs";import{agent as a}from"./packem_shared/agent-WMVWf1Ks.mjs";import{agentChat as f}from"./packem_shared/agentChat-CJ048ZZl.mjs";import{agentState as n}from"./packem_shared/agentState-CAqcW2tF.mjs";import{agentToolEvents as i}from"./packem_shared/agentToolEvents-Dyu5BFZn.mjs";import{auth as g,authGate as s}from"./packem_shared/auth-Bew4W5n1.mjs";import{connectionStatus as l}from"./packem_shared/connectionStatus-D9A79Eqw.mjs";import{getLunoraClient as h,setLunoraClient as y}from"./packem_shared/getLunoraClient-DU7BmZy1.mjs";import{flag as L,flags as v}from"./packem_shared/flag-Csh9LBiO.mjs";import{hydratePreloaded as S}from"./packem_shared/hydratePreloaded-Douu4xsv.mjs";import{mutation as q}from"./packem_shared/mutation-DLBr5Op1.mjs";import{mutator as E}from"./packem_shared/mutator-DECDuo94.mjs";import{infiniteQuery as P,paginatedQuery as T}from"./packem_shared/infiniteQuery-
|
|
1
|
+
import{action as t}from"./packem_shared/action-SjeZUGhX.mjs";import{agent as a}from"./packem_shared/agent-WMVWf1Ks.mjs";import{agentChat as f}from"./packem_shared/agentChat-CJ048ZZl.mjs";import{agentState as n}from"./packem_shared/agentState-CAqcW2tF.mjs";import{agentToolEvents as i}from"./packem_shared/agentToolEvents-Dyu5BFZn.mjs";import{auth as g,authGate as s}from"./packem_shared/auth-Bew4W5n1.mjs";import{connectionStatus as l}from"./packem_shared/connectionStatus-D9A79Eqw.mjs";import{getLunoraClient as h,setLunoraClient as y}from"./packem_shared/getLunoraClient-DU7BmZy1.mjs";import{flag as L,flags as v}from"./packem_shared/flag-Csh9LBiO.mjs";import{hydratePreloaded as S}from"./packem_shared/hydratePreloaded-Douu4xsv.mjs";import{mutation as q}from"./packem_shared/mutation-DLBr5Op1.mjs";import{mutator as E}from"./packem_shared/mutator-DECDuo94.mjs";import{infiniteQuery as P,paginatedQuery as T}from"./packem_shared/infiniteQuery-BFYk6edW.mjs";import{presence as k}from"./packem_shared/presence-BcBuOI0s.mjs";import{query as z}from"./packem_shared/query-BMl8EN8S.mjs";import{rateLimit as D}from"./packem_shared/rateLimit-Cli38qWO.mjs";import{stream as H}from"./packem_shared/stream-DGLI262b.mjs";import{subscription as J}from"./packem_shared/subscription-B1x2xDOl.mjs";import{voiceAgent as M}from"./packem_shared/voiceAgent-KSChAXsW.mjs";export{t as action,a as agent,f as agentChat,n as agentState,i as agentToolEvents,g as auth,s as authGate,l as connectionStatus,L as flag,v as flags,h as getLunoraClient,S as hydratePreloaded,P as infiniteQuery,q as mutation,E as mutator,T as paginatedQuery,k as presence,z as query,D as rateLimit,y as setLunoraClient,H as stream,J as subscription,M as voiceAgent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{initialPages as J,derivePaginationStatus as W,applyLoadMore as Z,rebalance as v}from"@lunora/client/pagination";import{derived as x,writable as B,readable as ee,get as L}from"svelte/store";import{getLunoraClient as G}from"./getLunoraClient-DU7BmZy1.mjs";import{i as H}from"./is-function-reference-abFdrAae.mjs";import{i as te,s as re}from"./subscribe-reactive-args-DYKqoWhw.mjs";const ne=/["\\\u0000-\u001F\uD800-\uDFFF]/,q=e=>ne.test(e)?JSON.stringify(e):`"${e}"`,D=e=>{if(e===void 0)return"null";if(typeof e=="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 e=="number"){if(Number.isNaN(e))return"nan";if(e===1/0)return"inf";if(e===-1/0)return"-inf";if(Object.is(e,-0))return"-0"}if(typeof e=="string")return q(e);if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e)){let s="[";for(let n=0;n<e.length;n++)n>0&&(s+=","),s+=D(e[n]);return s+"]"}const r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype){const s=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${s} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const a=e,u=Object.keys(a).sort();let o="{",t=!0;for(const s of u){const n=a[s];n!==void 0&&(t?t=!1:o+=",",o+=q(s),o+=":",o+=D(n))}return o+"}"},T=e=>{let r="";for(let u=0;u<e.length;u+=32768)r+=String.fromCharCode(...e.subarray(u,u+32768));return btoa(r)},g="$lunora.wire$",Q=64,z="__proto__",se=e=>{if(e===null||typeof e!="object")return!1;const r=Object.getPrototypeOf(e);return r===null||r===Object.prototype},E=(e,r=0)=>{if(r>Q)throw new RangeError(`wire-codec: value nesting exceeds the ${Q}-level limit`);if(e===void 0)return[g,"undefined"];if(e===null)return null;const a=typeof e;if(a==="bigint")return[g,"bigint",e.toString()];if(a==="number"){const t=e;return Number.isNaN(t)?[g,"nan"]:t===1/0?[g,"inf"]:t===-1/0?[g,"-inf"]:t}if(a!=="object")return e;if(e instanceof Date)return[g,"date",E(e.getTime(),r+1)];if(e instanceof Error){const t=e,s={};for(const f of Object.keys(t)){if(t[f]===void 0)continue;const b=E(t[f],r+1);f===z?Object.defineProperty(s,f,{configurable:!0,enumerable:!0,value:b,writable:!0}):s[f]=b}const n=[g,"error",t.name,t.message,s];return t.cause!==void 0&&n.push(E(t.cause,r+1)),n}if(e instanceof URL)return[g,"url",e.href];if(e instanceof Map)return[g,"map",[...e.entries()].map(([t,s])=>[E(t,r+1),E(s,r+1)])];if(e instanceof Set)return[g,"set",[...e].map(t=>E(t,r+1))];if(e instanceof ArrayBuffer)return[g,"bytes",T(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const t=e,s=t.constructor.name,n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return s==="Uint8Array"?[g,"bytes",T(n)]:[g,"bytes",T(n),s]}if(Array.isArray(e)){const t=e.map(s=>E(s,r+1));return t.length>0&&t[0]===g?[g,"arr",t]:t}if(!se(e)){const t=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} 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 u=e,o={};for(const t of Object.keys(u)){const s=u[t];if(s===void 0)continue;const n=E(s,r+1);t===z?Object.defineProperty(o,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):o[t]=n}return o},oe=e=>D(E(e)),_=(e,r)=>({...r,paginationOpts:{cursor:e.lower,endCursor:e.upper,numItems:e.numItems}}),K=(e,r)=>`${e}::${oe(r)}`,V=(e,r,a,u)=>{const{initialNumItems:o,onError:t,shardKey:s}=u,n=B(J(o)),f=B(),b=B([]),l=new Map,m=new Map,P=new Set;let c=te(a)?"skip":a;const A=()=>{if(c==="skip"){b.set([]);return}const y=c,h=L(n).map(k=>{const i=K(r.__lunoraRef,_(k,y));return l.get(i)});b.set(h)},j=(y,h)=>{if(c==="skip")return;const k=c,i=w=>K(r.__lunoraRef,_(w,k));for(const w of h){const d=i(w);if(l.has(d))continue;const M=y.find(R=>R.lower===w.lower);if(M){const R=l.get(i(M));R&&l.set(d,R)}}},O=()=>{if(c==="skip"){for(const i of m.values())i();m.clear(),b.set([]);return}const y=c,h=L(n),k=new Set;for(const i of h)k.add(K(r.__lunoraRef,_(i,y)));for(const[i,w]of m)k.has(i)||(w(),m.delete(i),P.delete(i),l.delete(i));for(const i of h){const w=_(i,y),d=K(r.__lunoraRef,w);if(m.has(d))continue;P.add(d);const M=e.subscribe(r,w,R=>{if(l.set(d,R),P.delete(d),f.set(void 0),A(),P.size===0){const S=L(n),N=v(S,L(b));N&&(j(S,N),n.set(N),p(),A())}},{onError:R=>{P.delete(d),f.set(R);const S=L(n),N=S.at(-1);S.length>1&&N&&!l.has(d)&&K(r.__lunoraRef,_(N,y))===d&&(n.set(S.slice(0,-1)),p(),A()),t?.(R)},shardKey:s});m.set(d,M)}};let C=!1,I=!1;const p=()=>{if(C){I=!0;return}C=!0;try{do I=!1,O();while(I)}finally{C=!1}},$=()=>{for(const y of m.values())y();m.clear(),l.clear(),P.clear()},F=ee([],y=>{const h=b.subscribe(y),k=re(a,i=>(c=i,p(),A(),()=>{$(),n.set(J(o)),f.set(void 0)}));return()=>{k(),h(),b.set([])}}),X=x(F,y=>W(c==="skip",y).status),Y=y=>{if(c==="skip")return;const h=L(b),{nextCursor:k,status:i}=W(!1,h);if(i!=="CanLoadMore")return;const w=L(n),d=Z(w,k,y);if(!d)return;const M=w.at(-1),R=d.at(-2);if(M&&R){const S=K(r.__lunoraRef,_(M,c)),N=K(r.__lunoraRef,_(R,c));if(S!==N){const U=l.get(S);U&&(l.set(N,U),l.delete(S))}}f.set(void 0),n.set(d),p(),A()};return{error:{subscribe:f.subscribe},loadMore:Y,pageResults:F,status:X}};function le(e,r,a,u){const o=!H(e),t=o?e:G(),s=o?r:e,n=o?a:r,f=o?u:a,{error:b,loadMore:l,pageResults:m,status:P}=V(t,s,n,f),c=x(m,j=>j.flatMap(O=>O?.page??[])),A=x(P,j=>j==="LoadingFirstPage"||j==="LoadingMore");return{error:b,isLoading:A,loadMore:l,results:c,status:P}}function ye(e,r,a,u){const o=!H(e),t=o?e:G(),s=o?r:e,n=o?a:r,f=o?u:a,{initialNumItems:b}=f,{error:l,loadMore:m,pageResults:P,status:c}=V(t,s,n,f),A=x(P,p=>p.flatMap($=>$?[$.page]:[])),j=x(c,p=>p==="LoadingFirstPage"),O=x(c,p=>p==="CanLoadMore"),C=x(c,p=>p==="LoadingMore");return{error:l,fetchNextPage:p=>{m(p??b)},hasNextPage:O,isFetchingNextPage:C,isLoading:j,pages:A,status:c}}export{ye as infiniteQuery,le as paginatedQuery};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{writable as A,get as H}from"svelte/store";import{isClient as V}from"./agent-WMVWf1Ks.mjs";import{getLunoraClient as $}from"./getLunoraClient-DU7BmZy1.mjs";const I="/_lunora/ws",O="/_lunora/voice/",B=4001,U=e=>e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e,q=e=>{const n=e.startsWith("agents:")?e.slice(7):e;return n.endsWith("Voice")?n.slice(0,-5):n},K=(e,n)=>{if(n===void 0||n==="")return U(e);if(n.endsWith(I))return n.slice(0,-I.length);try{return new URL(n).origin}catch{return U(e)}},J=e=>{const n=K(e.httpUrl,e.wsUrl),r=n.endsWith("/")?n.slice(0,-1):n,a=new URLSearchParams({threadKey:e.threadKey});return`${r}${O}${encodeURIComponent(e.agent)}?${a.toString()}`},G=(e,n)=>{if(n?.code===B)return new Error(`${e}: authentication token expired — refresh the credential and start a new call`)},X=(e,n,r)=>{const a=e.currentIdentity();return e.onAuthTokenChange(()=>{e.currentIdentity()!==a&&r(new Error(`${n}: the signed-in identity changed during the call — the session was ended; start a new call`))})},j=16e3,z=e=>{if(e.length===0)return 0;let n=0;for(const r of e)n+=r*r;return Math.sqrt(n/e.length)},Q=(e,n)=>{const r=n/j,a=r>1?Math.floor(e.length/r):e.length,h=new ArrayBuffer(a*2),d=new DataView(h);for(let u=0;u<a;u+=1){const b=e[Math.floor(u*r)]??0,k=Math.max(-1,Math.min(1,b));d.setInt16(u*2,k<0?k*32768:k*32767,!0)}return new Uint8Array(h)},Y=async e=>{const n=globalThis,r=n.navigator?.mediaDevices?.getUserMedia.bind(n.navigator.mediaDevices),a=n.AudioContext??n.webkitAudioContext;if(!r||!a)throw new Error("useVoiceAgent: microphone capture requires getUserMedia + AudioContext (no browser audio available)");const h=await r({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),d=new a,u=d.createMediaStreamSource(h),b=d.createScriptProcessor(4096,1,1);let k=!1,w=!1,f=0,o=0;return b.onaudioprocess=c=>{const l=c.inputBuffer.getChannelData(0),g=k?0:z(l);if(e.onLevel(g),k)return;if(e.onAudio(Q(l,d.sampleRate)),e.isTurnActive()){o=g>=e.interruptThreshold?o+1:0,o>=e.interruptChunks&&(o=0,e.onInterrupt());return}o=0;const T=l.length/d.sampleRate*1e3;if(g>=e.silenceThreshold){w=!0,f=0;return}w&&(f+=T,f>=e.silenceDurationMs&&(w=!1,f=0,e.onSilence()))},u.connect(b),b.connect(d.destination),{setMuted:c=>{k=c},stop:()=>{b.disconnect(),u.disconnect();for(const c of h.getTracks())c.stop();d.close()}}},Z=()=>{const e=globalThis,n=e.AudioContext??e.webkitAudioContext;if(!n)throw new Error("useVoiceAgent: audio playback requires AudioContext (no browser audio available)");const r=new n,a=new Set;let h=0,d=Promise.resolve(),u=0;const b=async(f,o)=>{if(o!==u)return;let c;try{c=await r.decodeAudioData(f.buffer)}catch{return}if(o!==u)return;const l=r.createBufferSource();l.buffer=c,l.connect(r.destination);const g=Math.max(r.currentTime,h);l.start(g),h=g+c.duration,a.add(l),l.onended=()=>{a.delete(l)}},k=f=>{const o=Uint8Array.from(f),c=u;d=d.then(()=>b(o,c))},w=()=>{u+=1;for(const f of a)try{f.stop()}catch{}a.clear(),h=r.currentTime};return{enqueue:k,interrupt:w,stop:()=>{w(),r.close()}}},R=1,ee=.01,te=1200,ne=.15,se=3,re=(e,n)=>{const{createMicrophone:r=Y,createSpeaker:a=Z,createSocket:h,interruptChunks:d=se,interruptThreshold:u=ne,silenceDurationMs:b=te,silenceThreshold:k=ee,threadKey:w,voice:f}=n,o=A("idle"),c=A(!1),l=A(""),g=A(""),T=A(0),v=A(!1),m=A();let i,E=!1;const _=t=>{const s=i?.socket;return s?.readyState===R?(s.send(JSON.stringify(t)),!0):!1},C=()=>{const t=i;if(i=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{}}E=!1,c.set(!1),o.set("idle"),T.set(0)},L=C,D=t=>{const s=i;switch(t.type){case"assistant_delta":{s&&(s.speaking=!0),o.set("speaking"),g.update(x=>x+t.text);break}case"assistant_done":{s&&(s.awaitingTurn=!1,s.speaking=!1),g.set(t.text),o.set("listening");break}case"error":{s&&(s.awaitingTurn=!1,s.speaking=!1),m.set(new Error(t.message)),o.set("listening");break}case"interrupted":{s&&(s.awaitingTurn=!1,s.speaking=!1,s.suppressAudio=!1),s?.speaker?.interrupt(),o.set("listening");break}case"ready":{s&&(s.audioFormat=t.audioFormat,s.suppressAudio=!1),c.set(!0),o.set("listening");break}case"user_transcript":{s&&(s.suppressAudio=!1),l.set(t.text),g.set(""),o.set("thinking");break}}},F=t=>{const s=i;!s||s.suppressAudio||(s.speaker??=a({audioFormat:s.audioFormat}),s.speaking=!0,o.set("speaking"),s.speaker.enqueue(t))},W=async()=>{if(i||E)return;E=!0,m.set(void 0),l.set(""),g.set("");let t;try{const s=J({agent:q(f.__lunoraRef),httpUrl:e.url,threadKey:w,wsUrl:e.wsUrl}),S=(h??(p=>{const y=e.getWebSocketImpl();if(!y)throw new Error("voiceAgent: no WebSocket implementation available (pass createSocket explicitly)");return new y(p)}))(s);S.binaryType="arraybuffer",t={audioFormat:"mp3",microphone:void 0,socket:S,speaker:void 0,speaking:!1,awaitingTurn:!1,suppressAudio:!1,unwatchIdentity:void 0},i=t,t.unwatchIdentity=X(e,"voiceAgent",p=>{i===t&&(m.set(p),C())}),S.onmessage=p=>{if(typeof p.data=="string"){try{D(JSON.parse(p.data))}catch{}return}F(new Uint8Array(p.data))},S.onerror=()=>{m.set(new Error("voiceAgent: voice socket error"))},S.onclose=p=>{if(i!==t)return;const y=G("voiceAgent",p);y&&m.set(y),C()};const M=await r({interruptChunks:d,interruptThreshold:u,isTurnActive:()=>(i?.speaking??!1)||(i?.awaitingTurn??!1),onAudio:p=>{S.readyState===R&&S.send(p)},onInterrupt:()=>{_({type:"interrupt"}),i?.speaker?.interrupt(),i&&(i.awaitingTurn=!1,i.speaking=!1,i.suppressAudio=!0),o.set("listening")},onLevel:p=>{T.set(p)},onSilence:()=>{_({type:"commit"}),i&&(i.awaitingTurn=!0),o.set("thinking")},silenceDurationMs:b,silenceThreshold:k});i===t?(t.microphone=M,v.set(!1),t.speaking||o.set("listening")):M.stop()}catch(s){i===t&&(m.set(s instanceof Error?s:new Error(String(s))),C())}finally{E=!1}},N=()=>{const t=!H(v);return i?.microphone?.setMuted(t),v.set(t),t},P=t=>{_({text:t,type:"text"})&&(i&&(i.awaitingTurn=!0),o.set("thinking"))};return{audioLevel:{subscribe:T.subscribe},connected:{subscribe:c.subscribe},endCall:L,error:{subscribe:m.subscribe},interimTranscript:{subscribe:g.subscribe},isMuted:{subscribe:v.subscribe},sendText:P,startCall:W,status:{subscribe:o.subscribe},toggleMute:N,transcript:{subscribe:l.subscribe}}};function ce(e,n){const r=V(e),a=r?e:$();return re(a,r?n:e)}export{ce as voiceAgent};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/svelte",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.113",
|
|
4
4
|
"description": "Svelte adapter for Lunora — live stores, optimistic mutations, and reactive loaders",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
"access": "public"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@lunora/client": "1.0.0-alpha.
|
|
58
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
59
|
-
"@lunora/ratelimit": "1.0.0-alpha.
|
|
57
|
+
"@lunora/client": "1.0.0-alpha.79",
|
|
58
|
+
"@lunora/errors": "1.0.0-alpha.32",
|
|
59
|
+
"@lunora/ratelimit": "1.0.0-alpha.39",
|
|
60
60
|
"@visulima/storage-client": "1.0.2"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{initialPages as J,derivePaginationStatus as W,applyLoadMore as Y,rebalance as Z}from"@lunora/client/pagination";import{derived as x,writable as B,readable as v,get as L}from"svelte/store";import{getLunoraClient as z}from"./getLunoraClient-DU7BmZy1.mjs";import{i as G}from"./is-function-reference-abFdrAae.mjs";import{i as ee,s as te}from"./subscribe-reactive-args-DYKqoWhw.mjs";const re=/["\\\u0000-\u001F\uD800-\uDFFF]/,q=e=>re.test(e)?JSON.stringify(e):`"${e}"`,D=e=>{if(e===void 0)return"null";if(typeof e=="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 e=="number"){if(Number.isNaN(e))return"nan";if(e===1/0)return"inf";if(e===-1/0)return"-inf";if(Object.is(e,-0))return"-0"}if(typeof e=="string")return q(e);if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e)){let s="[";for(let n=0;n<e.length;n++)n>0&&(s+=","),s+=D(e[n]);return s+"]"}const r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype){const s=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${s} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const a=e,f=Object.keys(a).sort();let o="{",t=!0;for(const s of f){const n=a[s];n!==void 0&&(t?t=!1:o+=",",o+=q(s),o+=":",o+=D(n))}return o+"}"},T=e=>{let r="";for(let f=0;f<e.length;f+=32768)r+=String.fromCharCode(...e.subarray(f,f+32768));return btoa(r)},d="$lunora.wire$",Q=64,ne="__proto__",se=e=>{if(e===null||typeof e!="object")return!1;const r=Object.getPrototypeOf(e);return r===null||r===Object.prototype},E=(e,r=0)=>{if(r>Q)throw new RangeError(`wire-codec: value nesting exceeds the ${Q}-level limit`);if(e===void 0)return[d,"undefined"];if(e===null)return null;const a=typeof e;if(a==="bigint")return[d,"bigint",e.toString()];if(a==="number"){const t=e;return Number.isNaN(t)?[d,"nan"]:t===1/0?[d,"inf"]:t===-1/0?[d,"-inf"]:t}if(a!=="object")return e;if(e instanceof Date)return[d,"date",E(e.getTime(),r+1)];if(e instanceof Error){const t=e,s={};for(const g of Object.keys(t))t[g]!==void 0&&(s[g]=E(t[g],r+1));const n=[d,"error",t.name,t.message,s];return t.cause!==void 0&&n.push(E(t.cause,r+1)),n}if(e instanceof URL)return[d,"url",e.href];if(e instanceof Map)return[d,"map",[...e.entries()].map(([t,s])=>[E(t,r+1),E(s,r+1)])];if(e instanceof Set)return[d,"set",[...e].map(t=>E(t,r+1))];if(e instanceof ArrayBuffer)return[d,"bytes",T(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const t=e,s=t.constructor.name,n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return s==="Uint8Array"?[d,"bytes",T(n)]:[d,"bytes",T(n),s]}if(Array.isArray(e)){const t=e.map(s=>E(s,r+1));return t.length>0&&t[0]===d?[d,"arr",t]:t}if(!se(e)){const t=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} 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 f=e,o={};for(const t of Object.keys(f)){const s=f[t];if(s===void 0)continue;const n=E(s,r+1);t===ne?Object.defineProperty(o,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):o[t]=n}return o},oe=e=>D(E(e)),_=(e,r)=>({...r,paginationOpts:{cursor:e.lower,endCursor:e.upper,numItems:e.numItems}}),K=(e,r)=>`${e}::${oe(r)}`,H=(e,r,a,f)=>{const{initialNumItems:o,onError:t,shardKey:s}=f,n=B(J(o)),g=B(),R=B([]),u=new Map,p=new Map,P=new Set;let c=ee(a)?"skip":a;const A=()=>{if(c==="skip"){R.set([]);return}const l=c,h=L(n).map(k=>{const i=K(r.__lunoraRef,_(k,l));return u.get(i)});R.set(h)},j=(l,h)=>{if(c==="skip")return;const k=c,i=m=>K(r.__lunoraRef,_(m,k));for(const m of h){const y=i(m);if(u.has(y))continue;const M=l.find(w=>w.lower===m.lower);if(M){const w=u.get(i(M));w&&u.set(y,w)}}},C=()=>{if(c==="skip"){for(const i of p.values())i();p.clear(),R.set([]);return}const l=c,h=L(n),k=new Set;for(const i of h)k.add(K(r.__lunoraRef,_(i,l)));for(const[i,m]of p)k.has(i)||(m(),p.delete(i),P.delete(i),u.delete(i));for(const i of h){const m=_(i,l),y=K(r.__lunoraRef,m);if(p.has(y))continue;P.add(y);const M=e.subscribe(r,m,w=>{if(u.set(y,w),P.delete(y),g.set(void 0),A(),P.size===0){const S=L(n),N=Z(S,L(R));N&&(j(S,N),n.set(N),b(),A())}},{onError:w=>{P.delete(y),g.set(w);const S=L(n),N=S.at(-1);S.length>1&&N&&!u.has(y)&&K(r.__lunoraRef,_(N,l))===y&&(n.set(S.slice(0,-1)),b(),A()),t?.(w)},shardKey:s});p.set(y,M)}};let I=!1,O=!1;const b=()=>{if(I){O=!0;return}I=!0;try{do O=!1,C();while(O)}finally{I=!1}},$=()=>{for(const l of p.values())l();p.clear(),u.clear(),P.clear()},F=v([],l=>{const h=R.subscribe(l),k=te(a,i=>(c=i,b(),A(),()=>{$(),n.set(J(o)),g.set(void 0)}));return()=>{k(),h(),R.set([])}}),V=x(F,l=>W(c==="skip",l).status),X=l=>{if(c==="skip")return;const h=L(R),{nextCursor:k,status:i}=W(!1,h);if(i!=="CanLoadMore")return;const m=L(n),y=Y(m,k,l);if(!y)return;const M=m.at(-1),w=y.at(-2);if(M&&w){const S=K(r.__lunoraRef,_(M,c)),N=K(r.__lunoraRef,_(w,c));if(S!==N){const U=u.get(S);U&&(u.set(N,U),u.delete(S))}}g.set(void 0),n.set(y),b(),A()};return{error:{subscribe:g.subscribe},loadMore:X,pageResults:F,status:V}};function le(e,r,a,f){const o=!G(e),t=o?e:z(),s=o?r:e,n=o?a:r,g=o?f:a,{error:R,loadMore:u,pageResults:p,status:P}=H(t,s,n,g),c=x(p,j=>j.flatMap(C=>C?.page??[])),A=x(P,j=>j==="LoadingFirstPage"||j==="LoadingMore");return{error:R,isLoading:A,loadMore:u,results:c,status:P}}function ye(e,r,a,f){const o=!G(e),t=o?e:z(),s=o?r:e,n=o?a:r,g=o?f:a,{initialNumItems:R}=g,{error:u,loadMore:p,pageResults:P,status:c}=H(t,s,n,g),A=x(P,b=>b.flatMap($=>$?[$.page]:[])),j=x(c,b=>b==="LoadingFirstPage"),C=x(c,b=>b==="CanLoadMore"),I=x(c,b=>b==="LoadingMore");return{error:u,fetchNextPage:b=>{p(b??R)},hasNextPage:C,isFetchingNextPage:I,isLoading:j,pages:A,status:c}}export{ye as infiniteQuery,le as paginatedQuery};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{writable as A,get as H}from"svelte/store";import{isClient as V}from"./agent-WMVWf1Ks.mjs";import{getLunoraClient as O}from"./getLunoraClient-DU7BmZy1.mjs";const U="/_lunora/ws",$="/_lunora/voice/",B=4001,R=e=>e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e,q=e=>{const t=e.startsWith("agents:")?e.slice(7):e;return t.endsWith("Voice")?t.slice(0,-5):t},K=(e,t)=>{if(t===void 0||t==="")return R(e);if(t.endsWith(U))return t.slice(0,-U.length);try{return new URL(t).origin}catch{return R(e)}},J=e=>{const t=K(e.httpUrl,e.wsUrl),r=t.endsWith("/")?t.slice(0,-1):t,i=new URLSearchParams({threadKey:e.threadKey});return`${r}${$}${encodeURIComponent(e.agent)}?${i.toString()}`},G=(e,t)=>{if(t?.code===B)return new Error(`${e}: authentication token expired — refresh the credential and start a new call`)},X=16e3,j=e=>{if(e.length===0)return 0;let t=0;for(const r of e)t+=r*r;return Math.sqrt(t/e.length)},z=(e,t)=>{const r=t/X,i=r>1?Math.floor(e.length/r):e.length,p=new ArrayBuffer(i*2),d=new DataView(p);for(let u=0;u<i;u+=1){const b=e[Math.floor(u*r)]??0,g=Math.max(-1,Math.min(1,b));d.setInt16(u*2,g<0?g*32768:g*32767,!0)}return new Uint8Array(p)},Q=async e=>{const t=globalThis,r=t.navigator?.mediaDevices?.getUserMedia.bind(t.navigator.mediaDevices),i=t.AudioContext??t.webkitAudioContext;if(!r||!i)throw new Error("useVoiceAgent: microphone capture requires getUserMedia + AudioContext (no browser audio available)");const p=await r({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),d=new i,u=d.createMediaStreamSource(p),b=d.createScriptProcessor(4096,1,1);let g=!1,m=!1,h=0,o=0;return b.onaudioprocess=a=>{const l=a.inputBuffer.getChannelData(0),f=g?0:j(l);if(e.onLevel(f),g)return;if(e.onAudio(z(l,d.sampleRate)),e.isSpeaking()){o=f>=e.interruptThreshold?o+1:0,o>=e.interruptChunks&&(o=0,e.onInterrupt());return}o=0;const E=l.length/d.sampleRate*1e3;if(f>=e.silenceThreshold){m=!0,h=0;return}m&&(h+=E,h>=e.silenceDurationMs&&(m=!1,h=0,e.onSilence()))},u.connect(b),b.connect(d.destination),{setMuted:a=>{g=a},stop:()=>{b.disconnect(),u.disconnect();for(const a of p.getTracks())a.stop();d.close()}}},Y=()=>{const e=globalThis,t=e.AudioContext??e.webkitAudioContext;if(!t)throw new Error("useVoiceAgent: audio playback requires AudioContext (no browser audio available)");const r=new t,i=new Set;let p=0,d=Promise.resolve(),u=0;const b=async(h,o)=>{if(o!==u)return;let a;try{a=await r.decodeAudioData(h.buffer)}catch{return}if(o!==u)return;const l=r.createBufferSource();l.buffer=a,l.connect(r.destination);const f=Math.max(r.currentTime,p);l.start(f),p=f+a.duration,i.add(l),l.onended=()=>{i.delete(l)}},g=h=>{const o=Uint8Array.from(h),a=u;d=d.then(()=>b(o,a))},m=()=>{u+=1;for(const h of i)try{h.stop()}catch{}i.clear(),p=r.currentTime};return{enqueue:g,interrupt:m,stop:()=>{m(),r.close()}}},L=1,Z=.01,ee=1200,te=.15,se=3,ne=(e,t)=>{const{createMicrophone:r=Q,createSpeaker:i=Y,createSocket:p,interruptChunks:d=se,interruptThreshold:u=te,silenceDurationMs:b=ee,silenceThreshold:g=Z,threadKey:m,voice:h}=t,o=A("idle"),a=A(!1),l=A(""),f=A(""),E=A(0),C=A(!1),w=A();let c,v=!1;const T=s=>{const n=c?.socket;return n?.readyState===L?(n.send(JSON.stringify(s)),!0):!1},_=()=>{const s=c;if(c=void 0,s){s.microphone?.stop(),s.speaker?.stop(),s.socket.onmessage=null,s.socket.onerror=null,s.socket.onclose=null;try{s.socket.close()}catch{}}v=!1,a.set(!1),o.set("idle"),E.set(0)},D=_,I=s=>{const n=c;switch(s.type){case"assistant_delta":{n&&(n.speaking=!0),o.set("speaking"),f.update(x=>x+s.text);break}case"assistant_done":{n&&(n.speaking=!1),f.set(s.text),o.set("listening");break}case"error":{n&&(n.speaking=!1),w.set(new Error(s.message)),o.set("listening");break}case"interrupted":{n&&(n.speaking=!1,n.suppressAudio=!1),n?.speaker?.interrupt(),o.set("listening");break}case"ready":{n&&(n.audioFormat=s.audioFormat,n.suppressAudio=!1),a.set(!0),o.set("listening");break}case"user_transcript":{n&&(n.suppressAudio=!1),l.set(s.text),f.set(""),o.set("thinking");break}}},F=s=>{const n=c;!n||n.suppressAudio||(n.speaker??=i({audioFormat:n.audioFormat}),n.speaking=!0,o.set("speaking"),n.speaker.enqueue(s))},W=async()=>{if(c||v)return;v=!0,w.set(void 0),l.set(""),f.set("");let s;try{const n=J({agent:q(h.__lunoraRef),httpUrl:e.url,threadKey:m,wsUrl:e.wsUrl}),S=(p??(k=>{const y=e.getWebSocketImpl();if(!y)throw new Error("voiceAgent: no WebSocket implementation available (pass createSocket explicitly)");return new y(k)}))(n);S.binaryType="arraybuffer",s={audioFormat:"mp3",microphone:void 0,socket:S,speaker:void 0,speaking:!1,suppressAudio:!1},c=s,S.onmessage=k=>{if(typeof k.data=="string"){try{I(JSON.parse(k.data))}catch{}return}F(new Uint8Array(k.data))},S.onerror=()=>{w.set(new Error("voiceAgent: voice socket error"))},S.onclose=k=>{if(c!==s)return;const y=G("voiceAgent",k);y&&w.set(y),_()};const M=await r({interruptChunks:d,interruptThreshold:u,isSpeaking:()=>c?.speaking??!1,onAudio:k=>{S.readyState===L&&S.send(k)},onInterrupt:()=>{T({type:"interrupt"}),c?.speaker?.interrupt(),c&&(c.speaking=!1,c.suppressAudio=!0),o.set("listening")},onLevel:k=>{E.set(k)},onSilence:()=>{T({type:"commit"}),o.set("thinking")},silenceDurationMs:b,silenceThreshold:g});c===s?(s.microphone=M,C.set(!1),s.speaking||o.set("listening")):M.stop()}catch(n){c===s&&(w.set(n instanceof Error?n:new Error(String(n))),_())}finally{v=!1}},N=()=>{const s=!H(C);return c?.microphone?.setMuted(s),C.set(s),s},P=s=>{T({text:s,type:"text"})&&o.set("thinking")};return{audioLevel:{subscribe:E.subscribe},connected:{subscribe:a.subscribe},endCall:D,error:{subscribe:w.subscribe},interimTranscript:{subscribe:f.subscribe},isMuted:{subscribe:C.subscribe},sendText:P,startCall:W,status:{subscribe:o.subscribe},toggleMute:N,transcript:{subscribe:l.subscribe}}};function ce(e,t){const r=V(e),i=r?e:O();return ne(i,r?t:e)}export{ce as voiceAgent};
|