@lunora/angular 1.0.0-alpha.21 → 1.0.0-alpha.210
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/README.md +42 -0
- package/dist/index.d.mts +229 -50
- package/dist/index.d.ts +229 -50
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/LUNORA_CLIENT-B0toApHY.mjs +1 -0
- package/dist/packem_shared/agent-DjMQf-yE.mjs +1 -0
- package/dist/packem_shared/agentChat-DyJrje49.mjs +1 -0
- package/dist/packem_shared/agentState-Bjqf9q2f.mjs +1 -0
- package/dist/packem_shared/agentToolEvents-VuBRpS6v.mjs +1 -0
- package/dist/packem_shared/auth-C3dB8sYS.mjs +1 -0
- package/dist/packem_shared/connectionStatus-UhmuwzMa.mjs +1 -0
- package/dist/packem_shared/flag-BDKBQGos.mjs +1 -0
- package/dist/packem_shared/hydratePreloaded-QPAo50Am.mjs +1 -0
- package/dist/packem_shared/infiniteQuery-DGYdgFHW.mjs +1 -0
- package/dist/packem_shared/liveQuery-eE9zMaxo.mjs +1 -0
- package/dist/packem_shared/mutate-BZvLQLyu.mjs +1 -0
- package/dist/packem_shared/mutator-DjG1yGk8.mjs +1 -0
- package/dist/packem_shared/platform-DGTu4Ucl.mjs +1 -0
- package/dist/packem_shared/presence-1T4-U8ij.mjs +1 -0
- package/dist/packem_shared/rateLimit-B3h9qzh-.mjs +1 -0
- package/dist/packem_shared/runAction-BfiPq4Xz.mjs +1 -0
- package/dist/packem_shared/stream-BuhiwhIH.mjs +1 -0
- package/dist/packem_shared/subscription-zJv48q6C.mjs +1 -0
- package/dist/packem_shared/voiceAgent-CH--tRWP.mjs +1 -0
- package/dist/server.d.mts +1 -0
- package/dist/server.d.ts +1 -0
- package/dist/server.mjs +1 -0
- package/dist/upload.mjs +1 -1
- package/package.json +9 -4
- package/dist/packem_shared/LUNORA_CLIENT-B0pGE0Tv.mjs +0 -1
- package/dist/packem_shared/agent-C-GavfBl.mjs +0 -1
- package/dist/packem_shared/agentChat-Bay8gA8i.mjs +0 -1
- package/dist/packem_shared/agentState-BAfa0QuC.mjs +0 -1
- package/dist/packem_shared/agentToolEvents-CBTZ_DsO.mjs +0 -1
- package/dist/packem_shared/auth-BTEtMnGG.mjs +0 -1
- package/dist/packem_shared/connectionStatus-C53UhkPi.mjs +0 -1
- package/dist/packem_shared/flag-BYFWoQTg.mjs +0 -1
- package/dist/packem_shared/hydratePreloaded-BKHgpXzQ.mjs +0 -1
- package/dist/packem_shared/infiniteQuery-C-T8hD7-.mjs +0 -1
- package/dist/packem_shared/liveQuery-DEIqmTPj.mjs +0 -1
- package/dist/packem_shared/mutate-DR8Uo8Hs.mjs +0 -1
- package/dist/packem_shared/mutator-Cw6jpG06.mjs +0 -1
- package/dist/packem_shared/platform-BGZypnc9.mjs +0 -1
- package/dist/packem_shared/presence-BMrTlOCF.mjs +0 -1
- package/dist/packem_shared/rateLimit-CQazDrPJ.mjs +0 -1
- package/dist/packem_shared/stream-CcvHiJf2.mjs +0 -1
- package/dist/packem_shared/subscription-DJeoGEDR.mjs +0 -1
- package/dist/packem_shared/voiceAgent-CwlzrEjH.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{inject as i,PLATFORM_ID as c,computed as a,effect as u,untracked as d,NgZone as f}from"@angular/core";import{stableWireKey as l}from"@lunora/wire";const v=e=>e?i(c,{optional:!0})!=="server":!0,p=e=>{const r=e?i(f,{optional:!0}):void 0;return r?t=>r.runOutsideAngular(t):t=>t()},y=(e,r)=>p(e)(r),h=(e,r,t)=>{let n;const s=a(()=>l(e()));try{n=u(o=>{s(),d(()=>{t(e(),o)})},{injector:r.injector,manualCleanup:!0})}catch(o){throw r.injector!==void 0?o:new Error("reactive `args` need an injection context: call this primitive from a component/service field or constructor, or pass `injector` alongside `destroyRef`.",{cause:o})}r.destroyRef.onDestroy(()=>{n.destroy()})};export{h as a,p as o,y as r,v as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{inject as S,DestroyRef as U,signal as v}from"@angular/core";import{resolveLunoraClient as C}from"./LUNORA_CLIENT-B0toApHY.mjs";import{s as E,r as A}from"./platform-DGTu4Ucl.mjs";const w=()=>{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){const n=crypto.getRandomValues(new Uint8Array(16));return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}}throw new Error("randomSessionId: no Web Crypto available — a session id needs crypto.randomUUID or crypto.getRandomValues")},L=1e4,j=(n,e)=>{const i=C(e.client),f=e.destroyRef===void 0,p=e.destroyRef??S(U),{heartbeat:b,listPresent:g,shardKey:a}=e,o=e.intervalMs??L,c=e.sessionId??w(),y=v(void 0),d=v(void 0);if(!Number.isFinite(o)||o<=0)throw new RangeError(`presence intervalMs must be a positive number, got ${String(o)}`);let l=e.data,u=!1;const r=()=>{const t={roomId:n,sessionId:c};l!==void 0&&(t.data=l),i.mutation(b,t,{shardKey:a}).catch(()=>{})},R=t=>{l=t,u&&r()};if(E(f)){u=!0;const t=i.acquireConnectionContext({roomId:n,sessionId:c},{shardKey:a});r();const m=()=>{typeof document<"u"&&document.visibilityState==="visible"&&r()},I=A(f,()=>(typeof document<"u"&&document.addEventListener("visibilitychange",m),setInterval(r,o))),h={roomId:n},D=i.subscribe(g,h,s=>{y.set(s),d.set(void 0)},{onError:s=>{d.set(s),e.onError?.(s)},shardKey:a});p.onDestroy(()=>{u=!1,clearInterval(I),typeof document<"u"&&document.removeEventListener("visibilitychange",m),t(),D()})}return{error:d.asReadonly(),present:y.asReadonly(),sessionId:c,setData:R}};export{j as presence};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{inject as w,DestroyRef as y,signal as p,computed as v}from"@angular/core";import{evaluate as f}from"@lunora/ratelimit";const R=(o,r={})=>{const m=r.destroyRef??w(y),n=r.now??Date.now,k=r.tickMs??1e3;let t;const i=()=>f(o,t,{consume:!1,count:1,now:n(),reserve:!1}).status,e=p(i()),a=()=>{e.set(i())};let s;const l=()=>{s!==void 0&&(clearInterval(s),s=void 0)},d=()=>{e().ok||s!==void 0||(s=setInterval(()=>{a(),e().ok&&l()},k))};return d(),m.onDestroy(()=>{l()}),{check:(u=1)=>f(o,t,{consume:!1,count:u,now:n(),reserve:!1}).status.ok,consume:(u=1)=>{const c=f(o,t,{consume:!0,count:u,now:n(),reserve:!1});return c.value!==void 0&&(t=c.value),a(),d(),c.status},disabled:v(()=>!e().ok),ok:v(()=>e().ok),reset:()=>{t=void 0,l(),a()},retryAfter:v(()=>e().retryAfter)}};export{R as rateLimit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveLunoraClient as e}from"./LUNORA_CLIENT-B0toApHY.mjs";const l=(n,o,t={})=>{const{client:r,...c}=t;return e(r).action(n,o,c)};export{l as runAction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{inject as R,DestroyRef as b,signal as n}from"@angular/core";import{resolveLunoraClient as k}from"./LUNORA_CLIENT-B0toApHY.mjs";import{s as p}from"./platform-DGTu4Ucl.mjs";const g=(u,o,e={})=>{const d=k(e.client),m=e.destroyRef??R(b),y=e.destroyRef===void 0,a=n([]),c=n(void 0),t=n("idle");let s=!0,l;const f=()=>{s=!1,l?.()};if(o!=="skip"&&p(y)){t.set("streaming");const i=d.stream(u,o,{durable:e.durable,maxBuffer:e.maxBuffer,shardKey:e.shardKey});l=()=>{i.cancel()},(async()=>{try{for await(const r of i){if(!s)return;a.update(h=>[...h,r])}s&&t.set("complete")}catch(r){if(!s)return;c.set(r instanceof Error?r:new Error(String(r))),t.set("error")}})().catch(()=>{})}return m.onDestroy(f),{cancel:f,chunks:a.asReadonly(),error:c.asReadonly(),status:t.asReadonly()}};export{g as stream};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{inject as m,DestroyRef as R,signal as a}from"@angular/core";import{createQuerySubscription as p}from"@lunora/client/query";import{resolveLunoraClient as b}from"./LUNORA_CLIENT-B0toApHY.mjs";import{s as h,a as j}from"./platform-DGTu4Ucl.mjs";const C=(d,n,e={})=>{const f=b(e.client),v=e.destroyRef===void 0,i=e.destroyRef??m(R),l=e.onError,o=a(void 0),r=a(void 0),c=(t,u)=>{if(o.set(void 0),r.set(void 0),t==="skip")return;const y=p(f,d,t,{onData:s=>{o.set(s),r.set(void 0)},onError:s=>{r.set(s),o.set(void 0),l?.(s)},onReset:()=>{o.set(void 0)}},{shardKey:e.shardKey});u(y)};return h(v)&&(typeof n=="function"?j(n,{destroyRef:i,injector:e.injector},c):c(n,t=>i.onDestroy(t))),{data:o.asReadonly(),error:r.asReadonly()}};export{C as subscription};
|
|
@@ -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-DGTu4Ucl.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { type ArgsOf, type AuthLike, type FunctionReference, type HeadersSource, type Preloaded, type ReturnOf, type ServerClientOptions, type ServerSession, createServerClient, deserializePreloaded, getServerSession, preloadQuery, preloadedQueryResult, serializePreloaded } from '@lunora/client/ssr';
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { type ArgsOf, type AuthLike, type FunctionReference, type HeadersSource, type Preloaded, type ReturnOf, type ServerClientOptions, type ServerSession, createServerClient, deserializePreloaded, getServerSession, preloadQuery, preloadedQueryResult, serializePreloaded } from '@lunora/client/ssr';
|
package/dist/server.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createServerClient as d,deserializePreloaded as l,getServerSession as a,preloadQuery as o,preloadedQueryResult as i,serializePreloaded as s}from"@lunora/client/ssr";export{d as createServerClient,l as deserializePreloaded,a as getServerSession,o as preloadQuery,i as preloadedQueryResult,s as serializePreloaded};
|
package/dist/upload.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inject as
|
|
1
|
+
import{inject as g,DestroyRef as m,signal as r}from"@angular/core";import{createUpload as v}from"@lunora/client/upload";import{RestrictionError as D,UploadError as E,createChunkedRestAdapter as P,createMultipartAdapter as b,createTusAdapter as C,createUpload as S}from"@lunora/client/upload";import{UploadControl as k}from"@visulima/storage-client";const x=p=>{const{destroyRef:c,...u}=p,l=c??g(m),s=v(u),n=r(0),t=r("idle"),d=r(void 0),o=r(void 0),a=r(!1);s.setOnStart(()=>{t.set("uploading")}),s.setOnProgress(e=>{n.set(e)}),s.setOnFinish(e=>{d.set(e),t.set("success")}),s.setOnError(e=>{o.set(e),t.set("error")});const f=e=>(o.set(void 0),d.set(void 0),n.set(0),a.set(!1),t.set("uploading"),s.upload(e)),R=()=>{t()==="uploading"&&(s.pause(),a.set(!0),t.set("paused"))},y=()=>{t()==="paused"&&s.resume().then(()=>{a.set(!1),t.set("uploading")}).catch(e=>{o.set(e instanceof Error?e:new Error(String(e))),t.set("error")})},i=()=>{s.abort()};return l.onDestroy(i),{abort:i,error:o.asReadonly(),isPaused:a.asReadonly(),pause:R,progress:n.asReadonly(),result:d.asReadonly(),resume:y,start:f,status:t.asReadonly()}};export{D as RestrictionError,k as UploadControl,E as UploadError,P as createChunkedRestAdapter,b as createMultipartAdapter,C as createTusAdapter,S as createUpload,x as upload};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/angular",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.210",
|
|
4
4
|
"description": "Angular reactive adapter for Lunora — signal-based live queries and mutations",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"angular",
|
|
@@ -39,6 +39,10 @@
|
|
|
39
39
|
"types": "./dist/index.d.ts",
|
|
40
40
|
"import": "./dist/index.mjs"
|
|
41
41
|
},
|
|
42
|
+
"./server": {
|
|
43
|
+
"types": "./dist/server.d.ts",
|
|
44
|
+
"import": "./dist/server.mjs"
|
|
45
|
+
},
|
|
42
46
|
"./upload": {
|
|
43
47
|
"types": "./dist/upload.d.ts",
|
|
44
48
|
"import": "./dist/upload.mjs"
|
|
@@ -49,9 +53,10 @@
|
|
|
49
53
|
"access": "public"
|
|
50
54
|
},
|
|
51
55
|
"dependencies": {
|
|
52
|
-
"@lunora/client": "1.0.0-alpha.
|
|
53
|
-
"@lunora/ratelimit": "1.0.0-alpha.
|
|
54
|
-
"@
|
|
56
|
+
"@lunora/client": "1.0.0-alpha.224",
|
|
57
|
+
"@lunora/ratelimit": "1.0.0-alpha.148",
|
|
58
|
+
"@lunora/wire": "1.0.0-alpha.1",
|
|
59
|
+
"@visulima/storage-client": "1.0.9"
|
|
55
60
|
},
|
|
56
61
|
"peerDependencies": {
|
|
57
62
|
"@angular/core": "^19.2.0 || ^20.0.0 || ^21.0.0 || ^22.0.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{InjectionToken as i,makeEnvironmentProviders as t,inject as l}from"@angular/core";import{LunoraClient as r}from"@lunora/client";const n=()=>globalThis.location?.origin??"",e=new i("lunora.client",{factory:()=>new r({url:n()}),providedIn:"root"}),s=(o={})=>t([{provide:e,useFactory:()=>o instanceof r?o:new r({...o,url:o.url??n()})}]),a=()=>l(e),m=o=>o??a();export{e as LUNORA_CLIENT,a as injectLunoraClient,s as provideLunora,m as resolveLunoraClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as g,DestroyRef as h,computed as o,signal as v}from"@angular/core";import{resolveLunoraClient as R}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{subscription as K}from"./subscription-DJeoGEDR.mjs";const b=e=>{const{api:c,cancel:i,run:d,runArgs:u,threadKey:a}=e,n=R(e.client),l=e.destroyRef??g(h),{data:y}=K(c.agents.agentThread,{key:a},{client:n,destroyRef:l}),r=o(()=>y()),f=o(()=>r()?.status),s=v(!1),m=async(t,p)=>{s.set(!0);try{await n.mutation(d,{input:t,threadKey:a,...u,...p})}finally{s.set(!1)}};return{cancel:async()=>{const t=r()?.instanceId;i===void 0||t===void 0||await n.mutation(i,{instanceId:t,threadKey:a})},pending:s.asReadonly(),run:m,status:f,thread:r}};export{b as agent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as D,DestroyRef as E,signal as L,computed as s}from"@angular/core";import{reconcileOptimistic as v,maxSeq as I}from"@lunora/client";import{resolveLunoraClient as M}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{stream as _}from"./stream-CcvHiJf2.mjs";import{subscription as w}from"./subscription-DJeoGEDR.mjs";const O={__lunoraRef:""},J=l=>{const{api:i,cancel:u,limit:g,send:R,sendArgs:k,stream:f,threadKey:a}=l,o=M(l.client),m=l.destroyRef??D(E),C=g===void 0?{key:a}:{key:a,limit:g},{data:K}=w(i.agents.agentMessages,C,{client:o,destroyRef:m}),{data:j}=w(i.agents.agentThread,{key:a},{client:o,destroyRef:m}),x=f===void 0?"skip":{key:a},{chunks:A}=_(f??O,x,{client:o,destroyRef:m}),r=L([]);let y=0;const c=s(()=>j()),S=s(()=>c()?.status),d=s(()=>K()??[]),b=s(()=>{const e=d(),t=v(r(),e);if(t.length===0)return e;const n=I(e);return[...e,...t.map((p,h)=>({content:p.content,optimistic:!0,role:"user",seq:n+1+h}))]}),q=s(()=>{const e=d().filter(t=>t.role==="assistant").length;return A().filter(t=>t.kind!=="progress"&&t.threadKey===a&&t.turn>=e).map(t=>t.text).join("")});return{approve:async(e,t)=>{const n=c()?.instanceId;if(n===void 0)throw new Error("agentChat: cannot approve — no in-flight run (thread has no instanceId)");await o.mutation(i.agents.agentResolveApproval,{decision:"approve",instanceId:n,threadKey:a,toolCallId:e,...t===void 0?{}:{note:t}})},cancel:async()=>{const e=c()?.instanceId;u===void 0||e===void 0||await o.mutation(u,{instanceId:e,threadKey:a})},messages:b,reject:async(e,t)=>{const n=c()?.instanceId;if(n===void 0)throw new Error("agentChat: cannot reject — no in-flight run (thread has no instanceId)");await o.mutation(i.agents.agentResolveApproval,{decision:"reject",instanceId:n,threadKey:a,toolCallId:e,...t===void 0?{}:{note:t}})},send:async(e,t)=>{const n=y;y+=1;const p=I(d());r.set([...v(r(),d()),{content:e,id:n,maxDurableSeqAtSend:p}]);try{await o.mutation(R,{input:e,threadKey:a,...k,...t})}catch(h){throw r.set(r().filter(T=>T.id!==n)),h}},status:S,streamingText:q}};export{J as agentChat};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{computed as a}from"@angular/core";import{subscription as n}from"./subscription-DJeoGEDR.mjs";const c=t=>{const{data:r,error:e}=n(t.api.agents.agentState,{key:t.threadKey},{client:t.client,destroyRef:t.destroyRef}),o=a(()=>r());return{error:e,state:o}};export{c as agentState};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as c,DestroyRef as f,computed as y}from"@angular/core";import{resolveLunoraClient as C}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{stream as v}from"./stream-CcvHiJf2.mjs";import{subscription as g}from"./subscription-DJeoGEDR.mjs";const I={__lunoraRef:""},N=[],k=t=>{if(t.role==="assistant"&&t.toolCalls)return t.toolCalls.map(l=>({input:l.input,seq:t.seq,toolCallId:l.id,toolName:l.name,type:"call"}));if(t.role==="tool")return t.status==="awaiting_approval"?[{seq:t.seq,type:"awaiting-approval",...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolName===void 0?{}:{toolName:t.toolName}}]:[{output:t.content,seq:t.seq,type:"result",...t.status==="approved"||t.status==="rejected"?{status:t.status}:{},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolName===void 0?{}:{toolName:t.toolName}}]},j=t=>{const{api:l,limit:s,stream:e,threadKey:a}=t,r=C(t.client),i=t.destroyRef??c(f),d=s===void 0?{key:a}:{key:a,limit:s},{data:p}=g(l.agents.agentMessages,d,{client:r,destroyRef:i}),m=e===void 0?"skip":{key:a},{chunks:u}=v(e??I,m,{client:r,destroyRef:i});return{events:y(()=>{const n=(p()??N).flatMap(o=>k(o)??[]);for(const o of u())o.kind==="progress"&&o.threadKey===a&&n.push({data:o.data,toolCallId:o.toolCallId,type:"progress"});return n})}};export{j as agentToolEvents};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as g,DestroyRef as h,signal as u,computed as i}from"@angular/core";import{getIdentityStore as d}from"@lunora/client/auth";import{resolveLunoraClient as k}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";const m=(o={})=>{const e=k(o.client),n=o.destroyRef??g(h),t=d(e),r=u(e.getAuthToken()),s=u(t.getUser()),l=e.onAuthTokenChange(()=>{r.set(e.getAuthToken())}),a=t.subscribe(()=>{s.set(t.getUser())});return n.onDestroy(()=>{l(),a()}),{setToken:c=>{e.setAuthToken(c)},token:r.asReadonly(),user:s.asReadonly()}},A=(o={})=>{const{token:e,user:n}=m(o),t=i(()=>e()!==null&&n()===null);return{isAuthenticated:i(()=>e()!==null&&n()!==null),isLoading:t}};export{m as auth,A as authGate};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as c,DestroyRef as i,signal as a}from"@angular/core";import{resolveLunoraClient as l}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";const m=(o={})=>{const n=l(o.client),e=o.destroyRef??c(i),t=a(n.connectionStatus()),s=n.onConnectionStatus(r=>{t.set(r)});return e.onDestroy(s),t.asReadonly()};export{m as connectionStatus};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as f,DestroyRef as y,signal as u}from"@angular/core";import{resolveLunoraClient as i}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";const d="__lunora_flags__:eval",b=r=>{const t=typeof r;return t==="boolean"||t==="number"||t==="string"?t:"object"},p={__lunoraRef:d},m=(r,t,s={})=>{const l=i(s.client),e=s.destroyRef??f(y),c=b(t),o=u(t);let n;try{n=l.subscribe(p,{context:s.context,default:t,key:r,type:c},a=>{o.set(a)},{onError:()=>{o.set(t)}})}catch{}return n&&e.onDestroy(n),o.asReadonly()},x=(r,t={})=>{const s=i(t.client),l=t.destroyRef??f(y),e=u({...r}),c=[];for(const[o,n]of Object.entries(r))try{const a=s.subscribe(p,{context:t.context,default:n,key:o,type:b(n)},_=>{e.set({...e(),[o]:_})},{onError:()=>{e.set({...e(),[o]:n})}});c.push(a)}catch{}return l.onDestroy(()=>{for(const o of c)o()}),e.asReadonly()};export{m as flag,x as flags};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as m,DestroyRef as R,signal as t}from"@angular/core";import{resolveLunoraClient as h}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{s as v}from"./platform-BGZypnc9.mjs";const K=(a,o={})=>{const n=h(o.client),i=o.destroyRef===void 0,d=o.destroyRef??m(R),{args:l,functionPath:f,shardKey:y,value:c}=a,s=t(c),r=t(void 0),u={__lunoraRef:f};if(v(i)){const p=n.subscribe(u,l,e=>{s.set(e),r.set(void 0)},{onError:e=>{r.set(e)},shardKey:y});d.onDestroy(p)}return{data:s.asReadonly(),error:r.asReadonly()}};export{K as hydratePreloaded};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{computed as j,inject as W,DestroyRef as _,signal as C}from"@angular/core";import{initialPages as q,derivePaginationStatus as T,applyLoadMore as z,rebalance as V}from"@lunora/client/pagination";import{resolveLunoraClient as G}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{s as H}from"./platform-BGZypnc9.mjs";const X=(e,n)=>e<n?-1:e>n?1:0,I=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(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(s=>I(s)).join(",")}]`;const n=Object.getPrototypeOf(e);if(n!==null&&n!==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 r=e,y=Object.keys(r).toSorted(X),a=[];for(const s of y){const t=r[s];t!==void 0&&a.push(`${JSON.stringify(s)}:${I(t)}`)}return`{${a.join(",")}}`},F=e=>{let n="";for(let r=0;r<e.length;r+=32768)n+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(n)},f="$lunora.wire$",U=64,v=(e,n=0)=>{if(n>U)throw new RangeError(`wire-codec: value nesting exceeds the ${U}-level limit`);if(e===void 0)return[f,"undefined"];if(e===null)return null;const r=typeof e;if(r==="bigint")return[f,"bigint",e.toString()];if(r==="number"){const t=e;return Number.isNaN(t)?[f,"nan"]:t===1/0?[f,"inf"]:t===-1/0?[f,"-inf"]:t}if(r!=="object")return e;if(e instanceof Date)return[f,"date",v(e.getTime(),n+1)];if(e instanceof Error){const t=e,i={};for(const c of Object.keys(t))t[c]!==void 0&&(i[c]=v(t[c],n+1));const l=[f,"error",t.name,t.message,i];return t.cause!==void 0&&l.push(v(t.cause,n+1)),l}if(e instanceof URL)return[f,"url",e.href];if(e instanceof Map)return[f,"map",[...e.entries()].map(([t,i])=>[v(t,n+1),v(i,n+1)])];if(e instanceof Set)return[f,"set",[...e].map(t=>v(t,n+1))];if(e instanceof ArrayBuffer)return[f,"bytes",F(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const t=e,i=t.constructor.name,l=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return i==="Uint8Array"?[f,"bytes",F(l)]:[f,"bytes",F(l),i]}if(Array.isArray(e)){const t=e.map(i=>v(i,n+1));return t.length>0&&t[0]===f?[f,"arr",t]:t}const y=Object.getPrototypeOf(e);if(y!==null&&y!==Object.prototype){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 a=e,s={};for(const t of Object.keys(a)){const i=a[t];i!==void 0&&(s[t]=v(i,n+1))}return s},Y=e=>I(v(e)),S=(e,n)=>`${e}::${Y(n)}`,L=(e,n)=>({...n,paginationOpts:{cursor:e.lower,endCursor:e.upper,numItems:e.numItems}}),B=(e,n,r)=>{const y=G(r.client),a=r.destroyRef===void 0,s=r.destroyRef??W(_),{initialNumItems:t,shardKey:i}=r,l=e.__lunoraRef,c=n==="skip"?{}:n,d=C(q(t)),$=C([]),J=C("LoadingFirstPage"),O=new Map,h=new Map,k=new Set,M=()=>{const p=d().map(w=>{const o=S(l,L(w,c));return h.get(o)});$.set(p);const{status:b}=T(n==="skip",p);J.set(b)},D=(p,b)=>{const w=o=>S(l,L(o,c));for(const o of b){const g=w(o);if(h.has(g))continue;const m=p.find(u=>u.lower===o.lower);if(m){const u=h.get(w(m));u&&h.set(g,u)}}},Q=p=>{const b=new Set;for(const o of p)b.add(S(l,L(o,c)));for(const[o,g]of O)b.has(g.currentKey)||(g.unsub(),O.delete(o),h.delete(g.currentKey));const w=new Set([...O.values()].map(o=>o.currentKey));for(const o of p){const g=L(o,c),m=S(l,g);if(w.has(m))continue;const u={currentKey:m,unsub:void 0};k.add(m);const A=y.subscribe(e,g,K=>{if(h.set(u.currentKey,K),k.delete(u.currentKey),M(),k.size===0){const N=d(),R=V(N,$());R&&(D(N,R),d.set(R),x(R),M())}},{onError:()=>{k.delete(u.currentKey),M()},shardKey:i});u.unsub=A,O.set(m,u),w.add(m)}};let P=!1,E=!1;const x=p=>{if(P){E=!0;return}P=!0;try{let b=p;do E=!1,Q(b),b=d();while(E)}finally{P=!1}};return n!=="skip"&&H(a)&&x(d()),M(),s.onDestroy(()=>{for(const p of O.values())p.unsub();O.clear(),h.clear()}),{loadMore:p=>{if(n==="skip")return;const{nextCursor:b,status:w}=T(!1,$());if(w!=="CanLoadMore")return;const o=z(d(),b,p);if(!o)return;const g=d().at(-1),m=o.at(-2);if(g&&m){const u=S(l,L(g,c)),A=S(l,L(m,c)),K=O.get(u);if(K&&u!==A){const N=h.get(u);N&&h.set(A,N),K.unsub(),O.delete(u),h.delete(u)}}d.set(o),x(d()),M()},pageResults:$,status:J}},re=(e,n,r)=>{const y=B(e,n,r),a=j(()=>{const s=[];for(const t of y.pageResults())t&&s.push(...t.page);return s});return{isLoading:j(()=>{const s=y.status();return s==="LoadingFirstPage"||s==="LoadingMore"}),loadMore:y.loadMore,results:a,status:y.status}},se=(e,n,r)=>{const{initialNumItems:y}=r,a=B(e,n,r),s=j(()=>{const c=[];for(const d of a.pageResults())d&&c.push(d.page);return c}),t=j(()=>a.status()==="LoadingFirstPage"),i=j(()=>a.status()==="CanLoadMore"),l=j(()=>a.status()==="LoadingMore");return{fetchNextPage:c=>{a.loadMore(c??y)},hasNextPage:i,isFetchingNextPage:l,isLoading:t,pages:s,status:a.status}};export{se as infiniteQuery,re as paginatedQuery};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as y,DestroyRef as c,signal as f}from"@angular/core";import{createQuerySubscription as m}from"@lunora/client/query";import{resolveLunoraClient as p}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{s as u}from"./platform-BGZypnc9.mjs";const D=(t,e,o={})=>{const s=p(o.client),i=o.destroyRef===void 0,n=o.destroyRef??y(c),r=f(void 0);if(u(i)){const a=m(s,t,e,{onData:d=>{r.set(d)},onError:o.onError,onReset:()=>{r.set(void 0)}},{shardKey:o.shardKey});n.onDestroy(a)}return r.asReadonly()};export{D as liveQuery};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{resolveLunoraClient as i}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";const u=(t,o,r={})=>{const{client:e,...n}=r;return i(e).mutation(t,o,n)};export{u as mutate};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{signal as o,computed as m}from"@angular/core";import{createMutatorRunner as d}from"@lunora/client";const c=s=>{const r=o(void 0),t=o(!1),n=m(()=>r()!==void 0),{mutate:a,reset:i}=d(s,{setError:e=>{r.set(e)},setPending:e=>{t.set(e)}});return{error:r.asReadonly(),isError:n,mutate:a,pending:t.asReadonly(),reset:i}};export{c as mutator};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as n,PLATFORM_ID as o,NgZone as u}from"@angular/core";const i=r=>r?n(o,{optional:!0})!=="server":!0,a=(r,t)=>{const e=r?n(u,{optional:!0}):void 0;return e?e.runOutsideAngular(t):t()};export{a as r,i as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as h,DestroyRef as R,signal as D}from"@angular/core";import{resolveLunoraClient as S}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{s as $,r as U}from"./platform-BGZypnc9.mjs";const w=(e="sess")=>{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){const t=crypto.getRandomValues(new Uint8Array(16));return`${e}-${Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}`}}return`${e}-${Date.now().toString(36)}`},A=1e4,E=(e,t)=>{const n=S(t.client),d=t.destroyRef===void 0,y=t.destroyRef??h(R),{heartbeat:p,listPresent:f,shardKey:i}=t,r=t.intervalMs??A,a=t.sessionId??w(),u=D(void 0);if(!Number.isFinite(r)||r<=0)throw new RangeError(`presence intervalMs must be a positive number, got ${String(r)}`);let c=t.data;const s=()=>{const o={roomId:e,sessionId:a};c!==void 0&&(o.data=c),n.mutation(p,o,{shardKey:i}).catch(()=>{})},l=o=>{c=o,s()};if($(d)){const o=n.acquireConnectionContext({roomId:e,sessionId:a},{shardKey:i});s();const m=()=>{typeof document<"u"&&document.visibilityState==="visible"&&s()},v=U(d,()=>(typeof document<"u"&&document.addEventListener("visibilitychange",m),setInterval(s,r))),g={roomId:e},b=n.subscribe(f,g,I=>{u.set(I)},{shardKey:i});y.onDestroy(()=>{clearInterval(v),typeof document<"u"&&document.removeEventListener("visibilitychange",m),o(),b()})}return{present:u.asReadonly(),sessionId:a,setData:l}};export{E as presence};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as w,DestroyRef as y,signal as p,computed as i}from"@angular/core";import{evaluate as v}from"@lunora/ratelimit";const A=(s,r={})=>{const m=r.destroyRef??w(y),n=r.now??Date.now,k=r.tickMs??1e3;let t;const f=()=>v(s,t,{consume:!1,count:1,now:n(),reserve:!1}).status,e=p(f()),a=()=>{e.set(f())};let o;const c=()=>{o!==void 0&&(clearInterval(o),o=void 0)},d=()=>{e().ok||o!==void 0||(o=setInterval(()=>{a(),e().ok&&c()},k))};return d(),m.onDestroy(()=>{c()}),{check:(u=1)=>v(s,t,{consume:!1,count:u,now:n(),reserve:!1}).status.ok,consume:(u=1)=>{const l=v(s,t,{consume:!0,count:u,now:n(),reserve:!1});return l.value!==void 0&&(t=l.value),a(),d(),l.status},disabled:i(()=>!e().ok),ok:i(()=>e().ok),reset:()=>{t=void 0,c(),a()},retryAfter:i(()=>e().retryAfter)}};export{A as rateLimit};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as p,DestroyRef as h,signal as n}from"@angular/core";import{resolveLunoraClient as R}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";const k=(m,o,t={})=>{const u=R(t.client),d=t.destroyRef??p(h),a=n([]),c=n(void 0),r=n("idle");let s=!0,i;const f=()=>{s=!1,i?.()};if(o!=="skip"){r.set("streaming");const l=u.stream(m,o,{maxBuffer:t.maxBuffer,shardKey:t.shardKey});i=()=>{l.cancel()},(async()=>{try{for await(const e of l){if(!s)return;a.update(y=>[...y,e])}s&&r.set("complete")}catch(e){if(!s)return;c.set(e instanceof Error?e:new Error(String(e))),r.set("error")}})().catch(()=>{})}return d.onDestroy(f),{cancel:f,chunks:a.asReadonly(),error:c.asReadonly(),status:r.asReadonly()}};export{k as stream};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as y,DestroyRef as m,signal as i}from"@angular/core";import{createQuerySubscription as u}from"@lunora/client/query";import{resolveLunoraClient as l}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";import{s as v}from"./platform-BGZypnc9.mjs";const E=(n,e,o={})=>{const a=l(o.client),d=o.destroyRef===void 0,c=o.destroyRef??y(m),r=i(void 0),s=i(void 0);if(e!=="skip"&&v(d)){const p=o.onError,f=u(a,n,e,{onData:t=>{r.set(t),s.set(void 0)},onError:t=>{s.set(t),r.set(void 0),p?.(t)},onReset:()=>{r.set(void 0)}},{shardKey:o.shardKey});c.onDestroy(f)}return{data:r.asReadonly(),error:s.asReadonly()}};export{E as subscription};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{inject as L,DestroyRef as W,signal as v}from"@angular/core";import{resolveLunoraClient as I}from"./LUNORA_CLIENT-B0pGE0Tv.mjs";const B=e=>{if(e.length===0)return 0;let o=0;for(const n of e)o+=n*n;return Math.sqrt(o/e.length)},J=(e,o)=>{const n=o/16e3,a=n>1?Math.floor(e.length/n):e.length,d=new ArrayBuffer(a*2),i=new DataView(d);for(let l=0;l<a;l+=1){const g=e[Math.floor(l*n)]??0,h=Math.max(-1,Math.min(1,g));i.setInt16(l*2,h<0?h*32768:h*32767,!0)}return new Uint8Array(d)},K=async e=>{const o=globalThis,n=o.navigator?.mediaDevices?.getUserMedia.bind(o.navigator.mediaDevices),a=o.AudioContext??o.webkitAudioContext;if(!n||!a)throw new Error("voiceAgent: microphone capture requires getUserMedia + AudioContext (no browser audio available)");const d=await n({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),i=new a,l=i.createMediaStreamSource(d),g=i.createScriptProcessor(4096,1,1);let h=!1,m=!1,p=0,f=0;return g.onaudioprocess=r=>{const u=r.inputBuffer.getChannelData(0),k=h?0:B(u);if(e.onLevel(k),h)return;if(e.onAudio(J(u,i.sampleRate)),e.isSpeaking()){f=k>=e.interruptThreshold?f+1:0,f>=e.interruptChunks&&(f=0,e.onInterrupt());return}f=0;const w=u.length/i.sampleRate*1e3;if(k>=e.silenceThreshold){m=!0,p=0;return}m&&(p+=w,p>=e.silenceDurationMs&&(m=!1,p=0,e.onSilence()))},l.connect(g),g.connect(i.destination),{setMuted:r=>{h=r},stop:()=>{g.disconnect(),l.disconnect();for(const r of d.getTracks())r.stop();i.close()}}},N=()=>{const e=globalThis,o=e.AudioContext??e.webkitAudioContext;if(!o)throw new Error("voiceAgent: audio playback requires AudioContext (no browser audio available)");const n=new o,a=new Set;let d=0,i=Promise.resolve(),l=0;const g=async(p,f)=>{if(f!==l)return;let r;try{r=await n.decodeAudioData(p.buffer)}catch{return}if(f!==l)return;const u=n.createBufferSource();u.buffer=r,u.connect(n.destination);const k=Math.max(n.currentTime,d);u.start(k),d=k+r.duration,a.add(u),u.onended=()=>{a.delete(u)}},h=p=>{const f=Uint8Array.from(p),r=l;i=i.then(()=>g(f,r))},m=()=>{l+=1;for(const p of a)try{p.stop()}catch{}a.clear(),d=n.currentTime};return{enqueue:h,interrupt:m,stop:()=>{m(),n.close()}}},D=1,P=.01,V=1200,j=.15,O=3,z=e=>e.startsWith("https://")?`wss://${e.slice(8)}`:e.startsWith("http://")?`ws://${e.slice(7)}`:e,G=e=>{const o=e.__lunoraRef,n=o.startsWith("agents:")?o.slice(7):o;return n.endsWith("Voice")?n.slice(0,-5):n},H=(e,o,n)=>{const a=z(e),d=a.endsWith("/")?a.slice(0,-1):a,i=new URLSearchParams({threadKey:n});return`${d}/_lunora/voice/${encodeURIComponent(o)}?${i.toString()}`},Y=e=>{const{createMicrophone:o=K,createSpeaker:n=N,createSocket:a,interruptChunks:d=O,interruptThreshold:i=j,silenceDurationMs:l=V,silenceThreshold:g=P,threadKey:h,voice:m}=e,p=I(e.client),f=e.destroyRef??L(W),r=v("idle"),u=v(!1),k=v(""),w=v(""),x=v(0),S=v(!1),b=v(void 0);let c,M=!1;const T=s=>{const t=c?.socket;return t?.readyState===D?(t.send(JSON.stringify(s)),!0):!1},C=()=>{const s=c;if(c=void 0,s){s.microphone?.stop(),s.speaker?.stop();try{s.socket.close()}catch{}}M=!1,u.set(!1),r.set("idle"),x.set(0)},U=()=>{C()},$=s=>{const t=c;switch(s.type){case"assistant_delta":{t&&(t.speaking=!0),r.set("speaking"),w.update(A=>A+s.text);break}case"assistant_done":{t&&(t.speaking=!1),w.set(s.text),r.set("listening");break}case"error":{t&&(t.speaking=!1),b.set(new Error(s.message)),r.set("listening");break}case"interrupted":{t&&(t.speaking=!1,t.suppressAudio=!1),t?.speaker?.interrupt(),r.set("listening");break}case"ready":{t&&(t.audioFormat=s.audioFormat,t.suppressAudio=!1),u.set(!0),r.set("listening");break}case"user_transcript":{t&&(t.suppressAudio=!1),k.set(s.text),w.set(""),r.set("thinking");break}}},E=s=>{const t=c;!t||t.suppressAudio||(t.speaker??=n({audioFormat:t.audioFormat}),t.speaking=!0,r.set("speaking"),t.speaker.enqueue(s))},_=async()=>{if(!(c||M)){M=!0,b.set(void 0),k.set(""),w.set("");try{const s=H(p.url,G(m),h),t=(a??(y=>new globalThis.WebSocket(y)))(s);t.binaryType="arraybuffer";const A={audioFormat:"mp3",microphone:void 0,socket:t,speaker:void 0,speaking:!1,suppressAudio:!1};c=A,t.onmessage=y=>{if(typeof y.data=="string"){try{$(JSON.parse(y.data))}catch{}return}E(new Uint8Array(y.data))},t.onerror=()=>{b.set(new Error("voiceAgent: voice socket error"))},t.onclose=()=>{c===A&&C()};const R=await o({interruptChunks:d,interruptThreshold:i,isSpeaking:()=>c?.speaking??!1,onAudio:y=>{t.readyState===D&&t.send(y)},onInterrupt:()=>{T({type:"interrupt"}),c?.speaker?.interrupt(),c&&(c.speaking=!1,c.suppressAudio=!0),r.set("listening")},onLevel:y=>{x.set(y)},onSilence:()=>{T({type:"commit"}),r.set("thinking")},silenceDurationMs:l,silenceThreshold:g});c===A?(A.microphone=R,S.set(!1),r.set("listening")):R.stop()}catch(s){b.set(s instanceof Error?s:new Error(String(s))),C()}finally{M=!1}}},q=()=>{const s=!S();return c?.microphone?.setMuted(s),S.set(s),s},F=s=>{T({text:s,type:"text"})&&r.set("thinking")};return f.onDestroy(C),{audioLevel:x.asReadonly(),connected:u.asReadonly(),endCall:U,error:b.asReadonly(),interimTranscript:w.asReadonly(),isMuted:S.asReadonly(),sendText:F,startCall:_,status:r.asReadonly(),toggleMute:q,transcript:k.asReadonly()}};export{Y as voiceAgent};
|