@urun-sh/react 0.6.29 → 0.6.30
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 +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -584,6 +584,8 @@ interface ScopedStreamSource {
|
|
|
584
584
|
|
|
585
585
|
readonly track: MediaStreamTrack | null;
|
|
586
586
|
|
|
587
|
+
readonly directOut?: boolean;
|
|
588
|
+
|
|
587
589
|
on(event: 'track', handler: (track: MediaStreamTrack | null) => void): () => void;
|
|
588
590
|
|
|
589
591
|
attach(track: MediaStreamTrack): Promise<void>;
|
|
@@ -637,6 +639,8 @@ interface AudioStreamSource {
|
|
|
637
639
|
|
|
638
640
|
readonly track: MediaStreamTrack | null;
|
|
639
641
|
|
|
642
|
+
readonly directOut?: boolean;
|
|
643
|
+
|
|
640
644
|
on(event: 'track', handler: (track: MediaStreamTrack | null) => void): () => void;
|
|
641
645
|
}
|
|
642
646
|
|
|
@@ -670,6 +674,8 @@ interface AudioProps {
|
|
|
670
674
|
onUnlockChange?: (unlocked: boolean) => void;
|
|
671
675
|
|
|
672
676
|
onAudioElement?: (el: HTMLAudioElement | null) => void;
|
|
677
|
+
|
|
678
|
+
directOut?: boolean;
|
|
673
679
|
}
|
|
674
680
|
|
|
675
681
|
declare const Audio: react.ForwardRefExoticComponent<AudioProps & react.RefAttributes<AudioHandle>>;
|
|
@@ -748,6 +754,8 @@ interface VoiceProps {
|
|
|
748
754
|
onUnlockChange?: (unlocked: boolean) => void;
|
|
749
755
|
|
|
750
756
|
capture?: CaptureController;
|
|
757
|
+
|
|
758
|
+
directOut?: boolean;
|
|
751
759
|
}
|
|
752
760
|
|
|
753
761
|
declare const DEFAULT_VOICE_CONSTRAINTS: MediaTrackConstraints;
|
package/dist/index.d.ts
CHANGED
|
@@ -584,6 +584,8 @@ interface ScopedStreamSource {
|
|
|
584
584
|
|
|
585
585
|
readonly track: MediaStreamTrack | null;
|
|
586
586
|
|
|
587
|
+
readonly directOut?: boolean;
|
|
588
|
+
|
|
587
589
|
on(event: 'track', handler: (track: MediaStreamTrack | null) => void): () => void;
|
|
588
590
|
|
|
589
591
|
attach(track: MediaStreamTrack): Promise<void>;
|
|
@@ -637,6 +639,8 @@ interface AudioStreamSource {
|
|
|
637
639
|
|
|
638
640
|
readonly track: MediaStreamTrack | null;
|
|
639
641
|
|
|
642
|
+
readonly directOut?: boolean;
|
|
643
|
+
|
|
640
644
|
on(event: 'track', handler: (track: MediaStreamTrack | null) => void): () => void;
|
|
641
645
|
}
|
|
642
646
|
|
|
@@ -670,6 +674,8 @@ interface AudioProps {
|
|
|
670
674
|
onUnlockChange?: (unlocked: boolean) => void;
|
|
671
675
|
|
|
672
676
|
onAudioElement?: (el: HTMLAudioElement | null) => void;
|
|
677
|
+
|
|
678
|
+
directOut?: boolean;
|
|
673
679
|
}
|
|
674
680
|
|
|
675
681
|
declare const Audio: react.ForwardRefExoticComponent<AudioProps & react.RefAttributes<AudioHandle>>;
|
|
@@ -748,6 +754,8 @@ interface VoiceProps {
|
|
|
748
754
|
onUnlockChange?: (unlocked: boolean) => void;
|
|
749
755
|
|
|
750
756
|
capture?: CaptureController;
|
|
757
|
+
|
|
758
|
+
directOut?: boolean;
|
|
751
759
|
}
|
|
752
760
|
|
|
753
761
|
declare const DEFAULT_VOICE_CONSTRAINTS: MediaTrackConstraints;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
"use strict";var gr=Object.defineProperty;var No=Object.getOwnPropertyDescriptor;var Io=Object.getOwnPropertyNames;var Oo=Object.prototype.hasOwnProperty;var Lo=(e,t)=>{for(var r in t)gr(e,r,{get:t[r],enumerable:!0})},Do=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Io(t))!Oo.call(e,n)&&n!==r&&gr(e,n,{get:()=>t[n],enumerable:!(o=No(t,n))||o.enumerable});return e};var Vo=e=>Do(gr({},"__esModule",{value:!0}),e);var Ts={};Lo(Ts,{Audio:()=>Nt,Camera:()=>Vr,ComponentRenderer:()=>Nn,CreditsClient:()=>Xe.CreditsClient,CreditsError:()=>Xe.CreditsError,CreditsUnauthorizedError:()=>Xe.CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS:()=>Dr,DEFAULT_LOG_CAP:()=>je,DEFAULT_SMOOTH_CHARS_PER_FRAME:()=>Ar,DEFAULT_SMOOTH_THRESHOLD:()=>Mr,DEFAULT_VOICE_CONSTRAINTS:()=>Ir,DocPatchForm:()=>Lt,Image:()=>Jn,ImageFrame:()=>Hn,ImageFrameSchema:()=>qn,MetricsPanel:()=>Bn,MetricsPanelSchema:()=>Wn,Mic:()=>no,OPERATOR_CHORD_LABEL:()=>Zr,OPERATOR_TOKEN_STORAGE_KEY:()=>Jr,ProgressCard:()=>On,ProgressCardSchema:()=>In,ReprojectedVideo:()=>Un,Session:()=>kn,StatusBadge:()=>Dn,StatusBadgeSchema:()=>Ln,Text:()=>Gn,TextStream:()=>Fn,TextStreamError:()=>lt,TextStreamSchema:()=>Vn,UrunActivationOverlay:()=>ur,UrunAudio:()=>Qn,UrunAuthProvider:()=>Ct,UrunCamera:()=>oo,UrunControlSender:()=>So,UrunCreditsGate:()=>Eo,UrunDocPanel:()=>fo,UrunErrorBoundary:()=>ot,UrunEventSpine:()=>ho,UrunIdleWarning:()=>xo,UrunJwtProvider:()=>Gr,UrunProvider:()=>an,UrunSessionClock:()=>To,UrunSessionEnded:()=>Po,UrunSessionGate:()=>bo,UrunSessionPaused:()=>qr,UrunSessionStatus:()=>ko,UrunSessionWaking:()=>sr,UrunStreamTail:()=>mo,UrunVoice:()=>to,Video:()=>Ye,Voice:()=>It,authMode:()=>Tt,createCreditsClient:()=>Xe.createCreditsClient,createDocStore:()=>zt,describeSessionPhase:()=>fr.describeSessionPhase,formatPayload:()=>ft,getUrunAudioContext:()=>Rt,isWakingPhase:()=>fr.isWakingPhase,parseJsonObject:()=>Zt,pushCapped:()=>Ve,readOperatorToken:()=>Sr,registerComponent:()=>Mn,resumeUrunAudioContext:()=>Je,textDelta:()=>Ur,urunPublicEnv:()=>Pe,useActivation:()=>ir,useApp:()=>ln,useChat:()=>vn,useCompletion:()=>gn,useConfirmOnLeave:()=>qt,useCredits:()=>dr,useDocStore:()=>mt,useGenerationTick:()=>po,useImageFrame:()=>Er,useInputPresence:()=>yn,useMetricsPanel:()=>wr,useOperatorOverride:()=>Ft,useProgressCard:()=>Rr,useReferenceImage:()=>so,useRequest:()=>mn,useSession:()=>bn,useSessionDirectory:()=>pn,useSessionDoc:()=>lo,useSessionEndsAt:()=>Fr,useSessionIdle:()=>Wr,useSessionPhase:()=>Te,useSessionStats:()=>Ao,useSessionTrack:()=>io,useSessionWake:()=>or,useStatusBadge:()=>Pr,useStreamMessages:()=>er,useText:()=>_r,useTextMeter:()=>$n,useTextStream:()=>xr,useUrunAudioLevel:()=>Gt,useUrunAuth:()=>Dt,useUrunPrewake:()=>Uo,usesWorkOSAuth:()=>Kr});module.exports=Vo(Ts);var ce=require("react"),sn=require("@urun-sh/core/internal");var Br=require("react"),bt=require("react/jsx-runtime"),ot=class extends Br.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,bt.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,bt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,bt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var jr=require("react"),He=(0,jr.createContext)(null);function Ne(e){return e&&e.trim()?e.trim():void 0}function Pe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Ne(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ne(typeof process<"u"?process.env?.[e]:void 0)}}function Tt(){let e=Pe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Pe("VERCEL_ENV")==="production"?"workos":Pe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Kr(){return Tt()==="workos"}var st=require("react"),Xr=require("react/jsx-runtime"),$r=(0,st.createContext)(null);function Ct({getAccessToken:e,children:t}){let r=(0,st.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Xr.jsx)($r.Provider,{value:r,children:t})}var Gr=Ct;function Dt(){return(0,st.useContext)($r)}var Vt=require("react"),Jr="urun.operator_token",Yr=null,zr="op",Zr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Qr(){return typeof window<"u"}function Sr(){return Yr}function Fo(){if(!Qr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(zr);if(!r)return null;Yr=r,t.delete(zr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function qo(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Ft(e){let t=(0,Vt.useRef)(e);t.current=e,(0,Vt.useEffect)(()=>{if(!Qr())return;Fo();let r=o=>{if(!qo(o))return;let n=Sr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var en=require("react");function qt(e=!0){(0,en.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var Ie=require("react/jsx-runtime"),Ho="/api/urun-token",Wo=1e4;function Bo(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}var tn=3,jo=new Set([502,503,504]);function rn(e){return new Promise(t=>setTimeout(t,(0,sn.computeBackoffDelay)(e)))}async function nn(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=tn-1)throw a;await rn(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!jo.has(o.status)||r>=tn-1)throw a;await rn(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function on(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function hr(e){let t=e===void 0?void 0:JSON.stringify(e);return(0,ce.useMemo)(()=>e,[t])}function Ko(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Ie.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Ie.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Ie.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function an({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:m,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:h,sessionStats:w,confirmOnLeave:v=!1,fallback:d,errorFallback:b,children:f}){let S=n===void 0&&t===void 0;if(!S&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!S&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let C=r??o;if(S&&(typeof C!="string"||C.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);qt(v);let[p,T]=(0,ce.useState)(),[P,U]=(0,ce.useState)(null),A=(0,ce.useRef)(void 0),x=(0,ce.useRef)(null),[N,E]=(0,ce.useState)(null);Ft(M=>E({jwt:M}));let q=Dt(),Y=Pe("NEXT_PUBLIC_SESSION_TOKEN")??Pe("NEXT_PUBLIC_URUN_JWT"),z=Tt(),Z=N!==null,y=z==="workos"&&!n&&!Z&&!S,H=n??(z==="jwt"?Y:void 0)??p?.token,W=Z?N.jwt:H,ee=s??Pe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),R=y&&!W&&!q?.getAccessToken,L=t??p?.orgId,_=e??p?.gatewayUrl,j=S&&p===void 0,D=S&&p!==void 0&&!_?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,Q=R?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,me=P??D??Q,ae=on("NEXT_PUBLIC_URUN_TOKEN_URL",Pe("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Ho,le=on("NEXT_PUBLIC_URUN_EVENTS_URL",Pe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,we=(0,ce.useCallback)(async M=>{if(!M?.forceRefresh){let te=A.current;if(!te)return te;let ve=Bo(te);if(ve===null||ve-Date.now()>Wo)return te}return(await(x.current??(x.current=(async()=>{try{let te=await nn(ae);return A.current=te.token,T(te),te}finally{x.current=null}})()))).token},[ae]),he=(0,ce.useCallback)(async()=>W,[W]),qe=typeof W=="string"&&W.trim().length>0,fe=y?q?.getAccessToken:S&&!Z?we:qe?he:void 0,de=hr(g),se=hr(h),k=hr(w),V=(0,ce.useMemo)(()=>({appId:C,baseUrl:_??"",orgId:L??"",jwt:W,getAccessToken:y?q?.getAccessToken:S&&!Z?we:void 0,authProvider:ee,eventsUrl:le,sessionKey:a,releaseOnLeave:u,allowWebTransport:m,allowWebRtcFallback:l,audioPlayout:de,videoPlayout:se,sessionStats:k,priority:Z?"preempt":void 0}),[C,q,_,ee,W,le,L,a,u,m,l,de,se,k,y,Z,S,we]);return(0,ce.useEffect)(()=>{if(!S)return;let M=new AbortController;return U(null),(async()=>{try{let $=await nn(ae,M.signal);A.current=$.token,T($)}catch($){if(M.signal.aborted)return;U($ instanceof Error?$:new Error(String($)))}})(),()=>M.abort()},[S,ae]),(0,Ie.jsx)(ot,{fallback:d,children:me?Ko(b,me):j?(0,Ie.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Ie.jsx)(He.Provider,{value:V,children:fe?(0,Ie.jsx)(Ct,{getAccessToken:fe,children:f}):f})})}var ge=require("react"),un=require("@urun-sh/core");function cn(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function $o(e,t,r){let o=cn(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function Go(e,t,r,o){let n=cn(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var ze=new Map;var vr=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},yr=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},kr=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}watchDownlinkStall(t={}){return this._session.watchDownlinkStall?this._session.watchDownlinkStall(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new vr(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new yr(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function ln(){let e=(0,ge.useContext)(He);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,ge.useReducer)(i=>i+1,0),r=(0,ge.useRef)(new Map),o=(0,ge.useRef)(new Map),n=(0,ge.useRef)(null),s=(0,ge.useMemo)(()=>(0,un.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return(0,ge.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=ze.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let m=ze.get(c);m===u&&(m.handle.removeNotifier(t),m.refCount=Math.max(0,m.refCount-1),a.set(c,m),m.refCount===0&&(m.disposeTimer=setTimeout(()=>{let l=ze.get(c);!l||l.refCount!==0||(ze.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),(0,ge.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let m=(l,g)=>{let h=$o(c,l,g),w=r.current.get(h);if(w&&!w.disposed)return w;let v=Go(e,c,l,g),d=ze.get(v);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),ze.delete(v),o.current.get(v)===d&&o.current.delete(v),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new kr(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},ze.set(v,d)),o.current.get(v)!==d&&(o.current.set(v,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(h,d.handle),d.handle};return i.set(c,m),m}})},[e,s])}var Ht=require("react"),dn=require("@urun-sh/core");function pn(){let e=(0,Ht.useContext)(He);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return(0,Ht.useMemo)(()=>(0,dn.sessionDirectory)(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}var ie=require("react");function it(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Xo(e){return e instanceof Error?e:new Error(String(e))}function mn(e,t){let r=(0,ie.useMemo)(()=>it(e),[e]),[o,n]=(0,ie.useState)(void 0),[s,i]=(0,ie.useState)(null),[a,c]=(0,ie.useState)(!1),u=(0,ie.useRef)(t);u.current=t;let m=(0,ie.useRef)(0),l=(0,ie.useRef)(null),g=(0,ie.useRef)(!0);(0,ie.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let h=(0,ie.useCallback)(async d=>{l.current?.abort();let b=new AbortController;l.current=b;let f=++m.current,S=()=>g.current&&m.current===f;S()&&(c(!0),i(null));try{let C=await r.request(d,{...u.current,signal:b.signal});return S()&&(n(C),c(!1),u.current?.onSuccess?.(C)),C}catch(C){let p=Xo(C);throw S()&&(i(p),c(!1),u.current?.onError?.(p)),p}},[r]),w=(0,ie.useCallback)(d=>{h(d).catch(()=>{})},[h]),v=(0,ie.useCallback)(()=>{m.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:w,mutateAsync:h,data:o,error:s,isPending:a,reset:v}}var ue=require("react");function fn(e){return e instanceof Error?e:new Error(String(e))}var zo=e=>typeof e=="string"?e:String(e);function gn(e,t){let r=(0,ue.useMemo)(()=>it(e),[e]),[o,n]=(0,ue.useState)(""),[s,i]=(0,ue.useState)(!1),[a,c]=(0,ue.useState)(null),u=(0,ue.useRef)(t);u.current=t;let m=(0,ue.useRef)(0),l=(0,ue.useRef)(null),g=(0,ue.useRef)(!0);(0,ue.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let h=(0,ue.useCallback)(()=>{m.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),w=(0,ue.useCallback)(async v=>{l.current?.cancel();let d=++m.current,b=()=>g.current&&m.current===d,f=u.current,S=f?.parseChunk??zo,C=f?.buildPayload??(E=>({prompt:E}));b()&&(n(""),c(null),i(!0));let{parseChunk:p,buildPayload:T,onFinish:P,onError:U,...A}=f??{},x="",N;try{N=r.requestStream(C(v),A),l.current=N}catch(E){let q=fn(E);b()&&(c(q),i(!1),f?.onError?.(q));return}try{for await(let E of N){if(m.current!==d)break;x+=S(E),b()&&n(x)}b()&&(i(!1),f?.onFinish?.(x))}catch(E){let q=fn(E);b()&&(c(q),i(!1),f?.onError?.(q))}finally{l.current===N&&(l.current=null)}},[r]);return{completion:o,complete:w,stop:h,isStreaming:s,error:a}}var ne=require("react");function Sn(e){return e instanceof Error?e:new Error(String(e))}var Jo=e=>typeof e=="string"?e:String(e),hn=0;function br(e){return hn+=1,`${e}-${hn}`}function vn(e,t){let r=(0,ne.useMemo)(()=>it(e),[e]),[o,n]=(0,ne.useState)(()=>(t?.initialMessages??[]).map(S=>({id:S.id??br("msg"),role:S.role,content:S.content}))),[s,i]=(0,ne.useState)(""),[a,c]=(0,ne.useState)(!1),[u,m]=(0,ne.useState)(null),l=(0,ne.useRef)(t);l.current=t;let g=(0,ne.useRef)(o);g.current=o;let h=(0,ne.useRef)(s);h.current=s;let w=(0,ne.useRef)(0),v=(0,ne.useRef)(null),d=(0,ne.useRef)(!0);(0,ne.useEffect)(()=>(d.current=!0,()=>{d.current=!1,v.current?.cancel(),v.current=null}),[]);let b=(0,ne.useCallback)(()=>{w.current++,v.current?.cancel(),v.current=null,d.current&&c(!1)},[]),f=(0,ne.useCallback)(async S=>{let C=S===void 0,p=(C?h.current:S)??"";if(!p.trim())return;v.current?.cancel();let P=++w.current,U=()=>d.current&&w.current===P,A=l.current,x=A?.parseChunk??Jo,N={id:br("msg"),role:"user",content:p},E={id:br("msg"),role:"assistant",content:""},q=[...g.current,N].map(D=>({role:D.role,content:D.content})),Y=[...g.current,N,E];g.current=Y,n(Y),C&&i(""),m(null),c(!0);let z=A?.buildPayload??(D=>({messages:D})),{initialMessages:Z,parseChunk:y,buildPayload:H,onFinish:W,onError:ee,...R}=A??{},L=D=>{n(Q=>Q.map(me=>me.id===E.id?{...me,content:D}:me))},_="",j;try{j=r.requestStream(z(q),R),v.current=j}catch(D){let Q=Sn(D);U()&&(m(Q),c(!1),A?.onError?.(Q));return}try{for await(let D of j){if(w.current!==P)break;_+=x(D),U()&&L(_)}U()&&(c(!1),A?.onFinish?.({...E,content:_}))}catch(D){let Q=Sn(D);U()&&(m(Q),c(!1),A?.onError?.(Q))}finally{v.current===j&&(v.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:f,stop:b,isStreaming:a,error:u}}var re=require("react"),at=require("@urun-sh/core"),Tr=[];function yn(e,t={}){let{field:r=at.INPUT_PRESENCE_FIELD,hz:o=at.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,re.useMemo)(()=>s?(0,at.createInputPresencePublisher)({awareness:{setLocalStateField:(p,T)=>s.setField(p,T)},field:r,hz:o}):null,[s,r,o]),a=(0,re.useRef)(null);a.current=i;let[c,u]=(0,re.useState)(!1),[m,l]=(0,re.useState)(Tr),g=(0,re.useRef)(!1);(0,re.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let h=(0,re.useCallback)(()=>{let p=a.current;l(p?p.heldKeys():Tr)},[]),w=(0,re.useCallback)(()=>{a.current?.clear(),l(Tr)},[]);(0,re.useEffect)(()=>{if(!n)return;let p=()=>!!n.pointerLockElement,T=()=>{if(p()){g.current=!1,u(!0);return}g.current||(u(!1),w())},P=E=>{p()&&(a.current?.keyDown(E.key),h())},U=E=>{a.current?.keyUp(E.key),h()},A=E=>{p()&&a.current?.movePointer(E.movementX,E.movementY)},x=E=>{p()&&a.current?.setButtons(E.buttons)},N=()=>{w()};return n.addEventListener("pointerlockchange",T),n.addEventListener("keydown",P),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",x),n.addEventListener("mouseup",x),n.defaultView?.addEventListener("blur",N),()=>{n.removeEventListener("pointerlockchange",T),n.removeEventListener("keydown",P),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",x),n.removeEventListener("mouseup",x),n.defaultView?.removeEventListener("blur",N)}},[n,w,h]);let v=(0,re.useCallback)(p=>{p.requestPointerLock?.()},[]),d=(0,re.useCallback)(()=>{g.current=!0,u(!0)},[]),b=(0,re.useCallback)(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),w()},[n,w]),f=(0,re.useCallback)(p=>{a.current?.keyDown(p),h()},[h]),S=(0,re.useCallback)(p=>{a.current?.keyUp(p),h()},[h]),C=(0,re.useCallback)((p,T)=>{a.current?.movePointer(p,T)},[]);return{engage:v,engageTouch:d,release:b,engaged:c,heldKeys:m,pressKey:f,releaseKey:S,movePointer:C}}var pe=require("react"),wn=require("@urun-sh/core");var F=require("react"),En=require("@urun-sh/core");var Wt=null;function Yo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Rt(){if(Wt)return Wt;let e=Yo();return e?(Wt=new e,Wt):null}function Je(){let e=Rt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Pt=require("react"),Tn=require("react/jsx-runtime"),Cr=(0,Pt.createContext)(null);function kn({session:e,children:t}){return(0,Tn.jsx)(Cr.Provider,{value:e,children:t})}function Ue(){return(0,Pt.useContext)(Cr)}function bn(){let e=(0,Pt.useContext)(Cr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var xt=require("react/jsx-runtime");function Zo(e,t){return e-t>>>0<2147483648}var Cn=1e3;function Rn(...e){console.debug("[video]",...e)}function Pn(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function xn(e,t,r){return r?[r,t]:[e,t]}var Ye=(0,F.forwardRef)(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:m,style:l,videoClassName:g,placeholder:h,poster:w,children:v,onTrack:d,onFirstFrame:b,frameMarker:f,onFrameMarkerReached:S,onFrameMarkerUnsupported:C,onUnlockChange:p}=t,T=Ue(),P=o??T,U=(0,F.useRef)(null),A=(0,F.useRef)(null),[x,N]=(0,F.useState)(!1),[E,q]=(0,F.useState)(!1),Y=(0,F.useRef)(!1),z=(0,F.useRef)(null),Z=(0,F.useRef)(d);Z.current=d;let y=(0,F.useRef)(p);y.current=p;let H=(0,F.useRef)(b);H.current=b;let W=(0,F.useRef)(S);W.current=S;let ee=(0,F.useRef)(C);ee.current=C;let R=(0,F.useRef)(f??null);R.current=f??null;let L=(0,F.useCallback)(k=>{z.current!==k&&(z.current=k,y.current?.(k))},[]),_=(0,F.useRef)(null),j=(0,F.useRef)(null),D=(0,F.useCallback)((k,V=!1)=>{if(!V&&k===_.current||(_.current=k,j.current?.(),j.current=null,Y.current=!1,q(!1),!k))return;let M=U.current;if(!M)return;let $=R.current,te=$?.rtpTimestamp??null,ve=!1,O=()=>{ve||(ve=!0,ee.current?.())};$&&te==null&&O();let Ae=$!=null&&te!=null,rt=_e=>{j.current?.(),j.current=null,Y.current=!0,q(!0),H.current?.(),_e&&W.current?.()};if(typeof M.requestVideoFrameCallback=="function"){let _e=!1,B=0,K=(ye,ke)=>{if(!_e){if(Ae){let Re=ke?.rtpTimestamp;if(typeof Re!="number"){O(),rt(!1);return}if(!Zo(Re,te)){B=M.requestVideoFrameCallback(K);return}rt(!0);return}rt(!1)}};B=M.requestVideoFrameCallback(K),j.current=()=>{_e=!0,M.cancelVideoFrameCallback?.(B)};return}Ae&&O();let Me=()=>{let _e=M.getVideoPlaybackQuality?.();(_e?_e.totalVideoFrames>0:M.readyState>=2&&M.videoWidth>0)&&rt(!1)};M.addEventListener("loadeddata",Me),M.addEventListener("timeupdate",Me),M.addEventListener("playing",Me),j.current=()=>{M.removeEventListener("loadeddata",Me),M.removeEventListener("timeupdate",Me),M.removeEventListener("playing",Me)},Me()},[]);(0,F.useEffect)(()=>()=>{j.current?.(),j.current=null},[]);let Q=f==null?null:`${f.rtpTimestamp??""}|${f.ptsMs??""}`,me=(0,F.useRef)(Q);(0,F.useEffect)(()=>{if(me.current===Q||(me.current=Q,Q==null))return;let k=_.current;k&&D(k,!0)},[Q,D]);let ae=(0,F.useCallback)(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let k=U.current;return k&&k.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(k.srcObject=A.current),A.current},[]),le=(0,F.useCallback)(k=>{let V=U.current;if(!V)return;let M=V.play();!M||typeof M.then!="function"||M.then(()=>{V.muted||L(!0)}).catch($=>{if(($ instanceof Error?$.name:String($))==="NotAllowedError"&&!V.muted){Rn(`play() blocked pending a user gesture (${k})`),L(!1);return}Rn(`play() failed (${k})`,$)})},[L]),we=(0,F.useCallback)(()=>{let k=U.current;k&&(ae(),!k.muted&&(le("gesture"),Je(),L(!0)))},[ae,le,L]),he=(0,F.useCallback)(k=>{let V=ae();if(V){for(let M of V.getVideoTracks())M!==k&&V.removeTrack(M);if(k&&!V.getVideoTracks().includes(k)){V.addTrack(k);let M=U.current;M&&(M.srcObject=V)}k&&le("track-attach"),N(k!==null),D(k),Z.current?.(k)}},[ae,le,D]),qe=(0,F.useCallback)(k=>{let V=ae();if(V){for(let M of V.getAudioTracks())M!==k&&V.removeTrack(M);if(k&&!V.getAudioTracks().includes(k)){V.addTrack(k);let M=U.current;M&&M.srcObject!==V&&(M.srcObject=V)}k&&le("audio-attach")}},[ae,le]),fe=(0,F.useCallback)(k=>{U.current=k,k&&(a?(k.muted=!0,k.defaultMuted=!0,k.setAttribute("muted",""),z.current=null):(k.muted=!1,k.defaultMuted=!1,k.removeAttribute("muted")),k.setAttribute("playsinline",""),k.setAttribute("webkit-playsinline",""),ae())},[ae,a]);(0,F.useImperativeHandle)(r,()=>({get element(){return U.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return Y.current},unlock:we,get unlocked(){return z.current===!0}}),[we]);let de=(0,En.derivedLegRole)(n)!==void 0;(0,F.useEffect)(()=>{de&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[de,n]);let se=i!==void 0;return(0,F.useEffect)(()=>{if(se){he(i??null);return}if(de){he(null);return}if(!P)return;let k=Pn(P,xn(n,"video")),V=()=>{let O=A.current;return O?O.getVideoTracks()[0]??null:null},M=O=>{if(O!==V()&&(he(O),O)){let Ae=()=>{V()===O&&he(null)};O.addEventListener("ended",Ae)}},$=k.track;$&&$.readyState==="live"&&M($);let te=k.on("track",O=>{O&&O.readyState!=="live"||M(O)}),ve=setInterval(()=>{let O=k.track;O&&O.readyState==="live"&&M(O)},Cn);return()=>{te(),clearInterval(ve)}},[P,n,de,se,i,he]),(0,F.useEffect)(()=>{if(se||!P||s===!1||de)return;let k=Pn(P,xn(n,"audio",s)),V=()=>{let O=A.current;return O?O.getAudioTracks()[0]??null:null},M=O=>{if(O!==V()&&(qe(O),O)){let Ae=()=>{V()===O&&qe(null)};O.addEventListener("ended",Ae)}},$=k.track;$&&$.readyState==="live"&&M($);let te=k.on("track",O=>{O&&O.readyState!=="live"||M(O)}),ve=setInterval(()=>{let O=k.track;O&&O.readyState==="live"&&M(O)},Cn);return()=>{te(),clearInterval(ve)}},[P,n,de,s,se,qe]),(0,xt.jsxs)("div",{className:m,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":x?"true":"false","data-urun-video-framed":E?"true":"false",children:[(0,xt.jsx)("video",{ref:fe,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),x?null:h,w===void 0?null:(0,xt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":E||void 0,style:{position:"absolute",inset:0,...E?{opacity:0,pointerEvents:"none"}:null},children:w}),v]})});var Et=require("react/jsx-runtime"),Qo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},Un=(0,pe.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...m}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=(0,pe.useRef)(null),h=(0,pe.useRef)(null),w=(0,pe.useRef)(0),v=(0,pe.useRef)(m);v.current=m;let d=(0,pe.useMemo)(()=>(0,wn.createCameraWarp)(v.current),[]);return(0,pe.useImperativeHandle)(r,()=>({get video(){return g.current},get canvas(){return h.current},warp:d,get lastDrawTs(){return w.current}}),[d]),(0,pe.useEffect)(()=>{if(!i)return;let b=0,f=0,S=null,C=T=>{typeof T.requestVideoFrameCallback=="function"&&(S=T,f=T.requestVideoFrameCallback(function P(){d.frameArrived(),f=T.requestVideoFrameCallback(P)}))},p=T=>{b=requestAnimationFrame(p);let P=h.current,U=g.current?.element??null;if(!P||!U||(U!==S&&(S&&f&&S.cancelVideoFrameCallback?.(f),C(U)),U.readyState<2))return;d.tick(T);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,x=Math.max(1,Math.round(P.clientWidth*A)),N=Math.max(1,Math.round(P.clientHeight*A));(P.width!==x||P.height!==N)&&(P.width=x,P.height=N);let E=P.getContext("2d");if(!E)return;let q=d.transform(),Y=U.videoWidth||x,z=U.videoHeight||N,y=Math.max(x/Y,N/z)*(1+a)*q.scale;E.setTransform(y,0,0,y,x/2+q.translateX*x,N/2+q.translateY*N),E.drawImage(U,-Y/2,-z/2),w.current=T};return b=requestAnimationFrame(p),()=>{cancelAnimationFrame(b),S&&f&&S.cancelVideoFrameCallback?.(f)}},[i,a,d]),(0,pe.useEffect)(()=>{if(!i||!c||!l)return;let b=()=>!!l.pointerLockElement,f=P=>{b()&&d.keyDown(P.key)},S=P=>d.keyUp(P.key),C=P=>{b()&&d.pointerDelta(P.movementX,P.movementY)},p=()=>{b()||d.clearKeys()},T=()=>d.clearKeys();return l.addEventListener("keydown",f),l.addEventListener("keyup",S),l.addEventListener("mousemove",C),l.addEventListener("pointerlockchange",p),l.defaultView?.addEventListener("blur",T),()=>{l.removeEventListener("keydown",f),l.removeEventListener("keyup",S),l.removeEventListener("mousemove",C),l.removeEventListener("pointerlockchange",p),l.defaultView?.removeEventListener("blur",T)}},[i,c,l,d]),i?(0,Et.jsxs)(Ye,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,Et.jsx)("canvas",{ref:h,style:Qo,"data-urun-warp":""}),n]}):(0,Et.jsx)(Ye,{ref:g,...s,children:n})});var An=new Map;function Mn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);An.set(e,{component:t,schema:r})}function _n(e,t){let r=An.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var Ze=require("react/jsx-runtime");function Nn({name:e,props:t,fallback:r}){let o=_n(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Ze.jsx)(Ze.Fragment,{children:r}):(0,Ze.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Ze.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Ze.jsx)(n,{...o.validatedProps})}var ut=require("zod"),Qe=require("react/jsx-runtime"),In=ut.z.object({step:ut.z.number().min(0),total:ut.z.number().min(1),label:ut.z.string().optional(),variant:ut.z.enum(["default","success","error"]).default("default")});function Rr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function On(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Rr(e);return(0,Qe.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Qe.jsx)("div",{className:"urun-progress-label",children:o}),(0,Qe.jsx)("div",{className:"urun-progress-bar",children:(0,Qe.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Qe.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Bt=require("zod"),wt=require("react/jsx-runtime"),Ln=Bt.z.object({state:Bt.z.enum(["thinking","generating","idle","error"]),message:Bt.z.string().optional()}),es={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Pr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??es[t]??t;return{state:t,message:n,isActive:o}}function Dn(e){let{state:t,message:r,isActive:o}=Pr(e);return(0,wt.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,wt.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,wt.jsx)("span",{className:"urun-status-message",children:r})]})}var Ut=require("react"),jt=require("zod"),At=require("react/jsx-runtime"),Vn=jt.z.object({text:jt.z.string(),streaming:jt.z.boolean().default(!1)});function xr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Fn(e){let{text:t,streaming:r}=xr(e),o=(0,Ut.useRef)(null),n=(0,Ut.useRef)(0);return(0,Ut.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,At.jsxs)("div",{className:"urun-text-stream",children:[(0,At.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,At.jsx)("span",{className:"urun-text-cursor"})]})}var Mt=require("zod"),_t=require("react/jsx-runtime"),qn=Mt.z.object({src:Mt.z.string().url(),alt:Mt.z.string().optional(),caption:Mt.z.string().optional()});function Er(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Hn(e){let{src:t,alt:r,caption:o}=Er(e);return(0,_t.jsxs)("figure",{className:"urun-image-frame",children:[(0,_t.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,_t.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Oe=require("zod"),ct=require("react/jsx-runtime"),Wn=Oe.z.object({metrics:Oe.z.array(Oe.z.object({label:Oe.z.string(),value:Oe.z.union([Oe.z.string(),Oe.z.number()]),unit:Oe.z.string().optional()}))});function wr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Bn(e){let{metrics:t}=wr(e);return(0,ct.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ct.jsxs)("div",{className:"urun-metric-card",children:[(0,ct.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ct.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var J=require("react"),Xn=require("react/jsx-runtime");function We(e){return e&&typeof e=="object"?e:null}function Ur(e){if(typeof e=="string")return e;let t=We(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function ts(e){if(typeof e=="string")return"delta";let t=We(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function rs(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function ns(e){let t=We(e),r=t?.body;return rs(r,We(We(r)?.error)?.message,We(r)?.error,We(r)?.message,We(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var lt=class extends Error{name="TextStreamError"},os=4,Ar=3,Mr=240,jn=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function Kn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function ss(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function _r(e){let{session:t,stream:r}=e,o=(0,J.useRef)(e);(0,J.useEffect)(()=>{o.current=e});let n=(0,J.useRef)(null),s=(0,J.useRef)(()=>{}),i=(0,J.useRef)(null),a=(0,J.useRef)(""),c=(0,J.useRef)(""),u=(0,J.useRef)(null),m=(0,J.useRef)(!1),l=(0,J.useRef)(!1),g=(0,J.useRef)(!1),h=(0,J.useRef)(null),w=(0,J.useRef)(Kn()),v=(0,J.useCallback)(S=>{if(n.current=S,!S){i.current=null;return}let C=i.current;if(C&&C.parentNode===S)return;let p=S.ownerDocument.createTextNode(c.current);S.appendChild(p),i.current=p,a.current.length>0&&s.current()},[]),d=(0,J.useCallback)(()=>{u.current=null;let S=i.current,C=a.current;if(C.length>0){let A=o.current,x=A.smoothCharsPerFrame??Ar,N=A.smoothThreshold??Mr,E=A.smooth&&C.length<=N?C.slice(0,x):C;a.current=C.slice(E.length),c.current+=E,S?.appendData(E)}let p=w.current,T=c.current.length,P=h.current===null?0:Math.max(0,jn()-h.current),U=Math.round(T/os);if(p.chars=T,p.tokens=U,p.elapsedMs=P,p.tokensPerSecond=P>0?U*1e3/P:0,a.current.length>0){b(),o.current.onMeter?.(p);return}if(!m.current&&!g.current){g.current=!0,p.done=!0,o.current.onMeter?.(p),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(p)},[]),b=(0,J.useCallback)(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>d()))},[d]);s.current=b,(0,J.useEffect)(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,h.current=null,m.current=!0,ss(w.current),i.current&&(i.current.data="");let S=!1,C=null;return(async()=>{try{for(C=t.stream(r).messages()[Symbol.asyncIterator]();;){let T=await C.next();if(S)return;if(T.done)break;let P=T.value,U=ts(P);if(U==="error")throw new lt(ns(P));if(U==="done")break;if(U==="ignore")continue;let A=Ur(P);A&&(h.current===null&&(h.current=jn()),a.current+=A,b())}if(S)return;C.return?.(void 0),m.current=!1,b()}catch(p){if(S)return;C?.return?.(void 0),l.current=!0,m.current=!1,o.current.onError?.(p instanceof Error?p:new lt(String(p))),b()}})(),()=>{S=!0,m.current=!1,C?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,b]);let f=(0,J.useCallback)(()=>c.current,[]);return{ref:v,meterRef:w,getText:f}}function $n(e,t=250){let[r,o]=(0,J.useState)(Kn);return(0,J.useEffect)(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function Gn(e){let{className:t,style:r,...o}=e,{ref:n}=_r(o);return(0,Xn.jsx)("span",{ref:n,className:t,style:r})}var zn=require("react");var Yn=require("react/jsx-runtime"),Jn=(0,zn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Yn.jsx)(Ye,{ref:r,stream:o,...n})});var G=require("react"),Zn=require("@urun-sh/core");var eo=require("react/jsx-runtime"),is=1e3,as=1e3;function Nr(...e){console.debug("[audio]",...e)}var Nt=(0,G.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:m}=t,l=Ue(),g=o??l,h=(0,G.useRef)(null),w=(0,G.useRef)(null),v=(0,G.useRef)(null),d=(0,G.useRef)(null),b=(0,G.useRef)(null),f=(0,G.useRef)(0),S=(0,G.useRef)(c);S.current=c;let C=(0,G.useRef)(u);C.current=u;let p=(0,G.useCallback)(y=>{v.current!==y&&(v.current=y,C.current?.(y))},[]),T=(0,G.useCallback)(()=>{if(typeof MediaStream>"u")return null;w.current||(w.current=new MediaStream);let y=h.current;return y&&y.srcObject!==w.current&&w.current.getAudioTracks().length>0&&(y.srcObject=w.current),w.current},[]),P=(0,G.useCallback)(()=>{f.current=0,b.current!==null&&cancelAnimationFrame(b.current),b.current=null,d.current!==null&&clearTimeout(d.current),d.current=null},[]),U=(0,G.useCallback)(y=>{b.current=null,d.current=null,T(),N.current(`${y}:retry`)},[T]),A=(0,G.useCallback)(y=>{if(!h.current||b.current!==null||d.current!==null)return;let W=w.current;if(!(!!W&&W.getAudioTracks().some(L=>L.readyState==="live"))){P();return}let R=f.current;if(f.current=R+1,R===0&&typeof requestAnimationFrame=="function"){b.current=requestAnimationFrame(()=>U(y));return}d.current=setTimeout(()=>U(y),as)},[P,U]),x=(0,G.useCallback)(y=>{let H=h.current;if(!H)return;let W=H.play();!W||typeof W.then!="function"||W.then(()=>{H.muted||p(!0),P()}).catch(ee=>{let R=ee instanceof Error?ee.name:String(ee);if(R==="AbortError"){Nr(`play() aborted (${y}); retrying on the ladder`),A(`${y}:abort`);return}if(R==="NotAllowedError"){Nr(`play() blocked pending a user gesture (${y})`),p(!1),A(`${y}:blocked`);return}Nr(`play() failed (${y})`,ee)})},[p]),N=(0,G.useRef)(()=>{});N.current=x;let E=(0,G.useCallback)(y=>{let H=T();if(H){for(let W of H.getAudioTracks())W!==y&&H.removeTrack(W);y&&!H.getAudioTracks().includes(y)&&H.addTrack(y),T(),y&&x("track-attach"),S.current?.(y)}},[T,x]),q=(0,G.useCallback)(()=>{let y=h.current;y&&(T(),y.muted=!1,x("gesture"),Je(),p(!0))},[T,x,p]);(0,G.useImperativeHandle)(r,()=>({unlock:q,get unlocked(){return v.current===!0},get element(){return h.current}}),[q]);let Y=(0,G.useCallback)(()=>{A("pause-event")},[A]),z=(0,G.useCallback)(y=>{let H=h.current;H&&H!==y&&H.removeEventListener("pause",Y),h.current=y,y&&(y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),T(),y.addEventListener("pause",Y)),m?.(y)},[T,m,Y]),Z=s!==void 0;return(0,G.useEffect)(()=>{if(Z){E(s??null);return}if(!g)return;let y=g.stream(n),H=()=>{let _=w.current;return _?_.getAudioTracks()[0]??null:null},W=_=>{if(_!==H()&&(E(_),_)){let j=()=>{H()===_&&E(null)};_.addEventListener("ended",j)}},ee=y.track;ee&&ee.readyState==="live"&&W(ee);let R=y.on("track",_=>{_&&_.readyState!=="live"||W(_)}),L=setInterval(()=>{let _=y.track;_&&_.readyState==="live"&&W(_)},is);return()=>{R(),clearInterval(L)}},[g,n,Z,s,E]),(0,G.useEffect)(()=>(0,Zn.observePageLifecycle)(()=>{Je(),v.current===!0&&x("foreground")}),[x]),(0,G.useEffect)(()=>()=>{d.current&&clearTimeout(d.current),b.current!==null&&cancelAnimationFrame(b.current),b.current=null},[]),(0,eo.jsx)("audio",{ref:z,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Qn=Nt;var X=require("react"),Be=require("@urun-sh/core");var ro=require("react/jsx-runtime"),Ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Kt(...e){console.debug("[voice]",...e)}function us(e){return e instanceof Be.SessionFailedError&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var It=(0,X.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=Ir,connectTimeoutMs:c,attempts:u=3,retryDelayMs:m=1500,onActiveChange:l,onError:g,onMicStream:h,onTrack:w,onUnlockChange:v,capture:d}=t,b=Ue(),f=o??b,S=(0,X.useRef)(null),C=(0,X.useRef)(null),p=(0,X.useRef)(null),T=(0,X.useRef)([]),P=(0,X.useRef)(!1),U=(0,X.useRef)(l);U.current=l;let A=(0,X.useRef)(g);A.current=g;let x=(0,X.useRef)(h);x.current=h;let N=(0,X.useCallback)(R=>{P.current!==R&&(P.current=R,U.current?.(R))},[]),E=(0,X.useCallback)(()=>{for(let R of T.current)R();T.current=[],p.current?.release(),p.current=null,C.current&&(C.current=null,x.current?.(null))},[]),q=(0,X.useCallback)(async()=>{let R=p.current;if(R){let D=await R.update(a);return C.current=R.stream,x.current?.(R.stream),D}let _=await(d??(0,Be.sharedCaptureController)()).claim("audio",a);p.current=_,T.current=[_.onTrack((D,Q)=>{C.current=Q,x.current?.(Q),P.current&&f?.stream(n).attach(D).catch(me=>Kt("mic re-attach after one-capture re-acquire failed",me))}),_.onLost(D=>{p.current=null,T.current=[],C.current=null,x.current?.(null),N(!1),A.current?.(D)})],C.current=_.stream,x.current?.(_.stream);let j=_.track;if(!j)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return j},[d,a,f,n,N]),Y=(0,X.useCallback)(async()=>{E(),N(!1),await f?.stream(n).detach().catch(()=>{})},[f,n,E,N]),z=(0,X.useCallback)(async()=>{if(!f)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");S.current?.unlock();let R;try{R=await q()}catch(j){E();let D=(0,Be.sessionFailureFromMediaError)(j,f.status);throw A.current?.(D),D}let L;for(let j=1;j<=u;j++)try{await f.whenLive(c!==void 0?{timeout:c}:void 0),await f.stream(n).attach(R),N(!0);return}catch(D){if(L=D,Kt(`start attempt ${j}/${u} failed`,D),us(D))break;f.connect?.(),j<u&&await new Promise(Q=>setTimeout(Q,m))}E(),N(!1);let _=L instanceof Error?L:new Error(String(L??"voice start failed"));throw A.current?.(_),_},[f,n,c,u,m,q,E,N]);(0,X.useImperativeHandle)(r,()=>({start:z,stop:Y,unlock:()=>S.current?.unlock(),get active(){return P.current},get micStream(){return C.current},get audio(){return S.current}}),[z,Y]);let Z=(0,X.useRef)(z);Z.current=z;let y=(0,X.useRef)(null),H=(0,X.useCallback)((R,L)=>{R.promise.then(()=>{L&&(E(),N(!1)),R.session.stream(R.streamName).detach().catch(()=>{})})},[E,N]);(0,X.useEffect)(()=>{if(!i||!f)return;let R=y.current;R&&(R.session!==f||R.streamName!==n)&&(R.disposeTimer&&clearTimeout(R.disposeTimer),H(R,!1),R=null),R?R.disposeTimer&&(clearTimeout(R.disposeTimer),R.disposeTimer=null):(R={session:f,streamName:n,promise:Z.current().catch(()=>{}),refCount:0,disposeTimer:null},y.current=R),R.refCount+=1;let L=R;return()=>{L.refCount-=1,!(L.refCount>0)&&(L.disposeTimer=setTimeout(()=>{y.current===L&&(y.current=null),H(L,!0)},0))}},[i,f,n,H]);let W=(0,X.useRef)(!1),ee=(0,X.useCallback)(async()=>{if(!f||!P.current||W.current)return;let R=C.current?.getAudioTracks()[0]??null;if(R&&R.readyState==="live"){try{await f.stream(n).attach(R)}catch(L){Kt("foreground mic re-assert failed (will retry on next pass)",L)}return}W.current=!0;try{let L=await q();await f.stream(n).attach(L)}catch(L){let _=L instanceof Error?L:new Error(String(L));Kt("foreground mic re-acquire failed",_),A.current?.(_)}finally{W.current=!1}},[f,n,q]);return(0,X.useEffect)(()=>{let R=()=>{ee()};return f&&typeof f.onRecovery=="function"?f.onRecovery(R):(0,Be.observePageLifecycle)(R)},[f,ee]),(0,X.useEffect)(()=>E,[E]),s?(0,ro.jsx)(Nt,{ref:S,session:f,stream:n,onTrack:w,onUnlockChange:v}):null}),to=It;var De=require("react");var $t=require("react");var Or={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,$t.useState)(Or);return(0,$t.useEffect)(()=>{if(!e){i(Or);return}let a=Rt();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,m;try{u=a.createMediaStreamSource(c),m=a.createAnalyser(),m.fftSize=r,u.connect(m)}catch{return}let l=new Uint8Array(m.fftSize),h=setInterval(()=>{m.getByteTimeDomainData(l);let w=0;for(let d=0;d<l.length;d++){let b=(l[d]-128)/128;w+=b*b}let v=Math.sqrt(w/l.length);i(d=>{let b=v>n;return Math.abs(d.level-v)<.005&&d.speaking===b?d:{level:v,speaking:b}})},o);return()=>{clearInterval(h),u.disconnect(),i(Or)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),cs={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ls={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},no=(0,De.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:m,onMicStream:l,capture:g}=t,h=Ue(),w=o??h,v=(0,De.useRef)(null),[d,b]=(0,De.useState)(null),f=(0,De.useRef)(l);f.current=l;let{level:S,speaking:C}=Gt(a?d:null);return(0,De.useImperativeHandle)(r,()=>({start:()=>{let p=v.current;return p?p.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>v.current?.stop()??Promise.resolve(),get active(){return v.current?.active??!1},get micStream(){return v.current?.micStream??null}}),[]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(It,{ref:v,session:w,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:m,onMicStream:p=>{b(p),f.current?.(p)}}),a?(0,Le.jsx)("span",{className:c,style:cs,"data-urun-mic":"","data-urun-mic-active":d?"true":"false","data-urun-mic-speaking":C?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(S*100)/100,children:(0,Le.jsx)("span",{style:ls,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(S*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var dt=require("@urun-sh/core"),I=require("react");var be=require("react/jsx-runtime"),Dr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Lr(...e){console.debug("[camera]",...e)}function ds(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function ps(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var Vr=(0,I.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:m="auto",connectTimeoutMs:l,visible:g=!1,className:h,videoClassName:w,onActiveChange:v,onError:d,onStream:b,onTrack:f,children:S,capture:C,flipControl:p="auto",flipControlClassName:T,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":c??"environment",A=Ue(),x=o??A,N=(0,I.useRef)(null),E=(0,I.useRef)(null),q=(0,I.useRef)(null),Y=(0,I.useRef)([]),z=(0,I.useRef)(null),Z=(0,I.useRef)(!1),y=(0,I.useRef)(!1),H=(0,I.useRef)(U),[W,ee]=(0,I.useState)(U),[R,L]=(0,I.useState)(!1),[_,j]=(0,I.useState)(null),[D,Q]=(0,I.useState)(!1),[me]=(0,I.useState)(ds),ae=(0,I.useRef)(v);ae.current=v;let le=(0,I.useRef)(d);le.current=d;let we=(0,I.useRef)(b);we.current=b;let he=(0,I.useRef)(f);he.current=f;let qe=(0,I.useRef)(P);qe.current=P;let fe=(0,I.useCallback)(B=>{Z.current!==B&&(Z.current=B,L(B),ae.current?.(B))},[]);(0,I.useEffect)(()=>{if(!R){j(null);return}let B=!1,K=()=>{ps().then(ke=>{B||(j(ke),ke&&qe.current?.(ke))})};K();let ye=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ye?.addEventListener=="function"?(ye.addEventListener("devicechange",K),()=>{B=!0,ye.removeEventListener?.("devicechange",K)}):()=>{B=!0}},[R]);let de=(0,I.useCallback)(B=>{let K=N.current;K&&(K.muted=!0,K.defaultMuted=!0,K.setAttribute("muted",""),K.setAttribute("playsinline",""),K.setAttribute("webkit-playsinline",""),K.srcObject=B,B&&K.play()?.catch?.(ye=>Lr("preview play() failed",ye)))},[]),se=(0,I.useCallback)(()=>{y.current=!1,z.current?.(),z.current=null;for(let B of Y.current)B();Y.current=[],q.current?.release(),q.current=null,E.current&&(E.current=null,we.current?.(null),he.current?.(null)),de(null)},[de]),k=(0,I.useCallback)((B,K)=>{z.current?.(),E.current=K,de(K),we.current?.(K);let ye=()=>{E.current===K&&(Lr("camera track ended (device removed or permission revoked)"),se(),fe(!1))};B.addEventListener("ended",ye),z.current=()=>B.removeEventListener("ended",ye)},[de,se,fe]),V=(0,I.useCallback)(async B=>{let K=n!==!1;if(K&&!x)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ye={...Dr,...s,facingMode:B},ke;try{let Re=q.current;if(Re)ke=await Re.update(ye);else{let yt=await(C??(0,dt.sharedCaptureController)()).claim("video",ye);if(q.current=yt,Y.current=[yt.onTrack((kt,Mo)=>{k(kt,Mo),Z.current&&(!K||!x||x.stream(n).attachVideo(kt).then(()=>he.current?.(kt)).catch(_o=>Lr("camera re-publish after one-capture re-acquire failed",_o)))}),yt.onLost(kt=>{q.current=null,Y.current=[],se(),fe(!1),le.current?.(kt)})],!yt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ke=yt.track}}catch(Re){let nt=(0,dt.sessionFailureFromMediaError)(Re,x?.status);throw le.current?.(nt),nt}H.current=B,ee(B),k(ke,q.current?.stream??new MediaStream([ke]));try{K&&x&&(x.connect?.(),await x.whenLive(l!==void 0?{timeout:l}:void 0),await x.stream(n).attachVideo(ke)),y.current=K?n:!1}catch(Re){se(),fe(!1);let nt=Re instanceof Error?Re:new Error(String(Re));throw le.current?.(nt),nt}he.current?.(ke),fe(!0)},[x,n,s,l,C,k,se,fe]),M=(0,I.useCallback)(B=>V(B?.facingMode??H.current),[V]),$=(0,I.useCallback)(async B=>{let K=y.current===n;Z.current&&H.current===B&&K||await V(B)},[V,n]),te=(0,I.useCallback)(()=>V(H.current==="environment"?"user":"environment"),[V]),ve=(0,I.useCallback)(async()=>{se(),fe(!1),n!==!1&&await x?.stream(n).detachVideo().catch(()=>{})},[x,n,se,fe]),O=(0,I.useCallback)(async B=>{let K=N.current;if(!K)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,dt.captureStillFromVideo)(K,B)},[]);(0,I.useImperativeHandle)(r,()=>({start:M,stop:ve,flip:te,setFacingMode:$,capturePhoto:O,get active(){return Z.current},get facingMode(){return H.current},get stream(){return E.current},get element(){return N.current}}),[M,ve,te,$,O]);let Ae=(0,I.useRef)($);if(Ae.current=$,(0,I.useEffect)(()=>{u&&(n!==!1&&!x||Ae.current(U).catch(()=>{}))},[u,x,U,n]),(0,I.useEffect)(()=>se,[se]),!g)return null;let rt=m==="auto"?W==="user":m,Me=R&&(p===!0||p==="auto"&&me&&(_?.length??0)>1),_e=()=>{D||(Q(!0),te().catch(()=>{}).finally(()=>Q(!1)))};return(0,be.jsxs)("div",{className:h,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":W,children:[(0,be.jsx)("video",{ref:N,className:w,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...rt?{transform:"scaleX(-1)"}:{}}}),Me?(0,be.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:_e,disabled:D,className:T,style:T?{opacity:D?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:D?.6:1},children:(0,be.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,be.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,be.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,be.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,be.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,be.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,S]})}),oo=(0,I.forwardRef)(function({preview:t=!0,...r},o){return(0,be.jsx)(Vr,{ref:o,...r,visible:t,autoStart:!1})});var pt=require("@urun-sh/core"),oe=require("react");function so(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,oe.useState)(null),[a,c]=(0,oe.useState)(null),[u,m]=(0,oe.useState)(!1),[l,g]=(0,oe.useState)(null),[h]=(0,oe.useState)(pt.cameraCaptureAvailable),w=(0,oe.useRef)(n);w.current=n;let v=(0,oe.useRef)(null),d=(0,oe.useRef)(0),b=(0,oe.useCallback)(T=>{v.current&&URL.revokeObjectURL(v.current),v.current=T?URL.createObjectURL(new Blob([T.bytes],{type:T.type})):null,c(v.current),i(T),w.current?.(T)},[]);(0,oe.useEffect)(()=>()=>{d.current++,v.current&&URL.revokeObjectURL(v.current),v.current=null},[]);let f=(0,oe.useCallback)(async T=>{let P=++d.current;m(!0),g(null);try{let U=await T();if(d.current!==P)return;b(U)}catch(U){if(d.current!==P)return;g((0,pt.referenceImageErrorMessage)(U))}finally{d.current===P&&m(!1)}},[b]),S=(0,oe.useCallback)(T=>f(()=>(0,pt.normalizeReferenceImage)(T,{maxSize:t,type:r,quality:o,source:"file"})),[f,t,r,o]),C=(0,oe.useCallback)(T=>f(()=>T.capturePhoto({maxSize:t,type:r,quality:o})),[f,t,r,o]),p=(0,oe.useCallback)(()=>{d.current++,g(null),m(!1),b(null)},[b]);return{reference:s,previewUrl:a,pick:S,capture:C,clear:p,busy:u,error:l,cameraAvailable:h}}var Xt=require("react");function io(e,t){let[r,o]=(0,Xt.useState)(null);return(0,Xt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var co=require("react");var Jt=require("react");var ao=require("zustand/vanilla"),uo=require("zustand"),ms=()=>{};function zt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=(0,ao.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):ms,c=(u=>(0,uo.useStore)(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function mt(e,t){let r=(0,Jt.useMemo)(()=>zt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Jt.useEffect)(()=>r.bind(),[r]),r}function lo(e,t,r){let n=mt(e,t)(r??(a=>a)),s=(0,co.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var Yt=require("react");function po(e){let[t,r]=(0,Yt.useState)(null);return(0,Yt.useEffect)(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}var Qt=require("react");var je=200;function Ve(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function ft(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Zt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function er(e,t,r={}){let o=r.cap??200,[n,s]=(0,Qt.useState)([]);return(0,Qt.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>Ve(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var xe=require("react/jsx-runtime");function mo({session:e,name:t,cap:r,className:o}){let n=er(e,t,{cap:r});return(0,xe.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,xe.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,xe.jsx)("code",{children:t}),(0,xe.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,xe.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,xe.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,xe.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,xe.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,xe.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ft(s.payload)]},`${s.at}-${i}`))})]})}var Ot=require("react");var Se=require("react/jsx-runtime");function Lt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,Ot.useState)(""),[i,a]=(0,Ot.useState)(null),c=(0,Ot.useCallback)(()=>{let u=Zt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return(0,Se.jsxs)("div",{className:"urun-doc-patch",children:[(0,Se.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),(0,Se.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,Se.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?(0,Se.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function fo({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=mt(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return(0,Se.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,Se.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,Se.jsx)("code",{children:t}),(0,Se.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,Se.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,Se.jsx)(Lt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}var tr=require("react");var Fe=require("react/jsx-runtime");function go(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function So({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,tr.useState)([]);return(0,tr.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ve(c,{at:Date.now(),direction:"in",text:go(ft(a))},r))}):void 0),[e,t,r]),(0,Fe.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,Fe.jsx)(Lt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>Ve(c,{at:Date.now(),direction:"out",text:go(a)},r))}}),(0,Fe.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,Fe.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,Fe.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,Fe.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,Fe.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var rr=require("react");var et=require("react/jsx-runtime");function ho({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,rr.useState)([]),a=t.join(","),c=r.join(",");return(0,rr.useEffect)(()=>{if(i([]),!e)return;let u=(l,g)=>i(h=>Ve(h,{at:Date.now(),kind:l,text:g},o)),m=[];m.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);m.push(g.on("track",h=>u("track",`${l}: ${h?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);m.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>m.forEach(l=>l())},[e,a,c,o]),(0,et.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,et.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,m)=>(0,et.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,et.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,et.jsx)("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${m}`))})}var cr=require("@urun-sh/core");var nr=require("react");function Te(e){let[t,r]=(0,nr.useState)(e?.phase??null);return(0,nr.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var yo=require("@urun-sh/core");var gt=require("react"),vo=require("@urun-sh/core");function or(e){let t=Te(e),r=(0,vo.isWakingPhase)(t?.name),o=(0,gt.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,gt.useState)(s);return(0,gt.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var Ke=require("react/jsx-runtime");function sr({session:e,render:t,className:r}){let o=or(e);return!o.waking||!o.phase?null:(0,Ke.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,Ke.jsxs)(Ke.Fragment,{children:[(0,Ke.jsx)("span",{className:"urun-session-waking-label",children:(0,yo.describeSessionPhase)(o.phase)})," ",(0,Ke.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var ar=require("react");var $e=require("react"),fs={event:null,elapsedMs:0};function ir(e,t){let[r,o]=(0,$e.useState)(null),n=(0,$e.useRef)(0);(0,$e.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,$e.useState)(0);return(0,$e.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:fs}var St=require("react/jsx-runtime"),gs={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function Ss(e){let[t,r]=(0,ar.useState)(!1);return(0,ar.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function ur({session:e,stream:t,videoElement:r,render:o,className:n}){let s=ir(e,t),i=Ss(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return(0,St.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):(0,St.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,St.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??gs[c]})," ",(0,St.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var Ce=require("react/jsx-runtime"),hs={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function ko({session:e,className:t}){let r=Te(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,Ce.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,Ce.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,Ce.jsx)("span",{className:"urun-session-status-label",children:hs[o]}),n?(0,Ce.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function bo({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=Te(e);if(s?.name==="live")return(0,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,Ce.jsx)(ur,{session:e})]});let i=r?r(s):(0,Ce.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&(0,cr.isWakingPhase)(s.name)?(0,Ce.jsx)(sr,{session:e}):s&&s.name!=="idle"?(0,cr.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return(0,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,Ce.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var lr=require("react");var Co=require("react/jsx-runtime");function Fr(e){return Te(e)?.endsAt??null}function vs(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function To({session:e,urgentMs:t=6e4,className:r}){let n=Fr(e)?.getTime()??null,[s,i]=(0,lr.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,lr.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=vs(s);return(0,Co.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var Ro=require("@urun-sh/core");var ht=require("react/jsx-runtime"),ys=new Set(["paused","error"]);function qr({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=Te(e);if(!s||!ys.has(s.name))return null;let i=o?o(s):(0,ht.jsx)("span",{className:"urun-session-paused-copy",children:(0,Ro.describeSessionPhase)(s)});return(0,ht.jsxs)("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var Po=qr;var Ge=require("react"),tt=require("react/jsx-runtime");function Hr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Wr(e){let t=(0,Ge.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,Ge.useState)(()=>t?Hr(t.get("idle")):null);return(0,Ge.useEffect)(()=>{if(!t){o(null);return}return o(Hr(t.get("idle"))),t.on("change",()=>o(Hr(t.get("idle"))))},[t]),r}function ks(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function xo({session:e,onStillHere:t,className:r}){let o=Wr(e),n=o?.deadlineEpochS??null,[s,i]=(0,Ge.useState)(null);if((0,Ge.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,tt.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,tt.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,tt.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,tt.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${ks(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,tt.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var Ee=require("react");function bs(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function dr(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=(0,Ee.useState)(null),[s,i]=(0,Ee.useState)(e!==null),[a,c]=(0,Ee.useState)(null),u=(0,Ee.useRef)(e),m=(0,Ee.useCallback)(async g=>{i(!0);try{let h=await g.getBalance();if(u.current!==g)return;n(h),c(null)}catch(h){if(u.current!==g)return;c(h instanceof Error?h:new Error(String(h)))}finally{u.current===g&&i(!1)}},[]);(0,Ee.useEffect)(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(m(e),r!==void 0&&r>0){let g=setInterval(()=>{m(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,m]);let l=(0,Ee.useCallback)(async()=>{let g=u.current;g&&await m(g)},[m]);return{balance:o,isExhausted:bs(o),loading:s,error:a,refresh:l}}var pr=require("react/jsx-runtime");function Eo({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=dr(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return(0,pr.jsx)("div",{className:i,children:t});let a=r?r(n):(0,pr.jsx)("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return(0,pr.jsx)("div",{className:i,children:a})}var Xe=require("@urun-sh/core");var vt=require("react"),wo=require("@urun-sh/core");function Uo(e){let t=(0,vt.useContext)(He),[r,o]=(0,vt.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,m=t?.getAccessToken,l=t?.authProvider;return(0,vt.useEffect)(()=>{if(!a||!c||!n||!s)return;let g=!1,h=()=>{(0,wo.prewake)({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:m,authProvider:l}).then(v=>{g||o(v)}).catch(()=>{})};h();let w=setInterval(h,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(w)}},[n,s,i,a,c,u,m,l]),r}var mr=require("react");function Ao(e){let[t,r]=(0,mr.useState)(null);return(0,mr.useEffect)(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}var fr=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,CreditsClient,CreditsError,CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_SMOOTH_CHARS_PER_FRAME,DEFAULT_SMOOTH_THRESHOLD,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,ReprojectedVideo,Session,StatusBadge,StatusBadgeSchema,Text,TextStream,TextStreamError,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunCreditsGate,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionPaused,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createCreditsClient,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,textDelta,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useCredits,useDocStore,useGenerationTick,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useReferenceImage,useRequest,useSession,useSessionDirectory,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionStats,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useText,useTextMeter,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
|
2
|
+
"use strict";var gr=Object.defineProperty;var Oo=Object.getOwnPropertyDescriptor;var Io=Object.getOwnPropertyNames;var Lo=Object.prototype.hasOwnProperty;var Do=(e,t)=>{for(var r in t)gr(e,r,{get:t[r],enumerable:!0})},Vo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Io(t))!Lo.call(e,n)&&n!==r&&gr(e,n,{get:()=>t[n],enumerable:!(o=Oo(t,n))||o.enumerable});return e};var Fo=e=>Vo(gr({},"__esModule",{value:!0}),e);var Rs={};Do(Rs,{Audio:()=>Nt,Camera:()=>Fr,ComponentRenderer:()=>On,CreditsClient:()=>Xe.CreditsClient,CreditsError:()=>Xe.CreditsError,CreditsUnauthorizedError:()=>Xe.CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS:()=>Vr,DEFAULT_LOG_CAP:()=>je,DEFAULT_SMOOTH_CHARS_PER_FRAME:()=>Ar,DEFAULT_SMOOTH_THRESHOLD:()=>Mr,DEFAULT_VOICE_CONSTRAINTS:()=>Ir,DocPatchForm:()=>Lt,Image:()=>Yn,ImageFrame:()=>Wn,ImageFrameSchema:()=>Hn,MetricsPanel:()=>jn,MetricsPanelSchema:()=>Bn,Mic:()=>oo,OPERATOR_CHORD_LABEL:()=>Qr,OPERATOR_TOKEN_STORAGE_KEY:()=>Yr,ProgressCard:()=>Ln,ProgressCardSchema:()=>In,ReprojectedVideo:()=>An,Session:()=>bn,StatusBadge:()=>Vn,StatusBadgeSchema:()=>Dn,Text:()=>Xn,TextStream:()=>qn,TextStreamError:()=>lt,TextStreamSchema:()=>Fn,UrunActivationOverlay:()=>ur,UrunAudio:()=>eo,UrunAuthProvider:()=>Ct,UrunCamera:()=>so,UrunControlSender:()=>ho,UrunCreditsGate:()=>wo,UrunDocPanel:()=>go,UrunErrorBoundary:()=>ot,UrunEventSpine:()=>vo,UrunIdleWarning:()=>Eo,UrunJwtProvider:()=>Xr,UrunProvider:()=>un,UrunSessionClock:()=>Co,UrunSessionEnded:()=>xo,UrunSessionGate:()=>To,UrunSessionPaused:()=>Hr,UrunSessionStatus:()=>bo,UrunSessionWaking:()=>sr,UrunStreamTail:()=>fo,UrunVoice:()=>ro,Video:()=>Ye,Voice:()=>Ot,authMode:()=>Tt,createCreditsClient:()=>Xe.createCreditsClient,createDocStore:()=>zt,describeSessionPhase:()=>fr.describeSessionPhase,formatPayload:()=>ft,getUrunAudioContext:()=>Rt,isWakingPhase:()=>fr.isWakingPhase,parseJsonObject:()=>Zt,pushCapped:()=>Ve,readOperatorToken:()=>Sr,registerComponent:()=>_n,resumeUrunAudioContext:()=>Je,textDelta:()=>Ur,urunPublicEnv:()=>Pe,useActivation:()=>ir,useApp:()=>dn,useChat:()=>yn,useCompletion:()=>Sn,useConfirmOnLeave:()=>qt,useCredits:()=>dr,useDocStore:()=>mt,useGenerationTick:()=>mo,useImageFrame:()=>Er,useInputPresence:()=>kn,useMetricsPanel:()=>wr,useOperatorOverride:()=>Ft,useProgressCard:()=>Rr,useReferenceImage:()=>io,useRequest:()=>fn,useSession:()=>Tn,useSessionDirectory:()=>mn,useSessionDoc:()=>po,useSessionEndsAt:()=>qr,useSessionIdle:()=>Br,useSessionPhase:()=>Te,useSessionStats:()=>Mo,useSessionTrack:()=>ao,useSessionWake:()=>or,useStatusBadge:()=>Pr,useStreamMessages:()=>er,useText:()=>_r,useTextMeter:()=>Gn,useTextStream:()=>xr,useUrunAudioLevel:()=>Gt,useUrunAuth:()=>Dt,useUrunPrewake:()=>Ao,usesWorkOSAuth:()=>$r});module.exports=Fo(Rs);var le=require("react"),an=require("@urun-sh/core/internal");var jr=require("react"),bt=require("react/jsx-runtime"),ot=class extends jr.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,bt.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,bt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,bt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var Kr=require("react"),He=(0,Kr.createContext)(null);function Ne(e){return e&&e.trim()?e.trim():void 0}function Pe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Ne(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ne(typeof process<"u"?process.env?.[e]:void 0)}}function Tt(){let e=Pe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Pe("VERCEL_ENV")==="production"?"workos":Pe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function $r(){return Tt()==="workos"}var st=require("react"),zr=require("react/jsx-runtime"),Gr=(0,st.createContext)(null);function Ct({getAccessToken:e,children:t}){let r=(0,st.useMemo)(()=>({getAccessToken:e}),[e]);return(0,zr.jsx)(Gr.Provider,{value:r,children:t})}var Xr=Ct;function Dt(){return(0,st.useContext)(Gr)}var Vt=require("react"),Yr="urun.operator_token",Zr=null,Jr="op",Qr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function en(){return typeof window<"u"}function Sr(){return Zr}function qo(){if(!en())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Jr);if(!r)return null;Zr=r,t.delete(Jr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Ho(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Ft(e){let t=(0,Vt.useRef)(e);t.current=e,(0,Vt.useEffect)(()=>{if(!en())return;qo();let r=o=>{if(!Ho(o))return;let n=Sr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var tn=require("react");function qt(e=!0){(0,tn.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var Oe=require("react/jsx-runtime"),Wo="/api/urun-token",Bo=1e4;function jo(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}var rn=3,Ko=new Set([502,503,504]);function nn(e){return new Promise(t=>setTimeout(t,(0,an.computeBackoffDelay)(e)))}async function on(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=rn-1)throw a;await nn(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!Ko.has(o.status)||r>=rn-1)throw a;await nn(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function sn(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function hr(e){let t=e===void 0?void 0:JSON.stringify(e);return(0,le.useMemo)(()=>e,[t])}function $o(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Oe.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Oe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Oe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function un({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:v,sessionStats:C,confirmOnLeave:h=!1,fallback:p,errorFallback:k,children:R}){let d=n===void 0&&t===void 0;if(!d&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!d&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let b=r??o;if(d&&(typeof b!="string"||b.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);qt(h);let[m,w]=(0,le.useState)(),[P,x]=(0,le.useState)(null),A=(0,le.useRef)(void 0),M=(0,le.useRef)(null),[L,E]=(0,le.useState)(null);Ft(_=>E({jwt:_}));let O=Dt(),J=Pe("NEXT_PUBLIC_SESSION_TOKEN")??Pe("NEXT_PUBLIC_URUN_JWT"),X=Tt(),z=L!==null,Z=X==="workos"&&!n&&!z&&!d,ne=n??(X==="jwt"?J:void 0)??m?.token,Q=z?L.jwt:ne,T=s??Pe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),W=Z&&!Q&&!O?.getAccessToken,S=t??m?.orgId,N=e??m?.gatewayUrl,V=d&&m===void 0,F=d&&m!==void 0&&!N?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,U=W?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,oe=P??F??U,se=sn("NEXT_PUBLIC_URUN_TOKEN_URL",Pe("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Wo,de=sn("NEXT_PUBLIC_URUN_EVENTS_URL",Pe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,we=(0,le.useCallback)(async _=>{if(!_?.forceRefresh){let ee=A.current;if(!ee)return ee;let ve=jo(ee);if(ve===null||ve-Date.now()>Bo)return ee}return(await(M.current??(M.current=(async()=>{try{let ee=await on(se);return A.current=ee.token,w(ee),ee}finally{M.current=null}})()))).token},[se]),he=(0,le.useCallback)(async()=>Q,[Q]),qe=typeof Q=="string"&&Q.trim().length>0,fe=Z?O?.getAccessToken:d&&!z?we:qe?he:void 0,pe=hr(g),ae=hr(v),y=hr(C),q=(0,le.useMemo)(()=>({appId:b,baseUrl:N??"",orgId:S??"",jwt:Q,getAccessToken:Z?O?.getAccessToken:d&&!z?we:void 0,authProvider:T,eventsUrl:de,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:pe,videoPlayout:ae,sessionStats:y,priority:z?"preempt":void 0}),[b,O,N,T,Q,de,S,a,u,f,l,pe,ae,y,Z,z,d,we]);return(0,le.useEffect)(()=>{if(!d)return;let _=new AbortController;return x(null),(async()=>{try{let $=await on(se,_.signal);A.current=$.token,w($)}catch($){if(_.signal.aborted)return;x($ instanceof Error?$:new Error(String($)))}})(),()=>_.abort()},[d,se]),(0,Oe.jsx)(ot,{fallback:p,children:oe?$o(k,oe):V?(0,Oe.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Oe.jsx)(He.Provider,{value:q,children:fe?(0,Oe.jsx)(Ct,{getAccessToken:fe,children:R}):R})})}var ge=require("react"),cn=require("@urun-sh/core");function ln(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Go(e,t,r){let o=ln(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function Xo(e,t,r,o){let n=ln(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var ze=new Map;var vr=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},yr=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}get directOut(){return this._stream.directOut}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},kr=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}watchDownlinkStall(t={}){return this._session.watchDownlinkStall?this._session.watchDownlinkStall(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new vr(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new yr(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function dn(){let e=(0,ge.useContext)(He);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,ge.useReducer)(i=>i+1,0),r=(0,ge.useRef)(new Map),o=(0,ge.useRef)(new Map),n=(0,ge.useRef)(null),s=(0,ge.useMemo)(()=>(0,cn.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return(0,ge.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=ze.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let f=ze.get(c);f===u&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(c,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let l=ze.get(c);!l||l.refCount!==0||(ze.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),(0,ge.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let f=(l,g)=>{let v=Go(c,l,g),C=r.current.get(v);if(C&&!C.disposed)return C;let h=Xo(e,c,l,g),p=ze.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),ze.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new kr(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},ze.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(c,f),f}})},[e,s])}var Ht=require("react"),pn=require("@urun-sh/core");function mn(){let e=(0,Ht.useContext)(He);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return(0,Ht.useMemo)(()=>(0,pn.sessionDirectory)(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}var ue=require("react");function it(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function zo(e){return e instanceof Error?e:new Error(String(e))}function fn(e,t){let r=(0,ue.useMemo)(()=>it(e),[e]),[o,n]=(0,ue.useState)(void 0),[s,i]=(0,ue.useState)(null),[a,c]=(0,ue.useState)(!1),u=(0,ue.useRef)(t);u.current=t;let f=(0,ue.useRef)(0),l=(0,ue.useRef)(null),g=(0,ue.useRef)(!0);(0,ue.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=(0,ue.useCallback)(async p=>{l.current?.abort();let k=new AbortController;l.current=k;let R=++f.current,d=()=>g.current&&f.current===R;d()&&(c(!0),i(null));try{let b=await r.request(p,{...u.current,signal:k.signal});return d()&&(n(b),c(!1),u.current?.onSuccess?.(b)),b}catch(b){let m=zo(b);throw d()&&(i(m),c(!1),u.current?.onError?.(m)),m}},[r]),C=(0,ue.useCallback)(p=>{v(p).catch(()=>{})},[v]),h=(0,ue.useCallback)(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:C,mutateAsync:v,data:o,error:s,isPending:a,reset:h}}var ce=require("react");function gn(e){return e instanceof Error?e:new Error(String(e))}var Jo=e=>typeof e=="string"?e:String(e);function Sn(e,t){let r=(0,ce.useMemo)(()=>it(e),[e]),[o,n]=(0,ce.useState)(""),[s,i]=(0,ce.useState)(!1),[a,c]=(0,ce.useState)(null),u=(0,ce.useRef)(t);u.current=t;let f=(0,ce.useRef)(0),l=(0,ce.useRef)(null),g=(0,ce.useRef)(!0);(0,ce.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=(0,ce.useCallback)(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),C=(0,ce.useCallback)(async h=>{l.current?.cancel();let p=++f.current,k=()=>g.current&&f.current===p,R=u.current,d=R?.parseChunk??Jo,b=R?.buildPayload??(E=>({prompt:E}));k()&&(n(""),c(null),i(!0));let{parseChunk:m,buildPayload:w,onFinish:P,onError:x,...A}=R??{},M="",L;try{L=r.requestStream(b(h),A),l.current=L}catch(E){let O=gn(E);k()&&(c(O),i(!1),R?.onError?.(O));return}try{for await(let E of L){if(f.current!==p)break;M+=d(E),k()&&n(M)}k()&&(i(!1),R?.onFinish?.(M))}catch(E){let O=gn(E);k()&&(c(O),i(!1),R?.onError?.(O))}finally{l.current===L&&(l.current=null)}},[r]);return{completion:o,complete:C,stop:v,isStreaming:s,error:a}}var re=require("react");function hn(e){return e instanceof Error?e:new Error(String(e))}var Yo=e=>typeof e=="string"?e:String(e),vn=0;function br(e){return vn+=1,`${e}-${vn}`}function yn(e,t){let r=(0,re.useMemo)(()=>it(e),[e]),[o,n]=(0,re.useState)(()=>(t?.initialMessages??[]).map(d=>({id:d.id??br("msg"),role:d.role,content:d.content}))),[s,i]=(0,re.useState)(""),[a,c]=(0,re.useState)(!1),[u,f]=(0,re.useState)(null),l=(0,re.useRef)(t);l.current=t;let g=(0,re.useRef)(o);g.current=o;let v=(0,re.useRef)(s);v.current=s;let C=(0,re.useRef)(0),h=(0,re.useRef)(null),p=(0,re.useRef)(!0);(0,re.useEffect)(()=>(p.current=!0,()=>{p.current=!1,h.current?.cancel(),h.current=null}),[]);let k=(0,re.useCallback)(()=>{C.current++,h.current?.cancel(),h.current=null,p.current&&c(!1)},[]),R=(0,re.useCallback)(async d=>{let b=d===void 0,m=(b?v.current:d)??"";if(!m.trim())return;h.current?.cancel();let P=++C.current,x=()=>p.current&&C.current===P,A=l.current,M=A?.parseChunk??Yo,L={id:br("msg"),role:"user",content:m},E={id:br("msg"),role:"assistant",content:""},O=[...g.current,L].map(F=>({role:F.role,content:F.content})),J=[...g.current,L,E];g.current=J,n(J),b&&i(""),f(null),c(!0);let X=A?.buildPayload??(F=>({messages:F})),{initialMessages:z,parseChunk:Z,buildPayload:ne,onFinish:Q,onError:T,...W}=A??{},S=F=>{n(U=>U.map(oe=>oe.id===E.id?{...oe,content:F}:oe))},N="",V;try{V=r.requestStream(X(O),W),h.current=V}catch(F){let U=hn(F);x()&&(f(U),c(!1),A?.onError?.(U));return}try{for await(let F of V){if(C.current!==P)break;N+=M(F),x()&&S(N)}x()&&(c(!1),A?.onFinish?.({...E,content:N}))}catch(F){let U=hn(F);x()&&(f(U),c(!1),A?.onError?.(U))}finally{h.current===V&&(h.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:R,stop:k,isStreaming:a,error:u}}var te=require("react"),at=require("@urun-sh/core"),Tr=[];function kn(e,t={}){let{field:r=at.INPUT_PRESENCE_FIELD,hz:o=at.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,te.useMemo)(()=>s?(0,at.createInputPresencePublisher)({awareness:{setLocalStateField:(m,w)=>s.setField(m,w)},field:r,hz:o}):null,[s,r,o]),a=(0,te.useRef)(null);a.current=i;let[c,u]=(0,te.useState)(!1),[f,l]=(0,te.useState)(Tr),g=(0,te.useRef)(!1);(0,te.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let v=(0,te.useCallback)(()=>{let m=a.current;l(m?m.heldKeys():Tr)},[]),C=(0,te.useCallback)(()=>{a.current?.clear(),l(Tr)},[]);(0,te.useEffect)(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,w=()=>{if(m()){g.current=!1,u(!0);return}g.current||(u(!1),C())},P=E=>{m()&&(a.current?.keyDown(E.key),v())},x=E=>{a.current?.keyUp(E.key),v()},A=E=>{m()&&a.current?.movePointer(E.movementX,E.movementY)},M=E=>{m()&&a.current?.setButtons(E.buttons)},L=()=>{C()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",P),n.addEventListener("keyup",x),n.addEventListener("mousemove",A),n.addEventListener("mousedown",M),n.addEventListener("mouseup",M),n.defaultView?.addEventListener("blur",L),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",P),n.removeEventListener("keyup",x),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",M),n.removeEventListener("mouseup",M),n.defaultView?.removeEventListener("blur",L)}},[n,C,v]);let h=(0,te.useCallback)(m=>{m.requestPointerLock?.()},[]),p=(0,te.useCallback)(()=>{g.current=!0,u(!0)},[]),k=(0,te.useCallback)(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),C()},[n,C]),R=(0,te.useCallback)(m=>{a.current?.keyDown(m),v()},[v]),d=(0,te.useCallback)(m=>{a.current?.keyUp(m),v()},[v]),b=(0,te.useCallback)((m,w)=>{a.current?.movePointer(m,w)},[]);return{engage:h,engageTouch:p,release:k,engaged:c,heldKeys:f,pressKey:R,releaseKey:d,movePointer:b}}var me=require("react"),Un=require("@urun-sh/core");var H=require("react"),wn=require("@urun-sh/core");var Wt=null;function Zo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Rt(){if(Wt)return Wt;let e=Zo();return e?(Wt=new e,Wt):null}function Je(){let e=Rt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Pt=require("react"),Cn=require("react/jsx-runtime"),Cr=(0,Pt.createContext)(null);function bn({session:e,children:t}){return(0,Cn.jsx)(Cr.Provider,{value:e,children:t})}function Ue(){return(0,Pt.useContext)(Cr)}function Tn(){let e=(0,Pt.useContext)(Cr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var xt=require("react/jsx-runtime");function Qo(e,t){return e-t>>>0<2147483648}var Rn=1e3;function Pn(...e){console.debug("[video]",...e)}function xn(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function En(e,t,r){return r?[r,t]:[e,t]}var Ye=(0,H.forwardRef)(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:f,style:l,videoClassName:g,placeholder:v,poster:C,children:h,onTrack:p,onFirstFrame:k,frameMarker:R,onFrameMarkerReached:d,onFrameMarkerUnsupported:b,onUnlockChange:m}=t,w=Ue(),P=o??w,x=(0,H.useRef)(null),A=(0,H.useRef)(null),[M,L]=(0,H.useState)(!1),[E,O]=(0,H.useState)(!1),J=(0,H.useRef)(!1),X=(0,H.useRef)(null),z=(0,H.useRef)(p);z.current=p;let Z=(0,H.useRef)(m);Z.current=m;let ne=(0,H.useRef)(k);ne.current=k;let Q=(0,H.useRef)(d);Q.current=d;let T=(0,H.useRef)(b);T.current=b;let W=(0,H.useRef)(R??null);W.current=R??null;let S=(0,H.useCallback)(y=>{X.current!==y&&(X.current=y,Z.current?.(y))},[]),N=(0,H.useRef)(null),V=(0,H.useRef)(null),F=(0,H.useCallback)((y,q=!1)=>{if(!q&&y===N.current||(N.current=y,V.current?.(),V.current=null,J.current=!1,O(!1),!y))return;let _=x.current;if(!_)return;let $=W.current,ee=$?.rtpTimestamp??null,ve=!1,D=()=>{ve||(ve=!0,T.current?.())};$&&ee==null&&D();let Ae=$!=null&&ee!=null,rt=_e=>{V.current?.(),V.current=null,J.current=!0,O(!0),ne.current?.(),_e&&Q.current?.()};if(typeof _.requestVideoFrameCallback=="function"){let _e=!1,B=0,K=(ye,ke)=>{if(!_e){if(Ae){let Re=ke?.rtpTimestamp;if(typeof Re!="number"){D(),rt(!1);return}if(!Qo(Re,ee)){B=_.requestVideoFrameCallback(K);return}rt(!0);return}rt(!1)}};B=_.requestVideoFrameCallback(K),V.current=()=>{_e=!0,_.cancelVideoFrameCallback?.(B)};return}Ae&&D();let Me=()=>{let _e=_.getVideoPlaybackQuality?.();(_e?_e.totalVideoFrames>0:_.readyState>=2&&_.videoWidth>0)&&rt(!1)};_.addEventListener("loadeddata",Me),_.addEventListener("timeupdate",Me),_.addEventListener("playing",Me),V.current=()=>{_.removeEventListener("loadeddata",Me),_.removeEventListener("timeupdate",Me),_.removeEventListener("playing",Me)},Me()},[]);(0,H.useEffect)(()=>()=>{V.current?.(),V.current=null},[]);let U=R==null?null:`${R.rtpTimestamp??""}|${R.ptsMs??""}`,oe=(0,H.useRef)(U);(0,H.useEffect)(()=>{if(oe.current===U||(oe.current=U,U==null))return;let y=N.current;y&&F(y,!0)},[U,F]);let se=(0,H.useCallback)(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let y=x.current;return y&&y.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(y.srcObject=A.current),A.current},[]),de=(0,H.useCallback)(y=>{let q=x.current;if(!q)return;let _=q.play();!_||typeof _.then!="function"||_.then(()=>{q.muted||S(!0)}).catch($=>{if(($ instanceof Error?$.name:String($))==="NotAllowedError"&&!q.muted){Pn(`play() blocked pending a user gesture (${y})`),S(!1);return}Pn(`play() failed (${y})`,$)})},[S]),we=(0,H.useCallback)(()=>{let y=x.current;y&&(se(),!y.muted&&(de("gesture"),Je(),S(!0)))},[se,de,S]),he=(0,H.useCallback)(y=>{let q=se();if(q){for(let _ of q.getVideoTracks())_!==y&&q.removeTrack(_);if(y&&!q.getVideoTracks().includes(y)){q.addTrack(y);let _=x.current;_&&(_.srcObject=q)}y&&de("track-attach"),L(y!==null),F(y),z.current?.(y)}},[se,de,F]),qe=(0,H.useCallback)(y=>{let q=se();if(q){for(let _ of q.getAudioTracks())_!==y&&q.removeTrack(_);if(y&&!q.getAudioTracks().includes(y)){q.addTrack(y);let _=x.current;_&&_.srcObject!==q&&(_.srcObject=q)}y&&de("audio-attach")}},[se,de]),fe=(0,H.useCallback)(y=>{x.current=y,y&&(a?(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted",""),X.current=null):(y.muted=!1,y.defaultMuted=!1,y.removeAttribute("muted")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),se())},[se,a]);(0,H.useImperativeHandle)(r,()=>({get element(){return x.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return J.current},unlock:we,get unlocked(){return X.current===!0}}),[we]);let pe=(0,wn.derivedLegRole)(n)!==void 0;(0,H.useEffect)(()=>{pe&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[pe,n]);let ae=i!==void 0;return(0,H.useEffect)(()=>{if(ae){he(i??null);return}if(pe){he(null);return}if(!P)return;let y=xn(P,En(n,"video")),q=()=>{let D=A.current;return D?D.getVideoTracks()[0]??null:null},_=D=>{if(D!==q()&&(he(D),D)){let Ae=()=>{q()===D&&he(null)};D.addEventListener("ended",Ae)}},$=y.track;$&&$.readyState==="live"&&_($);let ee=y.on("track",D=>{D&&D.readyState!=="live"||_(D)}),ve=setInterval(()=>{let D=y.track;D&&D.readyState==="live"&&_(D)},Rn);return()=>{ee(),clearInterval(ve)}},[P,n,pe,ae,i,he]),(0,H.useEffect)(()=>{if(ae||!P||s===!1||pe)return;let y=xn(P,En(n,"audio",s)),q=()=>{let D=A.current;return D?D.getAudioTracks()[0]??null:null},_=D=>{if(D!==q()&&(qe(D),D)){let Ae=()=>{q()===D&&qe(null)};D.addEventListener("ended",Ae)}},$=y.track;$&&$.readyState==="live"&&_($);let ee=y.on("track",D=>{D&&D.readyState!=="live"||_(D)}),ve=setInterval(()=>{let D=y.track;D&&D.readyState==="live"&&_(D)},Rn);return()=>{ee(),clearInterval(ve)}},[P,n,pe,s,ae,qe]),(0,xt.jsxs)("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":M?"true":"false","data-urun-video-framed":E?"true":"false",children:[(0,xt.jsx)("video",{ref:fe,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),M?null:v,C===void 0?null:(0,xt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":E||void 0,style:{position:"absolute",inset:0,...E?{opacity:0,pointerEvents:"none"}:null},children:C}),h]})});var Et=require("react/jsx-runtime"),es={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},An=(0,me.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...f}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=(0,me.useRef)(null),v=(0,me.useRef)(null),C=(0,me.useRef)(0),h=(0,me.useRef)(f);h.current=f;let p=(0,me.useMemo)(()=>(0,Un.createCameraWarp)(h.current),[]);return(0,me.useImperativeHandle)(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:p,get lastDrawTs(){return C.current}}),[p]),(0,me.useEffect)(()=>{if(!i)return;let k=0,R=0,d=null,b=w=>{typeof w.requestVideoFrameCallback=="function"&&(d=w,R=w.requestVideoFrameCallback(function P(){p.frameArrived(),R=w.requestVideoFrameCallback(P)}))},m=w=>{k=requestAnimationFrame(m);let P=v.current,x=g.current?.element??null;if(!P||!x||(x!==d&&(d&&R&&d.cancelVideoFrameCallback?.(R),b(x)),x.readyState<2))return;p.tick(w);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,M=Math.max(1,Math.round(P.clientWidth*A)),L=Math.max(1,Math.round(P.clientHeight*A));(P.width!==M||P.height!==L)&&(P.width=M,P.height=L);let E=P.getContext("2d");if(!E)return;let O=p.transform(),J=x.videoWidth||M,X=x.videoHeight||L,Z=Math.max(M/J,L/X)*(1+a)*O.scale;E.setTransform(Z,0,0,Z,M/2+O.translateX*M,L/2+O.translateY*L),E.drawImage(x,-J/2,-X/2),C.current=w};return k=requestAnimationFrame(m),()=>{cancelAnimationFrame(k),d&&R&&d.cancelVideoFrameCallback?.(R)}},[i,a,p]),(0,me.useEffect)(()=>{if(!i||!c||!l)return;let k=()=>!!l.pointerLockElement,R=P=>{k()&&p.keyDown(P.key)},d=P=>p.keyUp(P.key),b=P=>{k()&&p.pointerDelta(P.movementX,P.movementY)},m=()=>{k()||p.clearKeys()},w=()=>p.clearKeys();return l.addEventListener("keydown",R),l.addEventListener("keyup",d),l.addEventListener("mousemove",b),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",w),()=>{l.removeEventListener("keydown",R),l.removeEventListener("keyup",d),l.removeEventListener("mousemove",b),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",w)}},[i,c,l,p]),i?(0,Et.jsxs)(Ye,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,Et.jsx)("canvas",{ref:v,style:es,"data-urun-warp":""}),n]}):(0,Et.jsx)(Ye,{ref:g,...s,children:n})});var Mn=new Map;function _n(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Mn.set(e,{component:t,schema:r})}function Nn(e,t){let r=Mn.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var Ze=require("react/jsx-runtime");function On({name:e,props:t,fallback:r}){let o=Nn(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Ze.jsx)(Ze.Fragment,{children:r}):(0,Ze.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Ze.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Ze.jsx)(n,{...o.validatedProps})}var ut=require("zod"),Qe=require("react/jsx-runtime"),In=ut.z.object({step:ut.z.number().min(0),total:ut.z.number().min(1),label:ut.z.string().optional(),variant:ut.z.enum(["default","success","error"]).default("default")});function Rr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Ln(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Rr(e);return(0,Qe.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Qe.jsx)("div",{className:"urun-progress-label",children:o}),(0,Qe.jsx)("div",{className:"urun-progress-bar",children:(0,Qe.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Qe.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Bt=require("zod"),wt=require("react/jsx-runtime"),Dn=Bt.z.object({state:Bt.z.enum(["thinking","generating","idle","error"]),message:Bt.z.string().optional()}),ts={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Pr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??ts[t]??t;return{state:t,message:n,isActive:o}}function Vn(e){let{state:t,message:r,isActive:o}=Pr(e);return(0,wt.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,wt.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,wt.jsx)("span",{className:"urun-status-message",children:r})]})}var Ut=require("react"),jt=require("zod"),At=require("react/jsx-runtime"),Fn=jt.z.object({text:jt.z.string(),streaming:jt.z.boolean().default(!1)});function xr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function qn(e){let{text:t,streaming:r}=xr(e),o=(0,Ut.useRef)(null),n=(0,Ut.useRef)(0);return(0,Ut.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,At.jsxs)("div",{className:"urun-text-stream",children:[(0,At.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,At.jsx)("span",{className:"urun-text-cursor"})]})}var Mt=require("zod"),_t=require("react/jsx-runtime"),Hn=Mt.z.object({src:Mt.z.string().url(),alt:Mt.z.string().optional(),caption:Mt.z.string().optional()});function Er(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Wn(e){let{src:t,alt:r,caption:o}=Er(e);return(0,_t.jsxs)("figure",{className:"urun-image-frame",children:[(0,_t.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,_t.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Ie=require("zod"),ct=require("react/jsx-runtime"),Bn=Ie.z.object({metrics:Ie.z.array(Ie.z.object({label:Ie.z.string(),value:Ie.z.union([Ie.z.string(),Ie.z.number()]),unit:Ie.z.string().optional()}))});function wr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function jn(e){let{metrics:t}=wr(e);return(0,ct.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ct.jsxs)("div",{className:"urun-metric-card",children:[(0,ct.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ct.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var Y=require("react"),zn=require("react/jsx-runtime");function We(e){return e&&typeof e=="object"?e:null}function Ur(e){if(typeof e=="string")return e;let t=We(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function rs(e){if(typeof e=="string")return"delta";let t=We(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function ns(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function os(e){let t=We(e),r=t?.body;return ns(r,We(We(r)?.error)?.message,We(r)?.error,We(r)?.message,We(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var lt=class extends Error{name="TextStreamError"},ss=4,Ar=3,Mr=240,Kn=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function $n(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function is(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function _r(e){let{session:t,stream:r}=e,o=(0,Y.useRef)(e);(0,Y.useEffect)(()=>{o.current=e});let n=(0,Y.useRef)(null),s=(0,Y.useRef)(()=>{}),i=(0,Y.useRef)(null),a=(0,Y.useRef)(""),c=(0,Y.useRef)(""),u=(0,Y.useRef)(null),f=(0,Y.useRef)(!1),l=(0,Y.useRef)(!1),g=(0,Y.useRef)(!1),v=(0,Y.useRef)(null),C=(0,Y.useRef)($n()),h=(0,Y.useCallback)(d=>{if(n.current=d,!d){i.current=null;return}let b=i.current;if(b&&b.parentNode===d)return;let m=d.ownerDocument.createTextNode(c.current);d.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),p=(0,Y.useCallback)(()=>{u.current=null;let d=i.current,b=a.current;if(b.length>0){let A=o.current,M=A.smoothCharsPerFrame??Ar,L=A.smoothThreshold??Mr,E=A.smooth&&b.length<=L?b.slice(0,M):b;a.current=b.slice(E.length),c.current+=E,d?.appendData(E)}let m=C.current,w=c.current.length,P=v.current===null?0:Math.max(0,Kn()-v.current),x=Math.round(w/ss);if(m.chars=w,m.tokens=x,m.elapsedMs=P,m.tokensPerSecond=P>0?x*1e3/P:0,a.current.length>0){k(),o.current.onMeter?.(m);return}if(!f.current&&!g.current){g.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(m)},[]),k=(0,Y.useCallback)(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>p()))},[p]);s.current=k,(0,Y.useEffect)(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,v.current=null,f.current=!0,is(C.current),i.current&&(i.current.data="");let d=!1,b=null;return(async()=>{try{for(b=t.stream(r).messages()[Symbol.asyncIterator]();;){let w=await b.next();if(d)return;if(w.done)break;let P=w.value,x=rs(P);if(x==="error")throw new lt(os(P));if(x==="done")break;if(x==="ignore")continue;let A=Ur(P);A&&(v.current===null&&(v.current=Kn()),a.current+=A,k())}if(d)return;b.return?.(void 0),f.current=!1,k()}catch(m){if(d)return;b?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(m instanceof Error?m:new lt(String(m))),k()}})(),()=>{d=!0,f.current=!1,b?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,k]);let R=(0,Y.useCallback)(()=>c.current,[]);return{ref:h,meterRef:C,getText:R}}function Gn(e,t=250){let[r,o]=(0,Y.useState)($n);return(0,Y.useEffect)(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function Xn(e){let{className:t,style:r,...o}=e,{ref:n}=_r(o);return(0,zn.jsx)("span",{ref:n,className:t,style:r})}var Jn=require("react");var Zn=require("react/jsx-runtime"),Yn=(0,Jn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Zn.jsx)(Ye,{ref:r,stream:o,...n})});var j=require("react"),Qn=require("@urun-sh/core");var to=require("react/jsx-runtime"),as=1e3;function us(e){return e!==null&&Or.has(e)}var Or=new WeakSet,cs=1e3;function Nr(...e){console.debug("[audio]",...e)}var Nt=(0,j.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f,directOut:l}=t,g=Ue(),v=o??g,C=(0,j.useRef)(null),h=(0,j.useRef)(null),p=(0,j.useRef)(null),k=(0,j.useRef)(null),R=(0,j.useRef)(null),d=(0,j.useRef)(0),b=(0,j.useRef)(!1),m=(0,j.useRef)(c);m.current=c;let w=(0,j.useRef)(u);w.current=u;let P=(0,j.useRef)(l);P.current=l;let x=(0,j.useCallback)(T=>{p.current!==T&&(p.current=T,w.current?.(T))},[]),A=(0,j.useCallback)(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let T=C.current;return T&&T.srcObject!==h.current&&h.current.getAudioTracks().length>0&&(T.srcObject=h.current),h.current},[]),M=(0,j.useCallback)(()=>{d.current=0,R.current!==null&&cancelAnimationFrame(R.current),R.current=null,k.current!==null&&clearTimeout(k.current),k.current=null},[]),L=(0,j.useCallback)(T=>{R.current=null,k.current=null,A(),C.current&&(C.current.muted=b.current),J.current(`${T}:retry`)},[A]),E=(0,j.useCallback)(T=>{if(!C.current||R.current!==null||k.current!==null)return;let S=h.current;if(!(!!S&&S.getAudioTracks().some(F=>F.readyState==="live"))){M();return}let V=d.current;if(d.current=V+1,V===0&&typeof requestAnimationFrame=="function"){R.current=requestAnimationFrame(()=>L(T));return}k.current=setTimeout(()=>L(T),cs)},[M,L]),O=(0,j.useCallback)(T=>{let W=C.current;if(!W)return;let S=W.play();!S||typeof S.then!="function"||S.then(()=>{W.muted=b.current,W.muted||x(!0),M()}).catch(N=>{let V=N instanceof Error?N.name:String(N);if(V==="AbortError"){Nr(`play() aborted (${T}); retrying on the ladder`),E(`${T}:abort`);return}if(V==="NotAllowedError"){Nr(`play() blocked pending a user gesture (${T})`),x(!1),E(`${T}:blocked`);return}Nr(`play() failed (${T})`,N)})},[x]),J=(0,j.useRef)(()=>{});J.current=O;let X=(0,j.useCallback)(T=>{let W=A();if(!W)return;for(let N of W.getAudioTracks())N!==T&&W.removeTrack(N);T&&!W.getAudioTracks().includes(T)&&W.addTrack(T),A();let S=P.current??us(T);b.current=!!T&&S,C.current&&(C.current.muted=b.current),T&&O("track-attach"),m.current?.(T)},[A,O]),z=(0,j.useCallback)(()=>{let T=C.current;T&&(A(),T.muted=b.current,O("gesture"),Je(),x(!0))},[A,O,x]);(0,j.useImperativeHandle)(r,()=>({unlock:z,get unlocked(){return p.current===!0},get element(){return C.current}}),[z]);let Z=(0,j.useCallback)(()=>{E("pause-event")},[E]),ne=(0,j.useCallback)(T=>{let W=C.current;W&&W!==T&&W.removeEventListener("pause",Z),C.current=T,T&&(T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),A(),T.addEventListener("pause",Z)),f?.(T)},[A,f,Z]),Q=s!==void 0;return(0,j.useEffect)(()=>{if(Q){X(s??null);return}if(!v)return;let T=v.stream(n);if(T.directOut){let U=T.track;U&&Or.add(U)}let W=()=>{let U=h.current;return U?U.getAudioTracks()[0]??null:null},S=U=>{if(U!==W()&&(T.directOut&&U&&Or.add(U),X(U),U)){let oe=()=>{W()===U&&X(null)};U.addEventListener("ended",oe)}},N=T.track;N&&N.readyState==="live"&&S(N);let V=T.on("track",U=>{U&&U.readyState!=="live"||S(U)}),F=setInterval(()=>{let U=T.track;U&&U.readyState==="live"&&S(U)},as);return()=>{V(),clearInterval(F)}},[v,n,Q,s,X]),(0,j.useEffect)(()=>(0,Qn.observePageLifecycle)(()=>{Je(),p.current===!0&&O("foreground")}),[O]),(0,j.useEffect)(()=>()=>{k.current&&clearTimeout(k.current),R.current!==null&&cancelAnimationFrame(R.current),R.current=null},[]),(0,to.jsx)("audio",{ref:ne,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),eo=Nt;var G=require("react"),Be=require("@urun-sh/core");var no=require("react/jsx-runtime"),Ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Kt(...e){console.debug("[voice]",...e)}function ls(e){return e instanceof Be.SessionFailedError&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var Ot=(0,G.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=Ir,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:C,onUnlockChange:h,capture:p,directOut:k}=t,R=Ue(),d=o??R,b=(0,G.useRef)(null),m=(0,G.useRef)(null),w=(0,G.useRef)(null),P=(0,G.useRef)([]),x=(0,G.useRef)(!1),A=(0,G.useRef)(l);A.current=l;let M=(0,G.useRef)(g);M.current=g;let L=(0,G.useRef)(v);L.current=v;let E=(0,G.useCallback)(S=>{x.current!==S&&(x.current=S,A.current?.(S))},[]),O=(0,G.useCallback)(()=>{for(let S of P.current)S();P.current=[],w.current?.release(),w.current=null,m.current&&(m.current=null,L.current?.(null))},[]),J=(0,G.useCallback)(async()=>{let S=w.current;if(S){let U=await S.update(a);return m.current=S.stream,L.current?.(S.stream),U}let V=await(p??(0,Be.sharedCaptureController)()).claim("audio",a);w.current=V,P.current=[V.onTrack((U,oe)=>{m.current=oe,L.current?.(oe),x.current&&d?.stream(n).attach(U).catch(se=>Kt("mic re-attach after one-capture re-acquire failed",se))}),V.onLost(U=>{w.current=null,P.current=[],m.current=null,L.current?.(null),E(!1),M.current?.(U)})],m.current=V.stream,L.current?.(V.stream);let F=V.track;if(!F)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return F},[p,a,d,n,E]),X=(0,G.useCallback)(async()=>{O(),E(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,O,E]),z=(0,G.useCallback)(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");b.current?.unlock();let S;try{S=await J()}catch(F){O();let U=(0,Be.sessionFailureFromMediaError)(F,d.status);throw M.current?.(U),U}let N;for(let F=1;F<=u;F++)try{await d.whenLive(c!==void 0?{timeout:c}:void 0),await d.stream(n).attach(S),E(!0);return}catch(U){if(N=U,Kt(`start attempt ${F}/${u} failed`,U),ls(U))break;d.connect?.(),F<u&&await new Promise(oe=>setTimeout(oe,f))}O(),E(!1);let V=N instanceof Error?N:new Error(String(N??"voice start failed"));throw M.current?.(V),V},[d,n,c,u,f,J,O,E]);(0,G.useImperativeHandle)(r,()=>({start:z,stop:X,unlock:()=>b.current?.unlock(),get active(){return x.current},get micStream(){return m.current},get audio(){return b.current}}),[z,X]);let Z=(0,G.useRef)(z);Z.current=z;let ne=(0,G.useRef)(null),Q=(0,G.useCallback)((S,N)=>{S.promise.then(()=>{N&&(O(),E(!1)),S.session.stream(S.streamName).detach().catch(()=>{})})},[O,E]);(0,G.useEffect)(()=>{if(!i||!d)return;let S=ne.current;S&&(S.session!==d||S.streamName!==n)&&(S.disposeTimer&&clearTimeout(S.disposeTimer),Q(S,!1),S=null),S?S.disposeTimer&&(clearTimeout(S.disposeTimer),S.disposeTimer=null):(S={session:d,streamName:n,promise:Z.current().catch(()=>{}),refCount:0,disposeTimer:null},ne.current=S),S.refCount+=1;let N=S;return()=>{N.refCount-=1,!(N.refCount>0)&&(N.disposeTimer=setTimeout(()=>{ne.current===N&&(ne.current=null),Q(N,!0)},0))}},[i,d,n,Q]);let T=(0,G.useRef)(!1),W=(0,G.useCallback)(async()=>{if(!d||!x.current||T.current)return;let S=m.current?.getAudioTracks()[0]??null;if(S&&S.readyState==="live"){try{await d.stream(n).attach(S)}catch(N){Kt("foreground mic re-assert failed (will retry on next pass)",N)}return}T.current=!0;try{let N=await J();await d.stream(n).attach(N)}catch(N){let V=N instanceof Error?N:new Error(String(N));Kt("foreground mic re-acquire failed",V),M.current?.(V)}finally{T.current=!1}},[d,n,J]);return(0,G.useEffect)(()=>{let S=()=>{W()};return d&&typeof d.onRecovery=="function"?d.onRecovery(S):(0,Be.observePageLifecycle)(S)},[d,W]),(0,G.useEffect)(()=>O,[O]),s?(0,no.jsx)(Nt,{ref:b,session:d,stream:n,onTrack:C,onUnlockChange:h,directOut:k}):null}),ro=Ot;var De=require("react");var $t=require("react");var Lr={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,$t.useState)(Lr);return(0,$t.useEffect)(()=>{if(!e){i(Lr);return}let a=Rt();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,f;try{u=a.createMediaStreamSource(c),f=a.createAnalyser(),f.fftSize=r,u.connect(f)}catch{return}let l=new Uint8Array(f.fftSize),v=setInterval(()=>{f.getByteTimeDomainData(l);let C=0;for(let p=0;p<l.length;p++){let k=(l[p]-128)/128;C+=k*k}let h=Math.sqrt(C/l.length);i(p=>{let k=h>n;return Math.abs(p.level-h)<.005&&p.speaking===k?p:{level:h,speaking:k}})},o);return()=>{clearInterval(v),u.disconnect(),i(Lr)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),ds={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ps={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},oo=(0,De.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:f,onMicStream:l,capture:g}=t,v=Ue(),C=o??v,h=(0,De.useRef)(null),[p,k]=(0,De.useState)(null),R=(0,De.useRef)(l);R.current=l;let{level:d,speaking:b}=Gt(a?p:null);return(0,De.useImperativeHandle)(r,()=>({start:()=>{let m=h.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>h.current?.stop()??Promise.resolve(),get active(){return h.current?.active??!1},get micStream(){return h.current?.micStream??null}}),[]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(Ot,{ref:h,session:C,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:m=>{k(m),R.current?.(m)}}),a?(0,Le.jsx)("span",{className:c,style:ds,"data-urun-mic":"","data-urun-mic-active":p?"true":"false","data-urun-mic-speaking":b?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(d*100)/100,children:(0,Le.jsx)("span",{style:ps,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(d*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var dt=require("@urun-sh/core"),I=require("react");var be=require("react/jsx-runtime"),Vr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Dr(...e){console.debug("[camera]",...e)}function ms(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function fs(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var Fr=(0,I.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:f="auto",connectTimeoutMs:l,visible:g=!1,className:v,videoClassName:C,onActiveChange:h,onError:p,onStream:k,onTrack:R,children:d,capture:b,flipControl:m="auto",flipControlClassName:w,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let x=i?"user":a?"environment":c??"environment",A=Ue(),M=o??A,L=(0,I.useRef)(null),E=(0,I.useRef)(null),O=(0,I.useRef)(null),J=(0,I.useRef)([]),X=(0,I.useRef)(null),z=(0,I.useRef)(!1),Z=(0,I.useRef)(!1),ne=(0,I.useRef)(x),[Q,T]=(0,I.useState)(x),[W,S]=(0,I.useState)(!1),[N,V]=(0,I.useState)(null),[F,U]=(0,I.useState)(!1),[oe]=(0,I.useState)(ms),se=(0,I.useRef)(h);se.current=h;let de=(0,I.useRef)(p);de.current=p;let we=(0,I.useRef)(k);we.current=k;let he=(0,I.useRef)(R);he.current=R;let qe=(0,I.useRef)(P);qe.current=P;let fe=(0,I.useCallback)(B=>{z.current!==B&&(z.current=B,S(B),se.current?.(B))},[]);(0,I.useEffect)(()=>{if(!W){V(null);return}let B=!1,K=()=>{fs().then(ke=>{B||(V(ke),ke&&qe.current?.(ke))})};K();let ye=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ye?.addEventListener=="function"?(ye.addEventListener("devicechange",K),()=>{B=!0,ye.removeEventListener?.("devicechange",K)}):()=>{B=!0}},[W]);let pe=(0,I.useCallback)(B=>{let K=L.current;K&&(K.muted=!0,K.defaultMuted=!0,K.setAttribute("muted",""),K.setAttribute("playsinline",""),K.setAttribute("webkit-playsinline",""),K.srcObject=B,B&&K.play()?.catch?.(ye=>Dr("preview play() failed",ye)))},[]),ae=(0,I.useCallback)(()=>{Z.current=!1,X.current?.(),X.current=null;for(let B of J.current)B();J.current=[],O.current?.release(),O.current=null,E.current&&(E.current=null,we.current?.(null),he.current?.(null)),pe(null)},[pe]),y=(0,I.useCallback)((B,K)=>{X.current?.(),E.current=K,pe(K),we.current?.(K);let ye=()=>{E.current===K&&(Dr("camera track ended (device removed or permission revoked)"),ae(),fe(!1))};B.addEventListener("ended",ye),X.current=()=>B.removeEventListener("ended",ye)},[pe,ae,fe]),q=(0,I.useCallback)(async B=>{let K=n!==!1;if(K&&!M)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ye={...Vr,...s,facingMode:B},ke;try{let Re=O.current;if(Re)ke=await Re.update(ye);else{let yt=await(b??(0,dt.sharedCaptureController)()).claim("video",ye);if(O.current=yt,J.current=[yt.onTrack((kt,_o)=>{y(kt,_o),z.current&&(!K||!M||M.stream(n).attachVideo(kt).then(()=>he.current?.(kt)).catch(No=>Dr("camera re-publish after one-capture re-acquire failed",No)))}),yt.onLost(kt=>{O.current=null,J.current=[],ae(),fe(!1),de.current?.(kt)})],!yt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ke=yt.track}}catch(Re){let nt=(0,dt.sessionFailureFromMediaError)(Re,M?.status);throw de.current?.(nt),nt}ne.current=B,T(B),y(ke,O.current?.stream??new MediaStream([ke]));try{K&&M&&(M.connect?.(),await M.whenLive(l!==void 0?{timeout:l}:void 0),await M.stream(n).attachVideo(ke)),Z.current=K?n:!1}catch(Re){ae(),fe(!1);let nt=Re instanceof Error?Re:new Error(String(Re));throw de.current?.(nt),nt}he.current?.(ke),fe(!0)},[M,n,s,l,b,y,ae,fe]),_=(0,I.useCallback)(B=>q(B?.facingMode??ne.current),[q]),$=(0,I.useCallback)(async B=>{let K=Z.current===n;z.current&&ne.current===B&&K||await q(B)},[q,n]),ee=(0,I.useCallback)(()=>q(ne.current==="environment"?"user":"environment"),[q]),ve=(0,I.useCallback)(async()=>{ae(),fe(!1),n!==!1&&await M?.stream(n).detachVideo().catch(()=>{})},[M,n,ae,fe]),D=(0,I.useCallback)(async B=>{let K=L.current;if(!K)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,dt.captureStillFromVideo)(K,B)},[]);(0,I.useImperativeHandle)(r,()=>({start:_,stop:ve,flip:ee,setFacingMode:$,capturePhoto:D,get active(){return z.current},get facingMode(){return ne.current},get stream(){return E.current},get element(){return L.current}}),[_,ve,ee,$,D]);let Ae=(0,I.useRef)($);if(Ae.current=$,(0,I.useEffect)(()=>{u&&(n!==!1&&!M||Ae.current(x).catch(()=>{}))},[u,M,x,n]),(0,I.useEffect)(()=>ae,[ae]),!g)return null;let rt=f==="auto"?Q==="user":f,Me=W&&(m===!0||m==="auto"&&oe&&(N?.length??0)>1),_e=()=>{F||(U(!0),ee().catch(()=>{}).finally(()=>U(!1)))};return(0,be.jsxs)("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":Q,children:[(0,be.jsx)("video",{ref:L,className:C,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...rt?{transform:"scaleX(-1)"}:{}}}),Me?(0,be.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:_e,disabled:F,className:w,style:w?{opacity:F?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:F?.6:1},children:(0,be.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,be.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,be.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,be.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,be.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,be.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,d]})}),so=(0,I.forwardRef)(function({preview:t=!0,...r},o){return(0,be.jsx)(Fr,{ref:o,...r,visible:t,autoStart:!1})});var pt=require("@urun-sh/core"),ie=require("react");function io(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,ie.useState)(null),[a,c]=(0,ie.useState)(null),[u,f]=(0,ie.useState)(!1),[l,g]=(0,ie.useState)(null),[v]=(0,ie.useState)(pt.cameraCaptureAvailable),C=(0,ie.useRef)(n);C.current=n;let h=(0,ie.useRef)(null),p=(0,ie.useRef)(0),k=(0,ie.useCallback)(w=>{h.current&&URL.revokeObjectURL(h.current),h.current=w?URL.createObjectURL(new Blob([w.bytes],{type:w.type})):null,c(h.current),i(w),C.current?.(w)},[]);(0,ie.useEffect)(()=>()=>{p.current++,h.current&&URL.revokeObjectURL(h.current),h.current=null},[]);let R=(0,ie.useCallback)(async w=>{let P=++p.current;f(!0),g(null);try{let x=await w();if(p.current!==P)return;k(x)}catch(x){if(p.current!==P)return;g((0,pt.referenceImageErrorMessage)(x))}finally{p.current===P&&f(!1)}},[k]),d=(0,ie.useCallback)(w=>R(()=>(0,pt.normalizeReferenceImage)(w,{maxSize:t,type:r,quality:o,source:"file"})),[R,t,r,o]),b=(0,ie.useCallback)(w=>R(()=>w.capturePhoto({maxSize:t,type:r,quality:o})),[R,t,r,o]),m=(0,ie.useCallback)(()=>{p.current++,g(null),f(!1),k(null)},[k]);return{reference:s,previewUrl:a,pick:d,capture:b,clear:m,busy:u,error:l,cameraAvailable:v}}var Xt=require("react");function ao(e,t){let[r,o]=(0,Xt.useState)(null);return(0,Xt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var lo=require("react");var Jt=require("react");var uo=require("zustand/vanilla"),co=require("zustand"),gs=()=>{};function zt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=(0,uo.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):gs,c=(u=>(0,co.useStore)(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function mt(e,t){let r=(0,Jt.useMemo)(()=>zt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Jt.useEffect)(()=>r.bind(),[r]),r}function po(e,t,r){let n=mt(e,t)(r??(a=>a)),s=(0,lo.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var Yt=require("react");function mo(e){let[t,r]=(0,Yt.useState)(null);return(0,Yt.useEffect)(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}var Qt=require("react");var je=200;function Ve(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function ft(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Zt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function er(e,t,r={}){let o=r.cap??200,[n,s]=(0,Qt.useState)([]);return(0,Qt.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>Ve(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var xe=require("react/jsx-runtime");function fo({session:e,name:t,cap:r,className:o}){let n=er(e,t,{cap:r});return(0,xe.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,xe.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,xe.jsx)("code",{children:t}),(0,xe.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,xe.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,xe.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,xe.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,xe.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,xe.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ft(s.payload)]},`${s.at}-${i}`))})]})}var It=require("react");var Se=require("react/jsx-runtime");function Lt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,It.useState)(""),[i,a]=(0,It.useState)(null),c=(0,It.useCallback)(()=>{let u=Zt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return(0,Se.jsxs)("div",{className:"urun-doc-patch",children:[(0,Se.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),(0,Se.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,Se.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?(0,Se.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function go({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=mt(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return(0,Se.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,Se.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,Se.jsx)("code",{children:t}),(0,Se.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,Se.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,Se.jsx)(Lt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}var tr=require("react");var Fe=require("react/jsx-runtime");function So(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ho({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,tr.useState)([]);return(0,tr.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ve(c,{at:Date.now(),direction:"in",text:So(ft(a))},r))}):void 0),[e,t,r]),(0,Fe.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,Fe.jsx)(Lt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>Ve(c,{at:Date.now(),direction:"out",text:So(a)},r))}}),(0,Fe.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,Fe.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,Fe.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,Fe.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,Fe.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var rr=require("react");var et=require("react/jsx-runtime");function vo({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,rr.useState)([]),a=t.join(","),c=r.join(",");return(0,rr.useEffect)(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>Ve(v,{at:Date.now(),kind:l,text:g},o)),f=[];f.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);f.push(g.on("track",v=>u("track",`${l}: ${v?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);f.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>f.forEach(l=>l())},[e,a,c,o]),(0,et.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,et.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,f)=>(0,et.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,et.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,et.jsx)("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${f}`))})}var cr=require("@urun-sh/core");var nr=require("react");function Te(e){let[t,r]=(0,nr.useState)(e?.phase??null);return(0,nr.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var ko=require("@urun-sh/core");var gt=require("react"),yo=require("@urun-sh/core");function or(e){let t=Te(e),r=(0,yo.isWakingPhase)(t?.name),o=(0,gt.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,gt.useState)(s);return(0,gt.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var Ke=require("react/jsx-runtime");function sr({session:e,render:t,className:r}){let o=or(e);return!o.waking||!o.phase?null:(0,Ke.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,Ke.jsxs)(Ke.Fragment,{children:[(0,Ke.jsx)("span",{className:"urun-session-waking-label",children:(0,ko.describeSessionPhase)(o.phase)})," ",(0,Ke.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var ar=require("react");var $e=require("react"),Ss={event:null,elapsedMs:0};function ir(e,t){let[r,o]=(0,$e.useState)(null),n=(0,$e.useRef)(0);(0,$e.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,$e.useState)(0);return(0,$e.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:Ss}var St=require("react/jsx-runtime"),hs={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function vs(e){let[t,r]=(0,ar.useState)(!1);return(0,ar.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function ur({session:e,stream:t,videoElement:r,render:o,className:n}){let s=ir(e,t),i=vs(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return(0,St.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):(0,St.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,St.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??hs[c]})," ",(0,St.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var Ce=require("react/jsx-runtime"),ys={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function bo({session:e,className:t}){let r=Te(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,Ce.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,Ce.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,Ce.jsx)("span",{className:"urun-session-status-label",children:ys[o]}),n?(0,Ce.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function To({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=Te(e);if(s?.name==="live")return(0,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,Ce.jsx)(ur,{session:e})]});let i=r?r(s):(0,Ce.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&(0,cr.isWakingPhase)(s.name)?(0,Ce.jsx)(sr,{session:e}):s&&s.name!=="idle"?(0,cr.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return(0,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,Ce.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var lr=require("react");var Ro=require("react/jsx-runtime");function qr(e){return Te(e)?.endsAt??null}function ks(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Co({session:e,urgentMs:t=6e4,className:r}){let n=qr(e)?.getTime()??null,[s,i]=(0,lr.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,lr.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=ks(s);return(0,Ro.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var Po=require("@urun-sh/core");var ht=require("react/jsx-runtime"),bs=new Set(["paused","error"]);function Hr({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=Te(e);if(!s||!bs.has(s.name))return null;let i=o?o(s):(0,ht.jsx)("span",{className:"urun-session-paused-copy",children:(0,Po.describeSessionPhase)(s)});return(0,ht.jsxs)("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var xo=Hr;var Ge=require("react"),tt=require("react/jsx-runtime");function Wr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Br(e){let t=(0,Ge.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,Ge.useState)(()=>t?Wr(t.get("idle")):null);return(0,Ge.useEffect)(()=>{if(!t){o(null);return}return o(Wr(t.get("idle"))),t.on("change",()=>o(Wr(t.get("idle"))))},[t]),r}function Ts(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Eo({session:e,onStillHere:t,className:r}){let o=Br(e),n=o?.deadlineEpochS??null,[s,i]=(0,Ge.useState)(null);if((0,Ge.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,tt.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,tt.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,tt.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,tt.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Ts(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,tt.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var Ee=require("react");function Cs(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function dr(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=(0,Ee.useState)(null),[s,i]=(0,Ee.useState)(e!==null),[a,c]=(0,Ee.useState)(null),u=(0,Ee.useRef)(e),f=(0,Ee.useCallback)(async g=>{i(!0);try{let v=await g.getBalance();if(u.current!==g)return;n(v),c(null)}catch(v){if(u.current!==g)return;c(v instanceof Error?v:new Error(String(v)))}finally{u.current===g&&i(!1)}},[]);(0,Ee.useEffect)(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(f(e),r!==void 0&&r>0){let g=setInterval(()=>{f(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,f]);let l=(0,Ee.useCallback)(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:Cs(o),loading:s,error:a,refresh:l}}var pr=require("react/jsx-runtime");function wo({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=dr(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return(0,pr.jsx)("div",{className:i,children:t});let a=r?r(n):(0,pr.jsx)("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return(0,pr.jsx)("div",{className:i,children:a})}var Xe=require("@urun-sh/core");var vt=require("react"),Uo=require("@urun-sh/core");function Ao(e){let t=(0,vt.useContext)(He),[r,o]=(0,vt.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,f=t?.getAccessToken,l=t?.authProvider;return(0,vt.useEffect)(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{(0,Uo.prewake)({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(h=>{g||o(h)}).catch(()=>{})};v();let C=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(C)}},[n,s,i,a,c,u,f,l]),r}var mr=require("react");function Mo(e){let[t,r]=(0,mr.useState)(null);return(0,mr.useEffect)(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}var fr=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,CreditsClient,CreditsError,CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_SMOOTH_CHARS_PER_FRAME,DEFAULT_SMOOTH_THRESHOLD,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,ReprojectedVideo,Session,StatusBadge,StatusBadgeSchema,Text,TextStream,TextStreamError,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunCreditsGate,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionPaused,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createCreditsClient,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,textDelta,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useCredits,useDocStore,useGenerationTick,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useReferenceImage,useRequest,useSession,useSessionDirectory,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionStats,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useText,useTextMeter,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
import{a as bt,b as wn,c as Tt}from"./chunk-WF2OBDSX.mjs";import{useCallback as fr,useEffect as qn,useMemo as kr,useRef as gr,useState as Pt}from"react";import{computeBackoffDelay as Hn}from"@urun-sh/core/internal";import{Component as Un}from"react";import{jsx as cr,jsxs as An}from"react/jsx-runtime";var Ke=class extends Un{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||An("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[cr("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),cr("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Mn}from"react";var Ce=Mn(null);function be(e){return e&&e.trim()?e.trim():void 0}function fe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return be(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return be(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return be(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return be(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return be(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return be(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return be(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return be(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return be(typeof process<"u"?process.env?.[e]:void 0)}}function rt(){let e=fe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||fe("VERCEL_ENV")==="production"?"workos":fe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function _n(){return rt()==="workos"}import{useEffect as Nn,useRef as In}from"react";var On="urun.operator_token",dr=null,lr="op",Ln="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function pr(){return typeof window<"u"}function mr(){return dr}function Dn(){if(!pr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(lr);if(!r)return null;dr=r,t.delete(lr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Vn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Rt(e){let t=In(e);t.current=e,Nn(()=>{if(!pr())return;Dn();let r=o=>{if(!Vn(o))return;let n=mr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as Fn}from"react";function Ct(e=!0){Fn(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as Ve,jsxs as Xn}from"react/jsx-runtime";var Wn="/api/urun-token",Bn=1e4;function jn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}var Sr=3,Kn=new Set([502,503,504]);function hr(e){return new Promise(t=>setTimeout(t,Hn(e)))}async function vr(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=Sr-1)throw a;await hr(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!Kn.has(o.status)||r>=Sr-1)throw a;await hr(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function yr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function Et(e){let t=e===void 0?void 0:JSON.stringify(e);return kr(()=>e,[t])}function $n(e,t){return typeof e=="function"?e(t):e!==void 0?e:Xn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[Ve("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Ve("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Gn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:m,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:h,sessionStats:w,confirmOnLeave:v=!1,fallback:d,errorFallback:b,children:f}){let S=n===void 0&&t===void 0;if(!S&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!S&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let R=r??o;if(S&&(typeof R!="string"||R.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Ct(v);let[p,T]=Pt(),[P,U]=Pt(null),A=gr(void 0),E=gr(null),[N,x]=Pt(null);Rt(M=>x({jwt:M}));let V=Tt(),$=fe("NEXT_PUBLIC_SESSION_TOKEN")??fe("NEXT_PUBLIC_URUN_JWT"),K=rt(),G=N!==null,y=K==="workos"&&!n&&!G&&!S,F=n??(K==="jwt"?$:void 0)??p?.token,q=G?N.jwt:F,z=s??fe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),C=y&&!q&&!V?.getAccessToken,O=t??p?.orgId,_=e??p?.gatewayUrl,W=S&&p===void 0,L=S&&p!==void 0&&!_?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,X=C?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,re=P??L??X,Z=yr("NEXT_PUBLIC_URUN_TOKEN_URL",fe("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Wn,Q=yr("NEXT_PUBLIC_URUN_EVENTS_URL",fe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,me=fr(async M=>{if(!M?.forceRefresh){let J=A.current;if(!J)return J;let ie=jn(J);if(ie===null||ie-Date.now()>Bn)return J}return(await(E.current??(E.current=(async()=>{try{let J=await vr(Z);return A.current=J.token,T(J),J}finally{E.current=null}})()))).token},[Z]),se=fr(async()=>q,[q]),Re=typeof q=="string"&&q.trim().length>0,ne=y?V?.getAccessToken:S&&!G?me:Re?se:void 0,ee=Et(g),Y=Et(h),k=Et(w),D=kr(()=>({appId:R,baseUrl:_??"",orgId:O??"",jwt:q,getAccessToken:y?V?.getAccessToken:S&&!G?me:void 0,authProvider:z,eventsUrl:Q,sessionKey:a,releaseOnLeave:u,allowWebTransport:m,allowWebRtcFallback:l,audioPlayout:ee,videoPlayout:Y,sessionStats:k,priority:G?"preempt":void 0}),[R,V,_,z,q,Q,O,a,u,m,l,ee,Y,k,y,G,S,me]);return qn(()=>{if(!S)return;let M=new AbortController;return U(null),(async()=>{try{let j=await vr(Z,M.signal);A.current=j.token,T(j)}catch(j){if(M.signal.aborted)return;U(j instanceof Error?j:new Error(String(j)))}})(),()=>M.abort()},[S,Z]),Ve(Ke,{fallback:d,children:re?$n(b,re):W?Ve("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Ve(Ce.Provider,{value:D,children:ne?Ve(bt,{getAccessToken:ne,children:f}):f})})}import{useContext as zn,useEffect as Jn,useMemo as br,useReducer as Yn,useRef as xt}from"react";import{App as Zn}from"@urun-sh/core";function Tr(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Qn(e,t,r){let o=Tr(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function eo(e,t,r,o){let n=Tr(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var Me=new Map;var wt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Ut=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},At=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}watchDownlinkStall(t={}){return this._session.watchDownlinkStall?this._session.watchDownlinkStall(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new wt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Ut(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function to(){let e=zn(Ce);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Yn(i=>i+1,0),r=xt(new Map),o=xt(new Map),n=xt(null),s=br(()=>Zn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return Jn(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Me.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let m=Me.get(c);m===u&&(m.handle.removeNotifier(t),m.refCount=Math.max(0,m.refCount-1),a.set(c,m),m.refCount===0&&(m.disposeTimer=setTimeout(()=>{let l=Me.get(c);!l||l.refCount!==0||(Me.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),br(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let m=(l,g)=>{let h=Qn(c,l,g),w=r.current.get(h);if(w&&!w.disposed)return w;let v=eo(e,c,l,g),d=Me.get(v);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),Me.delete(v),o.current.get(v)===d&&o.current.delete(v),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new At(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Me.set(v,d)),o.current.get(v)!==d&&(o.current.set(v,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(h,d.handle),d.handle};return i.set(c,m),m}})},[e,s])}import{useContext as ro,useMemo as no}from"react";import{sessionDirectory as oo}from"@urun-sh/core";function so(){let e=ro(Ce);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return no(()=>oo(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}import{useCallback as Mt,useEffect as io,useMemo as ao,useRef as nt,useState as _t}from"react";function Fe(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function uo(e){return e instanceof Error?e:new Error(String(e))}function co(e,t){let r=ao(()=>Fe(e),[e]),[o,n]=_t(void 0),[s,i]=_t(null),[a,c]=_t(!1),u=nt(t);u.current=t;let m=nt(0),l=nt(null),g=nt(!0);io(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let h=Mt(async d=>{l.current?.abort();let b=new AbortController;l.current=b;let f=++m.current,S=()=>g.current&&m.current===f;S()&&(c(!0),i(null));try{let R=await r.request(d,{...u.current,signal:b.signal});return S()&&(n(R),c(!1),u.current?.onSuccess?.(R)),R}catch(R){let p=uo(R);throw S()&&(i(p),c(!1),u.current?.onError?.(p)),p}},[r]),w=Mt(d=>{h(d).catch(()=>{})},[h]),v=Mt(()=>{m.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:w,mutateAsync:h,data:o,error:s,isPending:a,reset:v}}import{useCallback as Rr,useEffect as lo,useMemo as po,useRef as ot,useState as Nt}from"react";function Cr(e){return e instanceof Error?e:new Error(String(e))}var mo=e=>typeof e=="string"?e:String(e);function fo(e,t){let r=po(()=>Fe(e),[e]),[o,n]=Nt(""),[s,i]=Nt(!1),[a,c]=Nt(null),u=ot(t);u.current=t;let m=ot(0),l=ot(null),g=ot(!0);lo(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let h=Rr(()=>{m.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),w=Rr(async v=>{l.current?.cancel();let d=++m.current,b=()=>g.current&&m.current===d,f=u.current,S=f?.parseChunk??mo,R=f?.buildPayload??(x=>({prompt:x}));b()&&(n(""),c(null),i(!0));let{parseChunk:p,buildPayload:T,onFinish:P,onError:U,...A}=f??{},E="",N;try{N=r.requestStream(R(v),A),l.current=N}catch(x){let V=Cr(x);b()&&(c(V),i(!1),f?.onError?.(V));return}try{for await(let x of N){if(m.current!==d)break;E+=S(x),b()&&n(E)}b()&&(i(!1),f?.onFinish?.(E))}catch(x){let V=Cr(x);b()&&(c(V),i(!1),f?.onError?.(V))}finally{l.current===N&&(l.current=null)}},[r]);return{completion:o,complete:w,stop:h,isStreaming:s,error:a}}import{useCallback as Pr,useEffect as go,useMemo as So,useRef as qe,useState as st}from"react";function Er(e){return e instanceof Error?e:new Error(String(e))}var ho=e=>typeof e=="string"?e:String(e),xr=0;function It(e){return xr+=1,`${e}-${xr}`}function vo(e,t){let r=So(()=>Fe(e),[e]),[o,n]=st(()=>(t?.initialMessages??[]).map(S=>({id:S.id??It("msg"),role:S.role,content:S.content}))),[s,i]=st(""),[a,c]=st(!1),[u,m]=st(null),l=qe(t);l.current=t;let g=qe(o);g.current=o;let h=qe(s);h.current=s;let w=qe(0),v=qe(null),d=qe(!0);go(()=>(d.current=!0,()=>{d.current=!1,v.current?.cancel(),v.current=null}),[]);let b=Pr(()=>{w.current++,v.current?.cancel(),v.current=null,d.current&&c(!1)},[]),f=Pr(async S=>{let R=S===void 0,p=(R?h.current:S)??"";if(!p.trim())return;v.current?.cancel();let P=++w.current,U=()=>d.current&&w.current===P,A=l.current,E=A?.parseChunk??ho,N={id:It("msg"),role:"user",content:p},x={id:It("msg"),role:"assistant",content:""},V=[...g.current,N].map(L=>({role:L.role,content:L.content})),$=[...g.current,N,x];g.current=$,n($),R&&i(""),m(null),c(!0);let K=A?.buildPayload??(L=>({messages:L})),{initialMessages:G,parseChunk:y,buildPayload:F,onFinish:q,onError:z,...C}=A??{},O=L=>{n(X=>X.map(re=>re.id===x.id?{...re,content:L}:re))},_="",W;try{W=r.requestStream(K(V),C),v.current=W}catch(L){let X=Er(L);U()&&(m(X),c(!1),A?.onError?.(X));return}try{for await(let L of W){if(w.current!==P)break;_+=E(L),U()&&O(_)}U()&&(c(!1),A?.onFinish?.({...x,content:_}))}catch(L){let X=Er(L);U()&&(m(X),c(!1),A?.onError?.(X))}finally{v.current===W&&(v.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:f,stop:b,isStreaming:a,error:u}}import{useCallback as Pe,useEffect as wr,useMemo as yo,useRef as Ur,useState as Ar}from"react";import{createInputPresencePublisher as ko,INPUT_PRESENCE_DEFAULT_HZ as bo,INPUT_PRESENCE_FIELD as To}from"@urun-sh/core";var Ot=[];function Ro(e,t={}){let{field:r=To,hz:o=bo}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=yo(()=>s?ko({awareness:{setLocalStateField:(p,T)=>s.setField(p,T)},field:r,hz:o}):null,[s,r,o]),a=Ur(null);a.current=i;let[c,u]=Ar(!1),[m,l]=Ar(Ot),g=Ur(!1);wr(()=>{if(i)return()=>i.dispose()},[i]);let h=Pe(()=>{let p=a.current;l(p?p.heldKeys():Ot)},[]),w=Pe(()=>{a.current?.clear(),l(Ot)},[]);wr(()=>{if(!n)return;let p=()=>!!n.pointerLockElement,T=()=>{if(p()){g.current=!1,u(!0);return}g.current||(u(!1),w())},P=x=>{p()&&(a.current?.keyDown(x.key),h())},U=x=>{a.current?.keyUp(x.key),h()},A=x=>{p()&&a.current?.movePointer(x.movementX,x.movementY)},E=x=>{p()&&a.current?.setButtons(x.buttons)},N=()=>{w()};return n.addEventListener("pointerlockchange",T),n.addEventListener("keydown",P),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",E),n.addEventListener("mouseup",E),n.defaultView?.addEventListener("blur",N),()=>{n.removeEventListener("pointerlockchange",T),n.removeEventListener("keydown",P),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",E),n.removeEventListener("mouseup",E),n.defaultView?.removeEventListener("blur",N)}},[n,w,h]);let v=Pe(p=>{p.requestPointerLock?.()},[]),d=Pe(()=>{g.current=!0,u(!0)},[]),b=Pe(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),w()},[n,w]),f=Pe(p=>{a.current?.keyDown(p),h()},[h]),S=Pe(p=>{a.current?.keyUp(p),h()},[h]),R=Pe((p,T)=>{a.current?.movePointer(p,T)},[]);return{engage:v,engageTouch:d,release:b,engaged:c,heldKeys:m,pressKey:f,releaseKey:S,movePointer:R}}import{forwardRef as Io,useEffect as Vr,useImperativeHandle as Oo,useMemo as Lo,useRef as ut}from"react";import{createCameraWarp as Do}from"@urun-sh/core";import{forwardRef as Uo,useCallback as Ee,useEffect as $e,useImperativeHandle as Ao,useRef as oe,useState as _r}from"react";import{derivedLegRole as Mo}from"@urun-sh/core";var it=null;function Co(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function at(){if(it)return it;let e=Co();return e?(it=new e,it):null}function He(){let e=at();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as Po,useContext as Mr}from"react";import{jsx as wo}from"react/jsx-runtime";var Lt=Po(null);function Eo({session:e,children:t}){return wo(Lt.Provider,{value:e,children:t})}function ge(){return Mr(Lt)}function xo(){let e=Mr(Lt);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{jsx as Dr,jsxs as No}from"react/jsx-runtime";function _o(e,t){return e-t>>>0<2147483648}var Nr=1e3;function Ir(...e){console.debug("[video]",...e)}function Or(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function Lr(e,t,r){return r?[r,t]:[e,t]}var We=Uo(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:m,style:l,videoClassName:g,placeholder:h,poster:w,children:v,onTrack:d,onFirstFrame:b,frameMarker:f,onFrameMarkerReached:S,onFrameMarkerUnsupported:R,onUnlockChange:p}=t,T=ge(),P=o??T,U=oe(null),A=oe(null),[E,N]=_r(!1),[x,V]=_r(!1),$=oe(!1),K=oe(null),G=oe(d);G.current=d;let y=oe(p);y.current=p;let F=oe(b);F.current=b;let q=oe(S);q.current=S;let z=oe(R);z.current=R;let C=oe(f??null);C.current=f??null;let O=Ee(k=>{K.current!==k&&(K.current=k,y.current?.(k))},[]),_=oe(null),W=oe(null),L=Ee((k,D=!1)=>{if(!D&&k===_.current||(_.current=k,W.current?.(),W.current=null,$.current=!1,V(!1),!k))return;let M=U.current;if(!M)return;let j=C.current,J=j?.rtpTimestamp??null,ie=!1,I=()=>{ie||(ie=!0,z.current?.())};j&&J==null&&I();let ve=j!=null&&J!=null,Le=ke=>{W.current?.(),W.current=null,$.current=!0,V(!0),F.current?.(),ke&&q.current?.()};if(typeof M.requestVideoFrameCallback=="function"){let ke=!1,H=0,B=(ae,ue)=>{if(!ke){if(ve){let le=ue?.rtpTimestamp;if(typeof le!="number"){I(),Le(!1);return}if(!_o(le,J)){H=M.requestVideoFrameCallback(B);return}Le(!0);return}Le(!1)}};H=M.requestVideoFrameCallback(B),W.current=()=>{ke=!0,M.cancelVideoFrameCallback?.(H)};return}ve&&I();let ye=()=>{let ke=M.getVideoPlaybackQuality?.();(ke?ke.totalVideoFrames>0:M.readyState>=2&&M.videoWidth>0)&&Le(!1)};M.addEventListener("loadeddata",ye),M.addEventListener("timeupdate",ye),M.addEventListener("playing",ye),W.current=()=>{M.removeEventListener("loadeddata",ye),M.removeEventListener("timeupdate",ye),M.removeEventListener("playing",ye)},ye()},[]);$e(()=>()=>{W.current?.(),W.current=null},[]);let X=f==null?null:`${f.rtpTimestamp??""}|${f.ptsMs??""}`,re=oe(X);$e(()=>{if(re.current===X||(re.current=X,X==null))return;let k=_.current;k&&L(k,!0)},[X,L]);let Z=Ee(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let k=U.current;return k&&k.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(k.srcObject=A.current),A.current},[]),Q=Ee(k=>{let D=U.current;if(!D)return;let M=D.play();!M||typeof M.then!="function"||M.then(()=>{D.muted||O(!0)}).catch(j=>{if((j instanceof Error?j.name:String(j))==="NotAllowedError"&&!D.muted){Ir(`play() blocked pending a user gesture (${k})`),O(!1);return}Ir(`play() failed (${k})`,j)})},[O]),me=Ee(()=>{let k=U.current;k&&(Z(),!k.muted&&(Q("gesture"),He(),O(!0)))},[Z,Q,O]),se=Ee(k=>{let D=Z();if(D){for(let M of D.getVideoTracks())M!==k&&D.removeTrack(M);if(k&&!D.getVideoTracks().includes(k)){D.addTrack(k);let M=U.current;M&&(M.srcObject=D)}k&&Q("track-attach"),N(k!==null),L(k),G.current?.(k)}},[Z,Q,L]),Re=Ee(k=>{let D=Z();if(D){for(let M of D.getAudioTracks())M!==k&&D.removeTrack(M);if(k&&!D.getAudioTracks().includes(k)){D.addTrack(k);let M=U.current;M&&M.srcObject!==D&&(M.srcObject=D)}k&&Q("audio-attach")}},[Z,Q]),ne=Ee(k=>{U.current=k,k&&(a?(k.muted=!0,k.defaultMuted=!0,k.setAttribute("muted",""),K.current=null):(k.muted=!1,k.defaultMuted=!1,k.removeAttribute("muted")),k.setAttribute("playsinline",""),k.setAttribute("webkit-playsinline",""),Z())},[Z,a]);Ao(r,()=>({get element(){return U.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return $.current},unlock:me,get unlocked(){return K.current===!0}}),[me]);let ee=Mo(n)!==void 0;$e(()=>{ee&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[ee,n]);let Y=i!==void 0;return $e(()=>{if(Y){se(i??null);return}if(ee){se(null);return}if(!P)return;let k=Or(P,Lr(n,"video")),D=()=>{let I=A.current;return I?I.getVideoTracks()[0]??null:null},M=I=>{if(I!==D()&&(se(I),I)){let ve=()=>{D()===I&&se(null)};I.addEventListener("ended",ve)}},j=k.track;j&&j.readyState==="live"&&M(j);let J=k.on("track",I=>{I&&I.readyState!=="live"||M(I)}),ie=setInterval(()=>{let I=k.track;I&&I.readyState==="live"&&M(I)},Nr);return()=>{J(),clearInterval(ie)}},[P,n,ee,Y,i,se]),$e(()=>{if(Y||!P||s===!1||ee)return;let k=Or(P,Lr(n,"audio",s)),D=()=>{let I=A.current;return I?I.getAudioTracks()[0]??null:null},M=I=>{if(I!==D()&&(Re(I),I)){let ve=()=>{D()===I&&Re(null)};I.addEventListener("ended",ve)}},j=k.track;j&&j.readyState==="live"&&M(j);let J=k.on("track",I=>{I&&I.readyState!=="live"||M(I)}),ie=setInterval(()=>{let I=k.track;I&&I.readyState==="live"&&M(I)},Nr);return()=>{J(),clearInterval(ie)}},[P,n,ee,s,Y,Re]),No("div",{className:m,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":E?"true":"false","data-urun-video-framed":x?"true":"false",children:[Dr("video",{ref:ne,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),E?null:h,w===void 0?null:Dr("div",{"data-urun-video-poster":"","aria-hidden":x||void 0,style:{position:"absolute",inset:0,...x?{opacity:0,pointerEvents:"none"}:null},children:w}),v]})});import{jsx as Fr,jsxs as qo}from"react/jsx-runtime";var Vo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},Fo=Io(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...m}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=ut(null),h=ut(null),w=ut(0),v=ut(m);v.current=m;let d=Lo(()=>Do(v.current),[]);return Oo(r,()=>({get video(){return g.current},get canvas(){return h.current},warp:d,get lastDrawTs(){return w.current}}),[d]),Vr(()=>{if(!i)return;let b=0,f=0,S=null,R=T=>{typeof T.requestVideoFrameCallback=="function"&&(S=T,f=T.requestVideoFrameCallback(function P(){d.frameArrived(),f=T.requestVideoFrameCallback(P)}))},p=T=>{b=requestAnimationFrame(p);let P=h.current,U=g.current?.element??null;if(!P||!U||(U!==S&&(S&&f&&S.cancelVideoFrameCallback?.(f),R(U)),U.readyState<2))return;d.tick(T);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,E=Math.max(1,Math.round(P.clientWidth*A)),N=Math.max(1,Math.round(P.clientHeight*A));(P.width!==E||P.height!==N)&&(P.width=E,P.height=N);let x=P.getContext("2d");if(!x)return;let V=d.transform(),$=U.videoWidth||E,K=U.videoHeight||N,y=Math.max(E/$,N/K)*(1+a)*V.scale;x.setTransform(y,0,0,y,E/2+V.translateX*E,N/2+V.translateY*N),x.drawImage(U,-$/2,-K/2),w.current=T};return b=requestAnimationFrame(p),()=>{cancelAnimationFrame(b),S&&f&&S.cancelVideoFrameCallback?.(f)}},[i,a,d]),Vr(()=>{if(!i||!c||!l)return;let b=()=>!!l.pointerLockElement,f=P=>{b()&&d.keyDown(P.key)},S=P=>d.keyUp(P.key),R=P=>{b()&&d.pointerDelta(P.movementX,P.movementY)},p=()=>{b()||d.clearKeys()},T=()=>d.clearKeys();return l.addEventListener("keydown",f),l.addEventListener("keyup",S),l.addEventListener("mousemove",R),l.addEventListener("pointerlockchange",p),l.defaultView?.addEventListener("blur",T),()=>{l.removeEventListener("keydown",f),l.removeEventListener("keyup",S),l.removeEventListener("mousemove",R),l.removeEventListener("pointerlockchange",p),l.defaultView?.removeEventListener("blur",T)}},[i,c,l,d]),i?qo(We,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[Fr("canvas",{ref:h,style:Vo,"data-urun-warp":""}),n]}):Fr(We,{ref:g,...s,children:n})});var qr=new Map;function Ho(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);qr.set(e,{component:t,schema:r})}function Hr(e,t){let r=qr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as Bo,jsx as ct}from"react/jsx-runtime";function Wo({name:e,props:t,fallback:r}){let o=Hr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?ct(Bo,{children:r}):ct("div",{className:"urun-component-error",role:"alert",children:ct("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return ct(n,{...o.validatedProps})}import{z as Ge}from"zod";import{jsx as Dt,jsxs as Wr}from"react/jsx-runtime";var jo=Ge.object({step:Ge.number().min(0),total:Ge.number().min(1),label:Ge.string().optional(),variant:Ge.enum(["default","success","error"]).default("default")});function Br(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Ko(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Br(e);return Wr("div",{className:"urun-progress-card","data-variant":n,children:[o&&Dt("div",{className:"urun-progress-label",children:o}),Dt("div",{className:"urun-progress-bar",children:Dt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Wr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Vt}from"zod";import{jsx as jr,jsxs as zo}from"react/jsx-runtime";var $o=Vt.object({state:Vt.enum(["thinking","generating","idle","error"]),message:Vt.string().optional()}),Go={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Kr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Go[t]??t;return{state:t,message:n,isActive:o}}function Xo(e){let{state:t,message:r,isActive:o}=Kr(e);return zo("span",{className:"urun-status-badge","data-state":t,children:[jr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),jr("span",{className:"urun-status-message",children:r})]})}import{useRef as $r,useEffect as Jo}from"react";import{z as Ft}from"zod";import{jsx as Gr,jsxs as Qo}from"react/jsx-runtime";var Yo=Ft.object({text:Ft.string(),streaming:Ft.boolean().default(!1)});function Xr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Zo(e){let{text:t,streaming:r}=Xr(e),o=$r(null),n=$r(0);return Jo(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Qo("div",{className:"urun-text-stream",children:[Gr("span",{ref:o,className:"urun-text-content"}),r&&Gr("span",{className:"urun-text-cursor"})]})}import{z as lt}from"zod";import{jsx as zr,jsxs as rs}from"react/jsx-runtime";var es=lt.object({src:lt.string().url(),alt:lt.string().optional(),caption:lt.string().optional()});function Jr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function ts(e){let{src:t,alt:r,caption:o}=Jr(e);return rs("figure",{className:"urun-image-frame",children:[zr("img",{className:"urun-image",src:t,alt:r}),o&&zr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as xe}from"zod";import{jsx as qt,jsxs as ss}from"react/jsx-runtime";var ns=xe.object({metrics:xe.array(xe.object({label:xe.string(),value:xe.union([xe.string(),xe.number()]),unit:xe.string().optional()}))});function Yr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function os(e){let{metrics:t}=Yr(e);return qt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>ss("div",{className:"urun-metric-card",children:[qt("div",{className:"urun-metric-label",children:r.label}),qt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{useCallback as dt,useEffect as Ht,useRef as ce,useState as is}from"react";import{jsx as fs}from"react/jsx-runtime";function we(e){return e&&typeof e=="object"?e:null}function Qr(e){if(typeof e=="string")return e;let t=we(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function as(e){if(typeof e=="string")return"delta";let t=we(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function us(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function cs(e){let t=we(e),r=t?.body;return us(r,we(we(r)?.error)?.message,we(r)?.error,we(r)?.message,we(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var Xe=class extends Error{name="TextStreamError"},ls=4,en=3,tn=240,Zr=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function rn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function ds(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function nn(e){let{session:t,stream:r}=e,o=ce(e);Ht(()=>{o.current=e});let n=ce(null),s=ce(()=>{}),i=ce(null),a=ce(""),c=ce(""),u=ce(null),m=ce(!1),l=ce(!1),g=ce(!1),h=ce(null),w=ce(rn()),v=dt(S=>{if(n.current=S,!S){i.current=null;return}let R=i.current;if(R&&R.parentNode===S)return;let p=S.ownerDocument.createTextNode(c.current);S.appendChild(p),i.current=p,a.current.length>0&&s.current()},[]),d=dt(()=>{u.current=null;let S=i.current,R=a.current;if(R.length>0){let A=o.current,E=A.smoothCharsPerFrame??en,N=A.smoothThreshold??tn,x=A.smooth&&R.length<=N?R.slice(0,E):R;a.current=R.slice(x.length),c.current+=x,S?.appendData(x)}let p=w.current,T=c.current.length,P=h.current===null?0:Math.max(0,Zr()-h.current),U=Math.round(T/ls);if(p.chars=T,p.tokens=U,p.elapsedMs=P,p.tokensPerSecond=P>0?U*1e3/P:0,a.current.length>0){b(),o.current.onMeter?.(p);return}if(!m.current&&!g.current){g.current=!0,p.done=!0,o.current.onMeter?.(p),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(p)},[]),b=dt(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>d()))},[d]);s.current=b,Ht(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,h.current=null,m.current=!0,ds(w.current),i.current&&(i.current.data="");let S=!1,R=null;return(async()=>{try{for(R=t.stream(r).messages()[Symbol.asyncIterator]();;){let T=await R.next();if(S)return;if(T.done)break;let P=T.value,U=as(P);if(U==="error")throw new Xe(cs(P));if(U==="done")break;if(U==="ignore")continue;let A=Qr(P);A&&(h.current===null&&(h.current=Zr()),a.current+=A,b())}if(S)return;R.return?.(void 0),m.current=!1,b()}catch(p){if(S)return;R?.return?.(void 0),l.current=!0,m.current=!1,o.current.onError?.(p instanceof Error?p:new Xe(String(p))),b()}})(),()=>{S=!0,m.current=!1,R?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,b]);let f=dt(()=>c.current,[]);return{ref:v,meterRef:w,getText:f}}function ps(e,t=250){let[r,o]=is(rn);return Ht(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function ms(e){let{className:t,style:r,...o}=e,{ref:n}=nn(o);return fs("span",{ref:n,className:t,style:r})}import{forwardRef as gs}from"react";import{jsx as hs}from"react/jsx-runtime";var Ss=gs(function(t,r){let{stream:o="image",...n}=t;return hs(We,{ref:r,stream:o,...n})});import{forwardRef as vs,useCallback as Se,useEffect as Wt,useImperativeHandle as ys,useRef as Te}from"react";import{observePageLifecycle as ks}from"@urun-sh/core";import{jsx as Cs}from"react/jsx-runtime";var bs=1e3,Ts=1e3;function Bt(...e){console.debug("[audio]",...e)}var pt=vs(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:m}=t,l=ge(),g=o??l,h=Te(null),w=Te(null),v=Te(null),d=Te(null),b=Te(null),f=Te(0),S=Te(c);S.current=c;let R=Te(u);R.current=u;let p=Se(y=>{v.current!==y&&(v.current=y,R.current?.(y))},[]),T=Se(()=>{if(typeof MediaStream>"u")return null;w.current||(w.current=new MediaStream);let y=h.current;return y&&y.srcObject!==w.current&&w.current.getAudioTracks().length>0&&(y.srcObject=w.current),w.current},[]),P=Se(()=>{f.current=0,b.current!==null&&cancelAnimationFrame(b.current),b.current=null,d.current!==null&&clearTimeout(d.current),d.current=null},[]),U=Se(y=>{b.current=null,d.current=null,T(),N.current(`${y}:retry`)},[T]),A=Se(y=>{if(!h.current||b.current!==null||d.current!==null)return;let q=w.current;if(!(!!q&&q.getAudioTracks().some(O=>O.readyState==="live"))){P();return}let C=f.current;if(f.current=C+1,C===0&&typeof requestAnimationFrame=="function"){b.current=requestAnimationFrame(()=>U(y));return}d.current=setTimeout(()=>U(y),Ts)},[P,U]),E=Se(y=>{let F=h.current;if(!F)return;let q=F.play();!q||typeof q.then!="function"||q.then(()=>{F.muted||p(!0),P()}).catch(z=>{let C=z instanceof Error?z.name:String(z);if(C==="AbortError"){Bt(`play() aborted (${y}); retrying on the ladder`),A(`${y}:abort`);return}if(C==="NotAllowedError"){Bt(`play() blocked pending a user gesture (${y})`),p(!1),A(`${y}:blocked`);return}Bt(`play() failed (${y})`,z)})},[p]),N=Te(()=>{});N.current=E;let x=Se(y=>{let F=T();if(F){for(let q of F.getAudioTracks())q!==y&&F.removeTrack(q);y&&!F.getAudioTracks().includes(y)&&F.addTrack(y),T(),y&&E("track-attach"),S.current?.(y)}},[T,E]),V=Se(()=>{let y=h.current;y&&(T(),y.muted=!1,E("gesture"),He(),p(!0))},[T,E,p]);ys(r,()=>({unlock:V,get unlocked(){return v.current===!0},get element(){return h.current}}),[V]);let $=Se(()=>{A("pause-event")},[A]),K=Se(y=>{let F=h.current;F&&F!==y&&F.removeEventListener("pause",$),h.current=y,y&&(y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),T(),y.addEventListener("pause",$)),m?.(y)},[T,m,$]),G=s!==void 0;return Wt(()=>{if(G){x(s??null);return}if(!g)return;let y=g.stream(n),F=()=>{let _=w.current;return _?_.getAudioTracks()[0]??null:null},q=_=>{if(_!==F()&&(x(_),_)){let W=()=>{F()===_&&x(null)};_.addEventListener("ended",W)}},z=y.track;z&&z.readyState==="live"&&q(z);let C=y.on("track",_=>{_&&_.readyState!=="live"||q(_)}),O=setInterval(()=>{let _=y.track;_&&_.readyState==="live"&&q(_)},bs);return()=>{C(),clearInterval(O)}},[g,n,G,s,x]),Wt(()=>ks(()=>{He(),v.current===!0&&E("foreground")}),[E]),Wt(()=>()=>{d.current&&clearTimeout(d.current),b.current!==null&&cancelAnimationFrame(b.current),b.current=null},[]),Cs("audio",{ref:K,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Rs=pt;import{forwardRef as Ps,useCallback as _e,useEffect as jt,useImperativeHandle as Es,useRef as de}from"react";import{observePageLifecycle as xs,SessionFailedError as ws,sessionFailureFromMediaError as Us,sharedCaptureController as As}from"@urun-sh/core";import{jsx as Ns}from"react/jsx-runtime";var on={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function mt(...e){console.debug("[voice]",...e)}function Ms(e){return e instanceof ws&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var ft=Ps(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=on,connectTimeoutMs:c,attempts:u=3,retryDelayMs:m=1500,onActiveChange:l,onError:g,onMicStream:h,onTrack:w,onUnlockChange:v,capture:d}=t,b=ge(),f=o??b,S=de(null),R=de(null),p=de(null),T=de([]),P=de(!1),U=de(l);U.current=l;let A=de(g);A.current=g;let E=de(h);E.current=h;let N=_e(C=>{P.current!==C&&(P.current=C,U.current?.(C))},[]),x=_e(()=>{for(let C of T.current)C();T.current=[],p.current?.release(),p.current=null,R.current&&(R.current=null,E.current?.(null))},[]),V=_e(async()=>{let C=p.current;if(C){let L=await C.update(a);return R.current=C.stream,E.current?.(C.stream),L}let _=await(d??As()).claim("audio",a);p.current=_,T.current=[_.onTrack((L,X)=>{R.current=X,E.current?.(X),P.current&&f?.stream(n).attach(L).catch(re=>mt("mic re-attach after one-capture re-acquire failed",re))}),_.onLost(L=>{p.current=null,T.current=[],R.current=null,E.current?.(null),N(!1),A.current?.(L)})],R.current=_.stream,E.current?.(_.stream);let W=_.track;if(!W)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return W},[d,a,f,n,N]),$=_e(async()=>{x(),N(!1),await f?.stream(n).detach().catch(()=>{})},[f,n,x,N]),K=_e(async()=>{if(!f)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");S.current?.unlock();let C;try{C=await V()}catch(W){x();let L=Us(W,f.status);throw A.current?.(L),L}let O;for(let W=1;W<=u;W++)try{await f.whenLive(c!==void 0?{timeout:c}:void 0),await f.stream(n).attach(C),N(!0);return}catch(L){if(O=L,mt(`start attempt ${W}/${u} failed`,L),Ms(L))break;f.connect?.(),W<u&&await new Promise(X=>setTimeout(X,m))}x(),N(!1);let _=O instanceof Error?O:new Error(String(O??"voice start failed"));throw A.current?.(_),_},[f,n,c,u,m,V,x,N]);Es(r,()=>({start:K,stop:$,unlock:()=>S.current?.unlock(),get active(){return P.current},get micStream(){return R.current},get audio(){return S.current}}),[K,$]);let G=de(K);G.current=K;let y=de(null),F=_e((C,O)=>{C.promise.then(()=>{O&&(x(),N(!1)),C.session.stream(C.streamName).detach().catch(()=>{})})},[x,N]);jt(()=>{if(!i||!f)return;let C=y.current;C&&(C.session!==f||C.streamName!==n)&&(C.disposeTimer&&clearTimeout(C.disposeTimer),F(C,!1),C=null),C?C.disposeTimer&&(clearTimeout(C.disposeTimer),C.disposeTimer=null):(C={session:f,streamName:n,promise:G.current().catch(()=>{}),refCount:0,disposeTimer:null},y.current=C),C.refCount+=1;let O=C;return()=>{O.refCount-=1,!(O.refCount>0)&&(O.disposeTimer=setTimeout(()=>{y.current===O&&(y.current=null),F(O,!0)},0))}},[i,f,n,F]);let q=de(!1),z=_e(async()=>{if(!f||!P.current||q.current)return;let C=R.current?.getAudioTracks()[0]??null;if(C&&C.readyState==="live"){try{await f.stream(n).attach(C)}catch(O){mt("foreground mic re-assert failed (will retry on next pass)",O)}return}q.current=!0;try{let O=await V();await f.stream(n).attach(O)}catch(O){let _=O instanceof Error?O:new Error(String(O));mt("foreground mic re-acquire failed",_),A.current?.(_)}finally{q.current=!1}},[f,n,V]);return jt(()=>{let C=()=>{z()};return f&&typeof f.onRecovery=="function"?f.onRecovery(C):xs(C)},[f,z]),jt(()=>x,[x]),s?Ns(pt,{ref:S,session:f,stream:n,onTrack:w,onUnlockChange:v}):null}),_s=ft;import{forwardRef as Ls,useImperativeHandle as Ds,useRef as sn,useState as Vs}from"react";import{useEffect as Is,useState as Os}from"react";var Kt={level:0,speaking:!1};function $t(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Os(Kt);return Is(()=>{if(!e){i(Kt);return}let a=at();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,m;try{u=a.createMediaStreamSource(c),m=a.createAnalyser(),m.fftSize=r,u.connect(m)}catch{return}let l=new Uint8Array(m.fftSize),h=setInterval(()=>{m.getByteTimeDomainData(l);let w=0;for(let d=0;d<l.length;d++){let b=(l[d]-128)/128;w+=b*b}let v=Math.sqrt(w/l.length);i(d=>{let b=v>n;return Math.abs(d.level-v)<.005&&d.speaking===b?d:{level:v,speaking:b}})},o);return()=>{clearInterval(h),u.disconnect(),i(Kt)}},[e,r,o,n]),s}import{Fragment as Ws,jsx as gt,jsxs as Bs}from"react/jsx-runtime";var Fs={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},qs={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Hs=Ls(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:m,onMicStream:l,capture:g}=t,h=ge(),w=o??h,v=sn(null),[d,b]=Vs(null),f=sn(l);f.current=l;let{level:S,speaking:R}=$t(a?d:null);return Ds(r,()=>({start:()=>{let p=v.current;return p?p.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>v.current?.stop()??Promise.resolve(),get active(){return v.current?.active??!1},get micStream(){return v.current?.micStream??null}}),[]),Bs(Ws,{children:[gt(ft,{ref:v,session:w,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:m,onMicStream:p=>{b(p),f.current?.(p)}}),a?gt("span",{className:c,style:Fs,"data-urun-mic":"","data-urun-mic-active":d?"true":"false","data-urun-mic-speaking":R?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(S*100)/100,children:gt("span",{style:qs,children:gt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(S*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as js,sessionFailureFromMediaError as Ks,sharedCaptureController as $s}from"@urun-sh/core";import{forwardRef as un,useCallback as he,useEffect as Gt,useImperativeHandle as Gs,useRef as te,useState as ze}from"react";import{jsx as Ue,jsxs as an}from"react/jsx-runtime";var cn={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Xt(...e){console.debug("[camera]",...e)}function Xs(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function zs(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var ln=un(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:m="auto",connectTimeoutMs:l,visible:g=!1,className:h,videoClassName:w,onActiveChange:v,onError:d,onStream:b,onTrack:f,children:S,capture:R,flipControl:p="auto",flipControlClassName:T,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":c??"environment",A=ge(),E=o??A,N=te(null),x=te(null),V=te(null),$=te([]),K=te(null),G=te(!1),y=te(!1),F=te(U),[q,z]=ze(U),[C,O]=ze(!1),[_,W]=ze(null),[L,X]=ze(!1),[re]=ze(Xs),Z=te(v);Z.current=v;let Q=te(d);Q.current=d;let me=te(b);me.current=b;let se=te(f);se.current=f;let Re=te(P);Re.current=P;let ne=he(H=>{G.current!==H&&(G.current=H,O(H),Z.current?.(H))},[]);Gt(()=>{if(!C){W(null);return}let H=!1,B=()=>{zs().then(ue=>{H||(W(ue),ue&&Re.current?.(ue))})};B();let ae=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ae?.addEventListener=="function"?(ae.addEventListener("devicechange",B),()=>{H=!0,ae.removeEventListener?.("devicechange",B)}):()=>{H=!0}},[C]);let ee=he(H=>{let B=N.current;B&&(B.muted=!0,B.defaultMuted=!0,B.setAttribute("muted",""),B.setAttribute("playsinline",""),B.setAttribute("webkit-playsinline",""),B.srcObject=H,H&&B.play()?.catch?.(ae=>Xt("preview play() failed",ae)))},[]),Y=he(()=>{y.current=!1,K.current?.(),K.current=null;for(let H of $.current)H();$.current=[],V.current?.release(),V.current=null,x.current&&(x.current=null,me.current?.(null),se.current?.(null)),ee(null)},[ee]),k=he((H,B)=>{K.current?.(),x.current=B,ee(B),me.current?.(B);let ae=()=>{x.current===B&&(Xt("camera track ended (device removed or permission revoked)"),Y(),ne(!1))};H.addEventListener("ended",ae),K.current=()=>H.removeEventListener("ended",ae)},[ee,Y,ne]),D=he(async H=>{let B=n!==!1;if(B&&!E)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ae={...cn,...s,facingMode:H},ue;try{let le=V.current;if(le)ue=await le.update(ae);else{let Be=await(R??$s()).claim("video",ae);if(V.current=Be,$.current=[Be.onTrack((je,En)=>{k(je,En),G.current&&(!B||!E||E.stream(n).attachVideo(je).then(()=>se.current?.(je)).catch(xn=>Xt("camera re-publish after one-capture re-acquire failed",xn)))}),Be.onLost(je=>{V.current=null,$.current=[],Y(),ne(!1),Q.current?.(je)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ue=Be.track}}catch(le){let De=Ks(le,E?.status);throw Q.current?.(De),De}F.current=H,z(H),k(ue,V.current?.stream??new MediaStream([ue]));try{B&&E&&(E.connect?.(),await E.whenLive(l!==void 0?{timeout:l}:void 0),await E.stream(n).attachVideo(ue)),y.current=B?n:!1}catch(le){Y(),ne(!1);let De=le instanceof Error?le:new Error(String(le));throw Q.current?.(De),De}se.current?.(ue),ne(!0)},[E,n,s,l,R,k,Y,ne]),M=he(H=>D(H?.facingMode??F.current),[D]),j=he(async H=>{let B=y.current===n;G.current&&F.current===H&&B||await D(H)},[D,n]),J=he(()=>D(F.current==="environment"?"user":"environment"),[D]),ie=he(async()=>{Y(),ne(!1),n!==!1&&await E?.stream(n).detachVideo().catch(()=>{})},[E,n,Y,ne]),I=he(async H=>{let B=N.current;if(!B)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await js(B,H)},[]);Gs(r,()=>({start:M,stop:ie,flip:J,setFacingMode:j,capturePhoto:I,get active(){return G.current},get facingMode(){return F.current},get stream(){return x.current},get element(){return N.current}}),[M,ie,J,j,I]);let ve=te(j);if(ve.current=j,Gt(()=>{u&&(n!==!1&&!E||ve.current(U).catch(()=>{}))},[u,E,U,n]),Gt(()=>Y,[Y]),!g)return null;let Le=m==="auto"?q==="user":m,ye=C&&(p===!0||p==="auto"&&re&&(_?.length??0)>1),ke=()=>{L||(X(!0),J().catch(()=>{}).finally(()=>X(!1)))};return an("div",{className:h,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":q,children:[Ue("video",{ref:N,className:w,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Le?{transform:"scaleX(-1)"}:{}}}),ye?Ue("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:ke,disabled:L,className:T,style:T?{opacity:L?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:L?.6:1},children:an("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[Ue("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),Ue("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),Ue("path",{d:"M14.5 10.5v1.6h-1.6"}),Ue("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),Ue("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,S]})}),Js=un(function({preview:t=!0,...r},o){return Ue(ln,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Ys,normalizeReferenceImage as Zs,referenceImageErrorMessage as Qs}from"@urun-sh/core";import{useCallback as Je,useEffect as ei,useRef as zt,useState as Ye}from"react";function ti(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=Ye(null),[a,c]=Ye(null),[u,m]=Ye(!1),[l,g]=Ye(null),[h]=Ye(Ys),w=zt(n);w.current=n;let v=zt(null),d=zt(0),b=Je(T=>{v.current&&URL.revokeObjectURL(v.current),v.current=T?URL.createObjectURL(new Blob([T.bytes],{type:T.type})):null,c(v.current),i(T),w.current?.(T)},[]);ei(()=>()=>{d.current++,v.current&&URL.revokeObjectURL(v.current),v.current=null},[]);let f=Je(async T=>{let P=++d.current;m(!0),g(null);try{let U=await T();if(d.current!==P)return;b(U)}catch(U){if(d.current!==P)return;g(Qs(U))}finally{d.current===P&&m(!1)}},[b]),S=Je(T=>f(()=>Zs(T,{maxSize:t,type:r,quality:o,source:"file"})),[f,t,r,o]),R=Je(T=>f(()=>T.capturePhoto({maxSize:t,type:r,quality:o})),[f,t,r,o]),p=Je(()=>{d.current++,g(null),m(!1),b(null)},[b]);return{reference:s,previewUrl:a,pick:S,capture:R,clear:p,busy:u,error:l,cameraAvailable:h}}import{useEffect as ri,useState as ni}from"react";function oi(e,t){let[r,o]=ni(null);return ri(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as li}from"react";import{useEffect as ui,useMemo as ci}from"react";import{createStore as si}from"zustand/vanilla";import{useStore as ii}from"zustand";var ai=()=>{};function Jt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=si(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):ai,c=(u=>ii(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function Ze(e,t){let r=ci(()=>Jt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return ui(()=>r.bind(),[r]),r}function di(e,t,r){let n=Ze(e,t)(r??(a=>a)),s=li(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as pi,useState as mi}from"react";function fi(e){let[t,r]=mi(null);return pi(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}import{useEffect as gi,useState as Si}from"react";var Ne=200;function Ae(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Qe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Yt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Zt(e,t,r={}){let o=r.cap??200,[n,s]=Si([]);return gi(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>Ae(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as St,jsxs as et}from"react/jsx-runtime";function hi({session:e,name:t,cap:r,className:o}){let n=Zt(e,t,{cap:r});return et("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[et("div",{className:"urun-stream-tail-meta",children:[St("code",{children:t}),et("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),St("div",{className:"urun-stream-tail-log",children:n.length===0?et("span",{className:"urun-stream-tail-empty",children:["Waiting for ",St("code",{children:t})," messages\u2026"]}):n.map((s,i)=>et("div",{className:"urun-stream-tail-line",children:[St("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Qe(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as vi,useState as dn}from"react";import{jsx as Ie,jsxs as ht}from"react/jsx-runtime";function vt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=dn(""),[i,a]=dn(null),c=vi(()=>{let u=Yt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return ht("div",{className:"urun-doc-patch",children:[Ie("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),ht("div",{className:"urun-doc-patch-actions",children:[Ie("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?Ie("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function yi({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ze(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return ht("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[ht("div",{className:"urun-doc-panel-meta",children:[Ie("code",{children:t}),Ie("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),Ie("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?Ie(vt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}import{useEffect as ki,useState as bi}from"react";import{jsx as tt,jsxs as mn}from"react/jsx-runtime";function pn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Ti({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=bi([]);return ki(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ae(c,{at:Date.now(),direction:"in",text:pn(Qe(a))},r))}):void 0),[e,t,r]),mn("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[tt(vt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>Ae(c,{at:Date.now(),direction:"out",text:pn(a)},r))}}),tt("div",{className:"urun-control-sender-log",children:n.length===0?tt("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>mn("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[tt("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",tt("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as Ri,useState as Ci}from"react";import{jsx as yt,jsxs as Ei}from"react/jsx-runtime";function Pi({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=Ci([]),a=t.join(","),c=r.join(",");return Ri(()=>{if(i([]),!e)return;let u=(l,g)=>i(h=>Ae(h,{at:Date.now(),kind:l,text:g},o)),m=[];m.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);m.push(g.on("track",h=>u("track",`${l}: ${h?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);m.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>m.forEach(l=>l())},[e,a,c,o]),yt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?yt("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,m)=>Ei("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[yt("span",{className:"urun-event-spine-kind",children:u.kind})," ",yt("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${m}`))})}import{describeSessionPhase as Hi,isWakingPhase as Wi}from"@urun-sh/core";import{useEffect as xi,useState as wi}from"react";function pe(e){let[t,r]=wi(e?.phase??null);return xi(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as Ni}from"@urun-sh/core";import{useEffect as Ui,useRef as Ai,useState as Mi}from"react";import{isWakingPhase as _i}from"@urun-sh/core";function Qt(e){let t=pe(e),r=_i(t?.name),o=Ai(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=Mi(s);return Ui(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as Ii,jsx as fn,jsxs as gn}from"react/jsx-runtime";function er({session:e,render:t,className:r}){let o=Qt(e);return!o.waking||!o.phase?null:fn("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):gn(Ii,{children:[fn("span",{className:"urun-session-waking-label",children:Ni(o.phase)})," ",gn("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Di,useState as Vi}from"react";import{useEffect as Sn,useRef as Oi,useState as hn}from"react";var Li={event:null,elapsedMs:0};function tr(e,t){let[r,o]=hn(null),n=Oi(0);Sn(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=hn(0);return Sn(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:Li}import{jsx as vn,jsxs as yn}from"react/jsx-runtime";var Fi={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function qi(e){let[t,r]=Vi(!1);return Di(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function rr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=tr(e,t),i=qi(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return vn("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):yn("div",{className:"urun-activation-overlay-card",children:[vn("span",{className:"urun-activation-overlay-copy",children:a.hint??Fi[c]})," ",yn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Oe,jsxs as nr}from"react/jsx-runtime";var Bi={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function ji({session:e,className:t}){let r=pe(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return nr("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Oe("span",{className:"urun-session-status-dot","data-phase":o}),Oe("span",{className:"urun-session-status-label",children:Bi[o]}),n?Oe("span",{className:"urun-session-status-detail",children:n}):null]})}function Ki({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=pe(e);if(s?.name==="live")return nr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Oe(rr,{session:e})]});let i=r?r(s):Oe("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&Wi(s.name)?Oe(er,{session:e}):s&&s.name!=="idle"?Hi(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return nr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Oe("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as $i,useState as Gi}from"react";import{jsx as Ji}from"react/jsx-runtime";function kn(e){return pe(e)?.endsAt??null}function Xi(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function zi({session:e,urgentMs:t=6e4,className:r}){let n=kn(e)?.getTime()??null,[s,i]=Gi(()=>n===null?null:Math.max(0,n-Date.now()));if($i(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=Xi(s);return Ji("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{describeSessionPhase as Yi}from"@urun-sh/core";import{jsx as or,jsxs as ea}from"react/jsx-runtime";var Zi=new Set(["paused","error"]);function bn({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=pe(e);if(!s||!Zi.has(s.name))return null;let i=o?o(s):or("span",{className:"urun-session-paused-copy",children:Yi(s)});return ea("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?or("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?or("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var Qi=bn;import{useEffect as Tn,useMemo as ta,useState as Rn}from"react";import{jsx as kt,jsxs as oa}from"react/jsx-runtime";function sr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Cn(e){let t=ta(()=>e?e.doc("control"):null,[e]),[r,o]=Rn(()=>t?sr(t.get("idle")):null);return Tn(()=>{if(!t){o(null);return}return o(sr(t.get("idle"))),t.on("change",()=>o(sr(t.get("idle"))))},[t]),r}function ra(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function na({session:e,onStillHere:t,className:r}){let o=Cn(e),n=o?.deadlineEpochS??null,[s,i]=Rn(null);if(Tn(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return kt("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:oa("div",{className:"urun-idle-warning-card",children:[kt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),kt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${ra(s)} due to inactivity.`:"This session will end soon due to inactivity."}),kt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useCallback as Pn,useEffect as sa,useRef as ia,useState as ir}from"react";function aa(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function ar(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=ir(null),[s,i]=ir(e!==null),[a,c]=ir(null),u=ia(e),m=Pn(async g=>{i(!0);try{let h=await g.getBalance();if(u.current!==g)return;n(h),c(null)}catch(h){if(u.current!==g)return;c(h instanceof Error?h:new Error(String(h)))}finally{u.current===g&&i(!1)}},[]);sa(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(m(e),r!==void 0&&r>0){let g=setInterval(()=>{m(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,m]);let l=Pn(async()=>{let g=u.current;g&&await m(g)},[m]);return{balance:o,isExhausted:aa(o),loading:s,error:a,refresh:l}}import{jsx as ur}from"react/jsx-runtime";function ua({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=ar(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return ur("div",{className:i,children:t});let a=r?r(n):ur("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return ur("div",{className:i,children:a})}import{CreditsClient as Gd,createCreditsClient as Xd,CreditsError as zd,CreditsUnauthorizedError as Jd}from"@urun-sh/core";import{useContext as ca,useEffect as la,useState as da}from"react";import{prewake as pa}from"@urun-sh/core";function ma(e){let t=ca(Ce),[r,o]=da(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,m=t?.getAccessToken,l=t?.authProvider;return la(()=>{if(!a||!c||!n||!s)return;let g=!1,h=()=>{pa({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:m,authProvider:l}).then(v=>{g||o(v)}).catch(()=>{})};h();let w=setInterval(h,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(w)}},[n,s,i,a,c,u,m,l]),r}import{useEffect as fa,useState as ga}from"react";function Sa(e){let[t,r]=ga(null);return fa(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as op,isWakingPhase as sp}from"@urun-sh/core";export{pt as Audio,ln as Camera,Wo as ComponentRenderer,Gd as CreditsClient,zd as CreditsError,Jd as CreditsUnauthorizedError,cn as DEFAULT_CAMERA_CONSTRAINTS,Ne as DEFAULT_LOG_CAP,en as DEFAULT_SMOOTH_CHARS_PER_FRAME,tn as DEFAULT_SMOOTH_THRESHOLD,on as DEFAULT_VOICE_CONSTRAINTS,vt as DocPatchForm,Ss as Image,ts as ImageFrame,es as ImageFrameSchema,os as MetricsPanel,ns as MetricsPanelSchema,Hs as Mic,Ln as OPERATOR_CHORD_LABEL,On as OPERATOR_TOKEN_STORAGE_KEY,Ko as ProgressCard,jo as ProgressCardSchema,Fo as ReprojectedVideo,Eo as Session,Xo as StatusBadge,$o as StatusBadgeSchema,ms as Text,Zo as TextStream,Xe as TextStreamError,Yo as TextStreamSchema,rr as UrunActivationOverlay,Rs as UrunAudio,bt as UrunAuthProvider,Js as UrunCamera,Ti as UrunControlSender,ua as UrunCreditsGate,yi as UrunDocPanel,Ke as UrunErrorBoundary,Pi as UrunEventSpine,na as UrunIdleWarning,wn as UrunJwtProvider,Gn as UrunProvider,zi as UrunSessionClock,Qi as UrunSessionEnded,Ki as UrunSessionGate,bn as UrunSessionPaused,ji as UrunSessionStatus,er as UrunSessionWaking,hi as UrunStreamTail,_s as UrunVoice,We as Video,ft as Voice,rt as authMode,Xd as createCreditsClient,Jt as createDocStore,op as describeSessionPhase,Qe as formatPayload,at as getUrunAudioContext,sp as isWakingPhase,Yt as parseJsonObject,Ae as pushCapped,mr as readOperatorToken,Ho as registerComponent,He as resumeUrunAudioContext,Qr as textDelta,fe as urunPublicEnv,tr as useActivation,to as useApp,vo as useChat,fo as useCompletion,Ct as useConfirmOnLeave,ar as useCredits,Ze as useDocStore,fi as useGenerationTick,Jr as useImageFrame,Ro as useInputPresence,Yr as useMetricsPanel,Rt as useOperatorOverride,Br as useProgressCard,ti as useReferenceImage,co as useRequest,xo as useSession,so as useSessionDirectory,di as useSessionDoc,kn as useSessionEndsAt,Cn as useSessionIdle,pe as useSessionPhase,Sa as useSessionStats,oi as useSessionTrack,Qt as useSessionWake,Kr as useStatusBadge,Zt as useStreamMessages,nn as useText,ps as useTextMeter,Xr as useTextStream,$t as useUrunAudioLevel,Tt as useUrunAuth,ma as useUrunPrewake,_n as usesWorkOSAuth};
|
|
2
|
+
import{a as kt,b as Un,c as Tt}from"./chunk-WF2OBDSX.mjs";import{useCallback as gr,useEffect as Hn,useMemo as kr,useRef as Sr,useState as Pt}from"react";import{computeBackoffDelay as Wn}from"@urun-sh/core/internal";import{Component as An}from"react";import{jsx as lr,jsxs as Mn}from"react/jsx-runtime";var Ke=class extends An{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Mn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[lr("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),lr("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as _n}from"react";var Ce=_n(null);function Te(e){return e&&e.trim()?e.trim():void 0}function ge(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Te(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Te(typeof process<"u"?process.env?.[e]:void 0)}}function rt(){let e=ge("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ge("VERCEL_ENV")==="production"?"workos":ge("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Nn(){return rt()==="workos"}import{useEffect as On,useRef as In}from"react";var Ln="urun.operator_token",pr=null,dr="op",Dn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function mr(){return typeof window<"u"}function fr(){return pr}function Vn(){if(!mr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(dr);if(!r)return null;pr=r,t.delete(dr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Fn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Rt(e){let t=In(e);t.current=e,On(()=>{if(!mr())return;Vn();let r=o=>{if(!Fn(o))return;let n=fr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as qn}from"react";function Ct(e=!0){qn(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as Ve,jsxs as zn}from"react/jsx-runtime";var Bn="/api/urun-token",jn=1e4;function Kn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}var hr=3,$n=new Set([502,503,504]);function vr(e){return new Promise(t=>setTimeout(t,Wn(e)))}async function yr(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=hr-1)throw a;await vr(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!$n.has(o.status)||r>=hr-1)throw a;await vr(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function br(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function Et(e){let t=e===void 0?void 0:JSON.stringify(e);return kr(()=>e,[t])}function Gn(e,t){return typeof e=="function"?e(t):e!==void 0?e:zn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[Ve("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Ve("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Xn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:v,sessionStats:R,confirmOnLeave:h=!1,fallback:p,errorFallback:b,children:C}){let d=n===void 0&&t===void 0;if(!d&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!d&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let k=r??o;if(d&&(typeof k!="string"||k.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Ct(h);let[m,w]=Pt(),[P,E]=Pt(null),A=Sr(void 0),M=Sr(null),[I,x]=Pt(null);Rt(_=>x({jwt:_}));let O=Tt(),$=ge("NEXT_PUBLIC_SESSION_TOKEN")??ge("NEXT_PUBLIC_URUN_JWT"),j=rt(),K=I!==null,G=j==="workos"&&!n&&!K&&!d,J=n??(j==="jwt"?$:void 0)??m?.token,X=K?I.jwt:J,T=s??ge("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),q=G&&!X&&!O?.getAccessToken,S=t??m?.orgId,N=e??m?.gatewayUrl,D=d&&m===void 0,V=d&&m!==void 0&&!N?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,U=q?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,Y=P??V??U,Z=br("NEXT_PUBLIC_URUN_TOKEN_URL",ge("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Bn,ee=br("NEXT_PUBLIC_URUN_EVENTS_URL",ge("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,fe=gr(async _=>{if(!_?.forceRefresh){let z=A.current;if(!z)return z;let ie=Kn(z);if(ie===null||ie-Date.now()>jn)return z}return(await(M.current??(M.current=(async()=>{try{let z=await yr(Z);return A.current=z.token,w(z),z}finally{M.current=null}})()))).token},[Z]),se=gr(async()=>X,[X]),Re=typeof X=="string"&&X.trim().length>0,ne=G?O?.getAccessToken:d&&!K?fe:Re?se:void 0,te=Et(g),Q=Et(v),y=Et(R),F=kr(()=>({appId:k,baseUrl:N??"",orgId:S??"",jwt:X,getAccessToken:G?O?.getAccessToken:d&&!K?fe:void 0,authProvider:T,eventsUrl:ee,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:te,videoPlayout:Q,sessionStats:y,priority:K?"preempt":void 0}),[k,O,N,T,X,ee,S,a,u,f,l,te,Q,y,G,K,d,fe]);return Hn(()=>{if(!d)return;let _=new AbortController;return E(null),(async()=>{try{let B=await yr(Z,_.signal);A.current=B.token,w(B)}catch(B){if(_.signal.aborted)return;E(B instanceof Error?B:new Error(String(B)))}})(),()=>_.abort()},[d,Z]),Ve(Ke,{fallback:p,children:Y?Gn(b,Y):D?Ve("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Ve(Ce.Provider,{value:F,children:ne?Ve(kt,{getAccessToken:ne,children:C}):C})})}import{useContext as Jn,useEffect as Yn,useMemo as Tr,useReducer as Zn,useRef as xt}from"react";import{App as Qn}from"@urun-sh/core";function Rr(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function eo(e,t,r){let o=Rr(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function to(e,t,r,o){let n=Rr(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var Me=new Map;var wt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Ut=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}get directOut(){return this._stream.directOut}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},At=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}watchDownlinkStall(t={}){return this._session.watchDownlinkStall?this._session.watchDownlinkStall(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new wt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Ut(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function ro(){let e=Jn(Ce);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Zn(i=>i+1,0),r=xt(new Map),o=xt(new Map),n=xt(null),s=Tr(()=>Qn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return Yn(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Me.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let f=Me.get(c);f===u&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(c,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let l=Me.get(c);!l||l.refCount!==0||(Me.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),Tr(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let f=(l,g)=>{let v=eo(c,l,g),R=r.current.get(v);if(R&&!R.disposed)return R;let h=to(e,c,l,g),p=Me.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),Me.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new At(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Me.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(c,f),f}})},[e,s])}import{useContext as no,useMemo as oo}from"react";import{sessionDirectory as so}from"@urun-sh/core";function io(){let e=no(Ce);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return oo(()=>so(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}import{useCallback as Mt,useEffect as ao,useMemo as uo,useRef as nt,useState as _t}from"react";function Fe(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function co(e){return e instanceof Error?e:new Error(String(e))}function lo(e,t){let r=uo(()=>Fe(e),[e]),[o,n]=_t(void 0),[s,i]=_t(null),[a,c]=_t(!1),u=nt(t);u.current=t;let f=nt(0),l=nt(null),g=nt(!0);ao(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=Mt(async p=>{l.current?.abort();let b=new AbortController;l.current=b;let C=++f.current,d=()=>g.current&&f.current===C;d()&&(c(!0),i(null));try{let k=await r.request(p,{...u.current,signal:b.signal});return d()&&(n(k),c(!1),u.current?.onSuccess?.(k)),k}catch(k){let m=co(k);throw d()&&(i(m),c(!1),u.current?.onError?.(m)),m}},[r]),R=Mt(p=>{v(p).catch(()=>{})},[v]),h=Mt(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:R,mutateAsync:v,data:o,error:s,isPending:a,reset:h}}import{useCallback as Cr,useEffect as po,useMemo as mo,useRef as ot,useState as Nt}from"react";function Pr(e){return e instanceof Error?e:new Error(String(e))}var fo=e=>typeof e=="string"?e:String(e);function go(e,t){let r=mo(()=>Fe(e),[e]),[o,n]=Nt(""),[s,i]=Nt(!1),[a,c]=Nt(null),u=ot(t);u.current=t;let f=ot(0),l=ot(null),g=ot(!0);po(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=Cr(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),R=Cr(async h=>{l.current?.cancel();let p=++f.current,b=()=>g.current&&f.current===p,C=u.current,d=C?.parseChunk??fo,k=C?.buildPayload??(x=>({prompt:x}));b()&&(n(""),c(null),i(!0));let{parseChunk:m,buildPayload:w,onFinish:P,onError:E,...A}=C??{},M="",I;try{I=r.requestStream(k(h),A),l.current=I}catch(x){let O=Pr(x);b()&&(c(O),i(!1),C?.onError?.(O));return}try{for await(let x of I){if(f.current!==p)break;M+=d(x),b()&&n(M)}b()&&(i(!1),C?.onFinish?.(M))}catch(x){let O=Pr(x);b()&&(c(O),i(!1),C?.onError?.(O))}finally{l.current===I&&(l.current=null)}},[r]);return{completion:o,complete:R,stop:v,isStreaming:s,error:a}}import{useCallback as Er,useEffect as So,useMemo as ho,useRef as qe,useState as st}from"react";function xr(e){return e instanceof Error?e:new Error(String(e))}var vo=e=>typeof e=="string"?e:String(e),wr=0;function Ot(e){return wr+=1,`${e}-${wr}`}function yo(e,t){let r=ho(()=>Fe(e),[e]),[o,n]=st(()=>(t?.initialMessages??[]).map(d=>({id:d.id??Ot("msg"),role:d.role,content:d.content}))),[s,i]=st(""),[a,c]=st(!1),[u,f]=st(null),l=qe(t);l.current=t;let g=qe(o);g.current=o;let v=qe(s);v.current=s;let R=qe(0),h=qe(null),p=qe(!0);So(()=>(p.current=!0,()=>{p.current=!1,h.current?.cancel(),h.current=null}),[]);let b=Er(()=>{R.current++,h.current?.cancel(),h.current=null,p.current&&c(!1)},[]),C=Er(async d=>{let k=d===void 0,m=(k?v.current:d)??"";if(!m.trim())return;h.current?.cancel();let P=++R.current,E=()=>p.current&&R.current===P,A=l.current,M=A?.parseChunk??vo,I={id:Ot("msg"),role:"user",content:m},x={id:Ot("msg"),role:"assistant",content:""},O=[...g.current,I].map(V=>({role:V.role,content:V.content})),$=[...g.current,I,x];g.current=$,n($),k&&i(""),f(null),c(!0);let j=A?.buildPayload??(V=>({messages:V})),{initialMessages:K,parseChunk:G,buildPayload:J,onFinish:X,onError:T,...q}=A??{},S=V=>{n(U=>U.map(Y=>Y.id===x.id?{...Y,content:V}:Y))},N="",D;try{D=r.requestStream(j(O),q),h.current=D}catch(V){let U=xr(V);E()&&(f(U),c(!1),A?.onError?.(U));return}try{for await(let V of D){if(R.current!==P)break;N+=M(V),E()&&S(N)}E()&&(c(!1),A?.onFinish?.({...x,content:N}))}catch(V){let U=xr(V);E()&&(f(U),c(!1),A?.onError?.(U))}finally{h.current===D&&(h.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:C,stop:b,isStreaming:a,error:u}}import{useCallback as Pe,useEffect as Ur,useMemo as bo,useRef as Ar,useState as Mr}from"react";import{createInputPresencePublisher as ko,INPUT_PRESENCE_DEFAULT_HZ as To,INPUT_PRESENCE_FIELD as Ro}from"@urun-sh/core";var It=[];function Co(e,t={}){let{field:r=Ro,hz:o=To}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=bo(()=>s?ko({awareness:{setLocalStateField:(m,w)=>s.setField(m,w)},field:r,hz:o}):null,[s,r,o]),a=Ar(null);a.current=i;let[c,u]=Mr(!1),[f,l]=Mr(It),g=Ar(!1);Ur(()=>{if(i)return()=>i.dispose()},[i]);let v=Pe(()=>{let m=a.current;l(m?m.heldKeys():It)},[]),R=Pe(()=>{a.current?.clear(),l(It)},[]);Ur(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,w=()=>{if(m()){g.current=!1,u(!0);return}g.current||(u(!1),R())},P=x=>{m()&&(a.current?.keyDown(x.key),v())},E=x=>{a.current?.keyUp(x.key),v()},A=x=>{m()&&a.current?.movePointer(x.movementX,x.movementY)},M=x=>{m()&&a.current?.setButtons(x.buttons)},I=()=>{R()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",P),n.addEventListener("keyup",E),n.addEventListener("mousemove",A),n.addEventListener("mousedown",M),n.addEventListener("mouseup",M),n.defaultView?.addEventListener("blur",I),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",P),n.removeEventListener("keyup",E),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",M),n.removeEventListener("mouseup",M),n.defaultView?.removeEventListener("blur",I)}},[n,R,v]);let h=Pe(m=>{m.requestPointerLock?.()},[]),p=Pe(()=>{g.current=!0,u(!0)},[]),b=Pe(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),R()},[n,R]),C=Pe(m=>{a.current?.keyDown(m),v()},[v]),d=Pe(m=>{a.current?.keyUp(m),v()},[v]),k=Pe((m,w)=>{a.current?.movePointer(m,w)},[]);return{engage:h,engageTouch:p,release:b,engaged:c,heldKeys:f,pressKey:C,releaseKey:d,movePointer:k}}import{forwardRef as Io,useEffect as Fr,useImperativeHandle as Lo,useMemo as Do,useRef as ut}from"react";import{createCameraWarp as Vo}from"@urun-sh/core";import{forwardRef as Ao,useCallback as Ee,useEffect as $e,useImperativeHandle as Mo,useRef as oe,useState as Nr}from"react";import{derivedLegRole as _o}from"@urun-sh/core";var it=null;function Po(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function at(){if(it)return it;let e=Po();return e?(it=new e,it):null}function He(){let e=at();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as Eo,useContext as _r}from"react";import{jsx as Uo}from"react/jsx-runtime";var Lt=Eo(null);function xo({session:e,children:t}){return Uo(Lt.Provider,{value:e,children:t})}function Se(){return _r(Lt)}function wo(){let e=_r(Lt);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{jsx as Vr,jsxs as Oo}from"react/jsx-runtime";function No(e,t){return e-t>>>0<2147483648}var Or=1e3;function Ir(...e){console.debug("[video]",...e)}function Lr(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function Dr(e,t,r){return r?[r,t]:[e,t]}var We=Ao(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:f,style:l,videoClassName:g,placeholder:v,poster:R,children:h,onTrack:p,onFirstFrame:b,frameMarker:C,onFrameMarkerReached:d,onFrameMarkerUnsupported:k,onUnlockChange:m}=t,w=Se(),P=o??w,E=oe(null),A=oe(null),[M,I]=Nr(!1),[x,O]=Nr(!1),$=oe(!1),j=oe(null),K=oe(p);K.current=p;let G=oe(m);G.current=m;let J=oe(b);J.current=b;let X=oe(d);X.current=d;let T=oe(k);T.current=k;let q=oe(C??null);q.current=C??null;let S=Ee(y=>{j.current!==y&&(j.current=y,G.current?.(y))},[]),N=oe(null),D=oe(null),V=Ee((y,F=!1)=>{if(!F&&y===N.current||(N.current=y,D.current?.(),D.current=null,$.current=!1,O(!1),!y))return;let _=E.current;if(!_)return;let B=q.current,z=B?.rtpTimestamp??null,ie=!1,L=()=>{ie||(ie=!0,T.current?.())};B&&z==null&&L();let ye=B!=null&&z!=null,Le=ke=>{D.current?.(),D.current=null,$.current=!0,O(!0),J.current?.(),ke&&X.current?.()};if(typeof _.requestVideoFrameCallback=="function"){let ke=!1,H=0,W=(ae,ue)=>{if(!ke){if(ye){let le=ue?.rtpTimestamp;if(typeof le!="number"){L(),Le(!1);return}if(!No(le,z)){H=_.requestVideoFrameCallback(W);return}Le(!0);return}Le(!1)}};H=_.requestVideoFrameCallback(W),D.current=()=>{ke=!0,_.cancelVideoFrameCallback?.(H)};return}ye&&L();let be=()=>{let ke=_.getVideoPlaybackQuality?.();(ke?ke.totalVideoFrames>0:_.readyState>=2&&_.videoWidth>0)&&Le(!1)};_.addEventListener("loadeddata",be),_.addEventListener("timeupdate",be),_.addEventListener("playing",be),D.current=()=>{_.removeEventListener("loadeddata",be),_.removeEventListener("timeupdate",be),_.removeEventListener("playing",be)},be()},[]);$e(()=>()=>{D.current?.(),D.current=null},[]);let U=C==null?null:`${C.rtpTimestamp??""}|${C.ptsMs??""}`,Y=oe(U);$e(()=>{if(Y.current===U||(Y.current=U,U==null))return;let y=N.current;y&&V(y,!0)},[U,V]);let Z=Ee(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let y=E.current;return y&&y.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(y.srcObject=A.current),A.current},[]),ee=Ee(y=>{let F=E.current;if(!F)return;let _=F.play();!_||typeof _.then!="function"||_.then(()=>{F.muted||S(!0)}).catch(B=>{if((B instanceof Error?B.name:String(B))==="NotAllowedError"&&!F.muted){Ir(`play() blocked pending a user gesture (${y})`),S(!1);return}Ir(`play() failed (${y})`,B)})},[S]),fe=Ee(()=>{let y=E.current;y&&(Z(),!y.muted&&(ee("gesture"),He(),S(!0)))},[Z,ee,S]),se=Ee(y=>{let F=Z();if(F){for(let _ of F.getVideoTracks())_!==y&&F.removeTrack(_);if(y&&!F.getVideoTracks().includes(y)){F.addTrack(y);let _=E.current;_&&(_.srcObject=F)}y&&ee("track-attach"),I(y!==null),V(y),K.current?.(y)}},[Z,ee,V]),Re=Ee(y=>{let F=Z();if(F){for(let _ of F.getAudioTracks())_!==y&&F.removeTrack(_);if(y&&!F.getAudioTracks().includes(y)){F.addTrack(y);let _=E.current;_&&_.srcObject!==F&&(_.srcObject=F)}y&&ee("audio-attach")}},[Z,ee]),ne=Ee(y=>{E.current=y,y&&(a?(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted",""),j.current=null):(y.muted=!1,y.defaultMuted=!1,y.removeAttribute("muted")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),Z())},[Z,a]);Mo(r,()=>({get element(){return E.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return $.current},unlock:fe,get unlocked(){return j.current===!0}}),[fe]);let te=_o(n)!==void 0;$e(()=>{te&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[te,n]);let Q=i!==void 0;return $e(()=>{if(Q){se(i??null);return}if(te){se(null);return}if(!P)return;let y=Lr(P,Dr(n,"video")),F=()=>{let L=A.current;return L?L.getVideoTracks()[0]??null:null},_=L=>{if(L!==F()&&(se(L),L)){let ye=()=>{F()===L&&se(null)};L.addEventListener("ended",ye)}},B=y.track;B&&B.readyState==="live"&&_(B);let z=y.on("track",L=>{L&&L.readyState!=="live"||_(L)}),ie=setInterval(()=>{let L=y.track;L&&L.readyState==="live"&&_(L)},Or);return()=>{z(),clearInterval(ie)}},[P,n,te,Q,i,se]),$e(()=>{if(Q||!P||s===!1||te)return;let y=Lr(P,Dr(n,"audio",s)),F=()=>{let L=A.current;return L?L.getAudioTracks()[0]??null:null},_=L=>{if(L!==F()&&(Re(L),L)){let ye=()=>{F()===L&&Re(null)};L.addEventListener("ended",ye)}},B=y.track;B&&B.readyState==="live"&&_(B);let z=y.on("track",L=>{L&&L.readyState!=="live"||_(L)}),ie=setInterval(()=>{let L=y.track;L&&L.readyState==="live"&&_(L)},Or);return()=>{z(),clearInterval(ie)}},[P,n,te,s,Q,Re]),Oo("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":M?"true":"false","data-urun-video-framed":x?"true":"false",children:[Vr("video",{ref:ne,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),M?null:v,R===void 0?null:Vr("div",{"data-urun-video-poster":"","aria-hidden":x||void 0,style:{position:"absolute",inset:0,...x?{opacity:0,pointerEvents:"none"}:null},children:R}),h]})});import{jsx as qr,jsxs as Ho}from"react/jsx-runtime";var Fo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},qo=Io(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...f}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=ut(null),v=ut(null),R=ut(0),h=ut(f);h.current=f;let p=Do(()=>Vo(h.current),[]);return Lo(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:p,get lastDrawTs(){return R.current}}),[p]),Fr(()=>{if(!i)return;let b=0,C=0,d=null,k=w=>{typeof w.requestVideoFrameCallback=="function"&&(d=w,C=w.requestVideoFrameCallback(function P(){p.frameArrived(),C=w.requestVideoFrameCallback(P)}))},m=w=>{b=requestAnimationFrame(m);let P=v.current,E=g.current?.element??null;if(!P||!E||(E!==d&&(d&&C&&d.cancelVideoFrameCallback?.(C),k(E)),E.readyState<2))return;p.tick(w);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,M=Math.max(1,Math.round(P.clientWidth*A)),I=Math.max(1,Math.round(P.clientHeight*A));(P.width!==M||P.height!==I)&&(P.width=M,P.height=I);let x=P.getContext("2d");if(!x)return;let O=p.transform(),$=E.videoWidth||M,j=E.videoHeight||I,G=Math.max(M/$,I/j)*(1+a)*O.scale;x.setTransform(G,0,0,G,M/2+O.translateX*M,I/2+O.translateY*I),x.drawImage(E,-$/2,-j/2),R.current=w};return b=requestAnimationFrame(m),()=>{cancelAnimationFrame(b),d&&C&&d.cancelVideoFrameCallback?.(C)}},[i,a,p]),Fr(()=>{if(!i||!c||!l)return;let b=()=>!!l.pointerLockElement,C=P=>{b()&&p.keyDown(P.key)},d=P=>p.keyUp(P.key),k=P=>{b()&&p.pointerDelta(P.movementX,P.movementY)},m=()=>{b()||p.clearKeys()},w=()=>p.clearKeys();return l.addEventListener("keydown",C),l.addEventListener("keyup",d),l.addEventListener("mousemove",k),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",w),()=>{l.removeEventListener("keydown",C),l.removeEventListener("keyup",d),l.removeEventListener("mousemove",k),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",w)}},[i,c,l,p]),i?Ho(We,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[qr("canvas",{ref:v,style:Fo,"data-urun-warp":""}),n]}):qr(We,{ref:g,...s,children:n})});var Hr=new Map;function Wo(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Hr.set(e,{component:t,schema:r})}function Wr(e,t){let r=Hr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as jo,jsx as ct}from"react/jsx-runtime";function Bo({name:e,props:t,fallback:r}){let o=Wr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?ct(jo,{children:r}):ct("div",{className:"urun-component-error",role:"alert",children:ct("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return ct(n,{...o.validatedProps})}import{z as Ge}from"zod";import{jsx as Dt,jsxs as Br}from"react/jsx-runtime";var Ko=Ge.object({step:Ge.number().min(0),total:Ge.number().min(1),label:Ge.string().optional(),variant:Ge.enum(["default","success","error"]).default("default")});function jr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function $o(e){let{step:t,total:r,label:o,variant:n,percentage:s}=jr(e);return Br("div",{className:"urun-progress-card","data-variant":n,children:[o&&Dt("div",{className:"urun-progress-label",children:o}),Dt("div",{className:"urun-progress-bar",children:Dt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Br("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Vt}from"zod";import{jsx as Kr,jsxs as Jo}from"react/jsx-runtime";var Go=Vt.object({state:Vt.enum(["thinking","generating","idle","error"]),message:Vt.string().optional()}),Xo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function $r(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Xo[t]??t;return{state:t,message:n,isActive:o}}function zo(e){let{state:t,message:r,isActive:o}=$r(e);return Jo("span",{className:"urun-status-badge","data-state":t,children:[Kr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Kr("span",{className:"urun-status-message",children:r})]})}import{useRef as Gr,useEffect as Yo}from"react";import{z as Ft}from"zod";import{jsx as Xr,jsxs as es}from"react/jsx-runtime";var Zo=Ft.object({text:Ft.string(),streaming:Ft.boolean().default(!1)});function zr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Qo(e){let{text:t,streaming:r}=zr(e),o=Gr(null),n=Gr(0);return Yo(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),es("div",{className:"urun-text-stream",children:[Xr("span",{ref:o,className:"urun-text-content"}),r&&Xr("span",{className:"urun-text-cursor"})]})}import{z as lt}from"zod";import{jsx as Jr,jsxs as ns}from"react/jsx-runtime";var ts=lt.object({src:lt.string().url(),alt:lt.string().optional(),caption:lt.string().optional()});function Yr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function rs(e){let{src:t,alt:r,caption:o}=Yr(e);return ns("figure",{className:"urun-image-frame",children:[Jr("img",{className:"urun-image",src:t,alt:r}),o&&Jr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as xe}from"zod";import{jsx as qt,jsxs as is}from"react/jsx-runtime";var os=xe.object({metrics:xe.array(xe.object({label:xe.string(),value:xe.union([xe.string(),xe.number()]),unit:xe.string().optional()}))});function Zr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function ss(e){let{metrics:t}=Zr(e);return qt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>is("div",{className:"urun-metric-card",children:[qt("div",{className:"urun-metric-label",children:r.label}),qt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{useCallback as dt,useEffect as Ht,useRef as ce,useState as as}from"react";import{jsx as gs}from"react/jsx-runtime";function we(e){return e&&typeof e=="object"?e:null}function en(e){if(typeof e=="string")return e;let t=we(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function us(e){if(typeof e=="string")return"delta";let t=we(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function cs(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function ls(e){let t=we(e),r=t?.body;return cs(r,we(we(r)?.error)?.message,we(r)?.error,we(r)?.message,we(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var Xe=class extends Error{name="TextStreamError"},ds=4,tn=3,rn=240,Qr=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function nn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function ps(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function on(e){let{session:t,stream:r}=e,o=ce(e);Ht(()=>{o.current=e});let n=ce(null),s=ce(()=>{}),i=ce(null),a=ce(""),c=ce(""),u=ce(null),f=ce(!1),l=ce(!1),g=ce(!1),v=ce(null),R=ce(nn()),h=dt(d=>{if(n.current=d,!d){i.current=null;return}let k=i.current;if(k&&k.parentNode===d)return;let m=d.ownerDocument.createTextNode(c.current);d.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),p=dt(()=>{u.current=null;let d=i.current,k=a.current;if(k.length>0){let A=o.current,M=A.smoothCharsPerFrame??tn,I=A.smoothThreshold??rn,x=A.smooth&&k.length<=I?k.slice(0,M):k;a.current=k.slice(x.length),c.current+=x,d?.appendData(x)}let m=R.current,w=c.current.length,P=v.current===null?0:Math.max(0,Qr()-v.current),E=Math.round(w/ds);if(m.chars=w,m.tokens=E,m.elapsedMs=P,m.tokensPerSecond=P>0?E*1e3/P:0,a.current.length>0){b(),o.current.onMeter?.(m);return}if(!f.current&&!g.current){g.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(m)},[]),b=dt(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>p()))},[p]);s.current=b,Ht(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,v.current=null,f.current=!0,ps(R.current),i.current&&(i.current.data="");let d=!1,k=null;return(async()=>{try{for(k=t.stream(r).messages()[Symbol.asyncIterator]();;){let w=await k.next();if(d)return;if(w.done)break;let P=w.value,E=us(P);if(E==="error")throw new Xe(ls(P));if(E==="done")break;if(E==="ignore")continue;let A=en(P);A&&(v.current===null&&(v.current=Qr()),a.current+=A,b())}if(d)return;k.return?.(void 0),f.current=!1,b()}catch(m){if(d)return;k?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(m instanceof Error?m:new Xe(String(m))),b()}})(),()=>{d=!0,f.current=!1,k?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,b]);let C=dt(()=>c.current,[]);return{ref:h,meterRef:R,getText:C}}function ms(e,t=250){let[r,o]=as(nn);return Ht(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function fs(e){let{className:t,style:r,...o}=e,{ref:n}=on(o);return gs("span",{ref:n,className:t,style:r})}import{forwardRef as Ss}from"react";import{jsx as vs}from"react/jsx-runtime";var hs=Ss(function(t,r){let{stream:o="image",...n}=t;return vs(We,{ref:r,stream:o,...n})});import{forwardRef as ys,useCallback as he,useEffect as Wt,useImperativeHandle as bs,useRef as de}from"react";import{observePageLifecycle as ks}from"@urun-sh/core";import{jsx as Es}from"react/jsx-runtime";var Ts=1e3;function Rs(e){return e!==null&&jt.has(e)}var jt=new WeakSet,Cs=1e3;function Bt(...e){console.debug("[audio]",...e)}var pt=ys(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f,directOut:l}=t,g=Se(),v=o??g,R=de(null),h=de(null),p=de(null),b=de(null),C=de(null),d=de(0),k=de(!1),m=de(c);m.current=c;let w=de(u);w.current=u;let P=de(l);P.current=l;let E=he(T=>{p.current!==T&&(p.current=T,w.current?.(T))},[]),A=he(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let T=R.current;return T&&T.srcObject!==h.current&&h.current.getAudioTracks().length>0&&(T.srcObject=h.current),h.current},[]),M=he(()=>{d.current=0,C.current!==null&&cancelAnimationFrame(C.current),C.current=null,b.current!==null&&clearTimeout(b.current),b.current=null},[]),I=he(T=>{C.current=null,b.current=null,A(),R.current&&(R.current.muted=k.current),$.current(`${T}:retry`)},[A]),x=he(T=>{if(!R.current||C.current!==null||b.current!==null)return;let S=h.current;if(!(!!S&&S.getAudioTracks().some(V=>V.readyState==="live"))){M();return}let D=d.current;if(d.current=D+1,D===0&&typeof requestAnimationFrame=="function"){C.current=requestAnimationFrame(()=>I(T));return}b.current=setTimeout(()=>I(T),Cs)},[M,I]),O=he(T=>{let q=R.current;if(!q)return;let S=q.play();!S||typeof S.then!="function"||S.then(()=>{q.muted=k.current,q.muted||E(!0),M()}).catch(N=>{let D=N instanceof Error?N.name:String(N);if(D==="AbortError"){Bt(`play() aborted (${T}); retrying on the ladder`),x(`${T}:abort`);return}if(D==="NotAllowedError"){Bt(`play() blocked pending a user gesture (${T})`),E(!1),x(`${T}:blocked`);return}Bt(`play() failed (${T})`,N)})},[E]),$=de(()=>{});$.current=O;let j=he(T=>{let q=A();if(!q)return;for(let N of q.getAudioTracks())N!==T&&q.removeTrack(N);T&&!q.getAudioTracks().includes(T)&&q.addTrack(T),A();let S=P.current??Rs(T);k.current=!!T&&S,R.current&&(R.current.muted=k.current),T&&O("track-attach"),m.current?.(T)},[A,O]),K=he(()=>{let T=R.current;T&&(A(),T.muted=k.current,O("gesture"),He(),E(!0))},[A,O,E]);bs(r,()=>({unlock:K,get unlocked(){return p.current===!0},get element(){return R.current}}),[K]);let G=he(()=>{x("pause-event")},[x]),J=he(T=>{let q=R.current;q&&q!==T&&q.removeEventListener("pause",G),R.current=T,T&&(T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),A(),T.addEventListener("pause",G)),f?.(T)},[A,f,G]),X=s!==void 0;return Wt(()=>{if(X){j(s??null);return}if(!v)return;let T=v.stream(n);if(T.directOut){let U=T.track;U&&jt.add(U)}let q=()=>{let U=h.current;return U?U.getAudioTracks()[0]??null:null},S=U=>{if(U!==q()&&(T.directOut&&U&&jt.add(U),j(U),U)){let Y=()=>{q()===U&&j(null)};U.addEventListener("ended",Y)}},N=T.track;N&&N.readyState==="live"&&S(N);let D=T.on("track",U=>{U&&U.readyState!=="live"||S(U)}),V=setInterval(()=>{let U=T.track;U&&U.readyState==="live"&&S(U)},Ts);return()=>{D(),clearInterval(V)}},[v,n,X,s,j]),Wt(()=>ks(()=>{He(),p.current===!0&&O("foreground")}),[O]),Wt(()=>()=>{b.current&&clearTimeout(b.current),C.current!==null&&cancelAnimationFrame(C.current),C.current=null},[]),Es("audio",{ref:J,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Ps=pt;import{forwardRef as xs,useCallback as _e,useEffect as Kt,useImperativeHandle as ws,useRef as pe}from"react";import{observePageLifecycle as Us,SessionFailedError as As,sessionFailureFromMediaError as Ms,sharedCaptureController as _s}from"@urun-sh/core";import{jsx as Is}from"react/jsx-runtime";var sn={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function mt(...e){console.debug("[voice]",...e)}function Ns(e){return e instanceof As&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var ft=xs(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=sn,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:R,onUnlockChange:h,capture:p,directOut:b}=t,C=Se(),d=o??C,k=pe(null),m=pe(null),w=pe(null),P=pe([]),E=pe(!1),A=pe(l);A.current=l;let M=pe(g);M.current=g;let I=pe(v);I.current=v;let x=_e(S=>{E.current!==S&&(E.current=S,A.current?.(S))},[]),O=_e(()=>{for(let S of P.current)S();P.current=[],w.current?.release(),w.current=null,m.current&&(m.current=null,I.current?.(null))},[]),$=_e(async()=>{let S=w.current;if(S){let U=await S.update(a);return m.current=S.stream,I.current?.(S.stream),U}let D=await(p??_s()).claim("audio",a);w.current=D,P.current=[D.onTrack((U,Y)=>{m.current=Y,I.current?.(Y),E.current&&d?.stream(n).attach(U).catch(Z=>mt("mic re-attach after one-capture re-acquire failed",Z))}),D.onLost(U=>{w.current=null,P.current=[],m.current=null,I.current?.(null),x(!1),M.current?.(U)})],m.current=D.stream,I.current?.(D.stream);let V=D.track;if(!V)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return V},[p,a,d,n,x]),j=_e(async()=>{O(),x(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,O,x]),K=_e(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");k.current?.unlock();let S;try{S=await $()}catch(V){O();let U=Ms(V,d.status);throw M.current?.(U),U}let N;for(let V=1;V<=u;V++)try{await d.whenLive(c!==void 0?{timeout:c}:void 0),await d.stream(n).attach(S),x(!0);return}catch(U){if(N=U,mt(`start attempt ${V}/${u} failed`,U),Ns(U))break;d.connect?.(),V<u&&await new Promise(Y=>setTimeout(Y,f))}O(),x(!1);let D=N instanceof Error?N:new Error(String(N??"voice start failed"));throw M.current?.(D),D},[d,n,c,u,f,$,O,x]);ws(r,()=>({start:K,stop:j,unlock:()=>k.current?.unlock(),get active(){return E.current},get micStream(){return m.current},get audio(){return k.current}}),[K,j]);let G=pe(K);G.current=K;let J=pe(null),X=_e((S,N)=>{S.promise.then(()=>{N&&(O(),x(!1)),S.session.stream(S.streamName).detach().catch(()=>{})})},[O,x]);Kt(()=>{if(!i||!d)return;let S=J.current;S&&(S.session!==d||S.streamName!==n)&&(S.disposeTimer&&clearTimeout(S.disposeTimer),X(S,!1),S=null),S?S.disposeTimer&&(clearTimeout(S.disposeTimer),S.disposeTimer=null):(S={session:d,streamName:n,promise:G.current().catch(()=>{}),refCount:0,disposeTimer:null},J.current=S),S.refCount+=1;let N=S;return()=>{N.refCount-=1,!(N.refCount>0)&&(N.disposeTimer=setTimeout(()=>{J.current===N&&(J.current=null),X(N,!0)},0))}},[i,d,n,X]);let T=pe(!1),q=_e(async()=>{if(!d||!E.current||T.current)return;let S=m.current?.getAudioTracks()[0]??null;if(S&&S.readyState==="live"){try{await d.stream(n).attach(S)}catch(N){mt("foreground mic re-assert failed (will retry on next pass)",N)}return}T.current=!0;try{let N=await $();await d.stream(n).attach(N)}catch(N){let D=N instanceof Error?N:new Error(String(N));mt("foreground mic re-acquire failed",D),M.current?.(D)}finally{T.current=!1}},[d,n,$]);return Kt(()=>{let S=()=>{q()};return d&&typeof d.onRecovery=="function"?d.onRecovery(S):Us(S)},[d,q]),Kt(()=>O,[O]),s?Is(pt,{ref:k,session:d,stream:n,onTrack:R,onUnlockChange:h,directOut:b}):null}),Os=ft;import{forwardRef as Vs,useImperativeHandle as Fs,useRef as an,useState as qs}from"react";import{useEffect as Ls,useState as Ds}from"react";var $t={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Ds($t);return Ls(()=>{if(!e){i($t);return}let a=at();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,f;try{u=a.createMediaStreamSource(c),f=a.createAnalyser(),f.fftSize=r,u.connect(f)}catch{return}let l=new Uint8Array(f.fftSize),v=setInterval(()=>{f.getByteTimeDomainData(l);let R=0;for(let p=0;p<l.length;p++){let b=(l[p]-128)/128;R+=b*b}let h=Math.sqrt(R/l.length);i(p=>{let b=h>n;return Math.abs(p.level-h)<.005&&p.speaking===b?p:{level:h,speaking:b}})},o);return()=>{clearInterval(v),u.disconnect(),i($t)}},[e,r,o,n]),s}import{Fragment as js,jsx as gt,jsxs as Ks}from"react/jsx-runtime";var Hs={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Ws={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Bs=Vs(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:f,onMicStream:l,capture:g}=t,v=Se(),R=o??v,h=an(null),[p,b]=qs(null),C=an(l);C.current=l;let{level:d,speaking:k}=Gt(a?p:null);return Fs(r,()=>({start:()=>{let m=h.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>h.current?.stop()??Promise.resolve(),get active(){return h.current?.active??!1},get micStream(){return h.current?.micStream??null}}),[]),Ks(js,{children:[gt(ft,{ref:h,session:R,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:m=>{b(m),C.current?.(m)}}),a?gt("span",{className:c,style:Hs,"data-urun-mic":"","data-urun-mic-active":p?"true":"false","data-urun-mic-speaking":k?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(d*100)/100,children:gt("span",{style:Ws,children:gt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(d*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as $s,sessionFailureFromMediaError as Gs,sharedCaptureController as Xs}from"@urun-sh/core";import{forwardRef as cn,useCallback as ve,useEffect as Xt,useImperativeHandle as zs,useRef as re,useState as ze}from"react";import{jsx as Ue,jsxs as un}from"react/jsx-runtime";var ln={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function zt(...e){console.debug("[camera]",...e)}function Js(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Ys(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var dn=cn(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:f="auto",connectTimeoutMs:l,visible:g=!1,className:v,videoClassName:R,onActiveChange:h,onError:p,onStream:b,onTrack:C,children:d,capture:k,flipControl:m="auto",flipControlClassName:w,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let E=i?"user":a?"environment":c??"environment",A=Se(),M=o??A,I=re(null),x=re(null),O=re(null),$=re([]),j=re(null),K=re(!1),G=re(!1),J=re(E),[X,T]=ze(E),[q,S]=ze(!1),[N,D]=ze(null),[V,U]=ze(!1),[Y]=ze(Js),Z=re(h);Z.current=h;let ee=re(p);ee.current=p;let fe=re(b);fe.current=b;let se=re(C);se.current=C;let Re=re(P);Re.current=P;let ne=ve(H=>{K.current!==H&&(K.current=H,S(H),Z.current?.(H))},[]);Xt(()=>{if(!q){D(null);return}let H=!1,W=()=>{Ys().then(ue=>{H||(D(ue),ue&&Re.current?.(ue))})};W();let ae=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ae?.addEventListener=="function"?(ae.addEventListener("devicechange",W),()=>{H=!0,ae.removeEventListener?.("devicechange",W)}):()=>{H=!0}},[q]);let te=ve(H=>{let W=I.current;W&&(W.muted=!0,W.defaultMuted=!0,W.setAttribute("muted",""),W.setAttribute("playsinline",""),W.setAttribute("webkit-playsinline",""),W.srcObject=H,H&&W.play()?.catch?.(ae=>zt("preview play() failed",ae)))},[]),Q=ve(()=>{G.current=!1,j.current?.(),j.current=null;for(let H of $.current)H();$.current=[],O.current?.release(),O.current=null,x.current&&(x.current=null,fe.current?.(null),se.current?.(null)),te(null)},[te]),y=ve((H,W)=>{j.current?.(),x.current=W,te(W),fe.current?.(W);let ae=()=>{x.current===W&&(zt("camera track ended (device removed or permission revoked)"),Q(),ne(!1))};H.addEventListener("ended",ae),j.current=()=>H.removeEventListener("ended",ae)},[te,Q,ne]),F=ve(async H=>{let W=n!==!1;if(W&&!M)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ae={...ln,...s,facingMode:H},ue;try{let le=O.current;if(le)ue=await le.update(ae);else{let Be=await(k??Xs()).claim("video",ae);if(O.current=Be,$.current=[Be.onTrack((je,xn)=>{y(je,xn),K.current&&(!W||!M||M.stream(n).attachVideo(je).then(()=>se.current?.(je)).catch(wn=>zt("camera re-publish after one-capture re-acquire failed",wn)))}),Be.onLost(je=>{O.current=null,$.current=[],Q(),ne(!1),ee.current?.(je)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ue=Be.track}}catch(le){let De=Gs(le,M?.status);throw ee.current?.(De),De}J.current=H,T(H),y(ue,O.current?.stream??new MediaStream([ue]));try{W&&M&&(M.connect?.(),await M.whenLive(l!==void 0?{timeout:l}:void 0),await M.stream(n).attachVideo(ue)),G.current=W?n:!1}catch(le){Q(),ne(!1);let De=le instanceof Error?le:new Error(String(le));throw ee.current?.(De),De}se.current?.(ue),ne(!0)},[M,n,s,l,k,y,Q,ne]),_=ve(H=>F(H?.facingMode??J.current),[F]),B=ve(async H=>{let W=G.current===n;K.current&&J.current===H&&W||await F(H)},[F,n]),z=ve(()=>F(J.current==="environment"?"user":"environment"),[F]),ie=ve(async()=>{Q(),ne(!1),n!==!1&&await M?.stream(n).detachVideo().catch(()=>{})},[M,n,Q,ne]),L=ve(async H=>{let W=I.current;if(!W)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await $s(W,H)},[]);zs(r,()=>({start:_,stop:ie,flip:z,setFacingMode:B,capturePhoto:L,get active(){return K.current},get facingMode(){return J.current},get stream(){return x.current},get element(){return I.current}}),[_,ie,z,B,L]);let ye=re(B);if(ye.current=B,Xt(()=>{u&&(n!==!1&&!M||ye.current(E).catch(()=>{}))},[u,M,E,n]),Xt(()=>Q,[Q]),!g)return null;let Le=f==="auto"?X==="user":f,be=q&&(m===!0||m==="auto"&&Y&&(N?.length??0)>1),ke=()=>{V||(U(!0),z().catch(()=>{}).finally(()=>U(!1)))};return un("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":X,children:[Ue("video",{ref:I,className:R,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Le?{transform:"scaleX(-1)"}:{}}}),be?Ue("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:ke,disabled:V,className:w,style:w?{opacity:V?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:V?.6:1},children:un("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[Ue("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),Ue("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),Ue("path",{d:"M14.5 10.5v1.6h-1.6"}),Ue("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),Ue("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,d]})}),Zs=cn(function({preview:t=!0,...r},o){return Ue(dn,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Qs,normalizeReferenceImage as ei,referenceImageErrorMessage as ti}from"@urun-sh/core";import{useCallback as Je,useEffect as ri,useRef as Jt,useState as Ye}from"react";function ni(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=Ye(null),[a,c]=Ye(null),[u,f]=Ye(!1),[l,g]=Ye(null),[v]=Ye(Qs),R=Jt(n);R.current=n;let h=Jt(null),p=Jt(0),b=Je(w=>{h.current&&URL.revokeObjectURL(h.current),h.current=w?URL.createObjectURL(new Blob([w.bytes],{type:w.type})):null,c(h.current),i(w),R.current?.(w)},[]);ri(()=>()=>{p.current++,h.current&&URL.revokeObjectURL(h.current),h.current=null},[]);let C=Je(async w=>{let P=++p.current;f(!0),g(null);try{let E=await w();if(p.current!==P)return;b(E)}catch(E){if(p.current!==P)return;g(ti(E))}finally{p.current===P&&f(!1)}},[b]),d=Je(w=>C(()=>ei(w,{maxSize:t,type:r,quality:o,source:"file"})),[C,t,r,o]),k=Je(w=>C(()=>w.capturePhoto({maxSize:t,type:r,quality:o})),[C,t,r,o]),m=Je(()=>{p.current++,g(null),f(!1),b(null)},[b]);return{reference:s,previewUrl:a,pick:d,capture:k,clear:m,busy:u,error:l,cameraAvailable:v}}import{useEffect as oi,useState as si}from"react";function ii(e,t){let[r,o]=si(null);return oi(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as pi}from"react";import{useEffect as li,useMemo as di}from"react";import{createStore as ai}from"zustand/vanilla";import{useStore as ui}from"zustand";var ci=()=>{};function Yt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=ai(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):ci,c=(u=>ui(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function Ze(e,t){let r=di(()=>Yt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return li(()=>r.bind(),[r]),r}function mi(e,t,r){let n=Ze(e,t)(r??(a=>a)),s=pi(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as fi,useState as gi}from"react";function Si(e){let[t,r]=gi(null);return fi(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}import{useEffect as hi,useState as vi}from"react";var Ne=200;function Ae(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Qe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Zt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Qt(e,t,r={}){let o=r.cap??200,[n,s]=vi([]);return hi(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>Ae(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as St,jsxs as et}from"react/jsx-runtime";function yi({session:e,name:t,cap:r,className:o}){let n=Qt(e,t,{cap:r});return et("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[et("div",{className:"urun-stream-tail-meta",children:[St("code",{children:t}),et("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),St("div",{className:"urun-stream-tail-log",children:n.length===0?et("span",{className:"urun-stream-tail-empty",children:["Waiting for ",St("code",{children:t})," messages\u2026"]}):n.map((s,i)=>et("div",{className:"urun-stream-tail-line",children:[St("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Qe(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as bi,useState as pn}from"react";import{jsx as Oe,jsxs as ht}from"react/jsx-runtime";function vt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=pn(""),[i,a]=pn(null),c=bi(()=>{let u=Zt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return ht("div",{className:"urun-doc-patch",children:[Oe("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),ht("div",{className:"urun-doc-patch-actions",children:[Oe("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?Oe("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function ki({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ze(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return ht("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[ht("div",{className:"urun-doc-panel-meta",children:[Oe("code",{children:t}),Oe("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),Oe("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?Oe(vt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}import{useEffect as Ti,useState as Ri}from"react";import{jsx as tt,jsxs as fn}from"react/jsx-runtime";function mn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Ci({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=Ri([]);return Ti(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ae(c,{at:Date.now(),direction:"in",text:mn(Qe(a))},r))}):void 0),[e,t,r]),fn("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[tt(vt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>Ae(c,{at:Date.now(),direction:"out",text:mn(a)},r))}}),tt("div",{className:"urun-control-sender-log",children:n.length===0?tt("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>fn("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[tt("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",tt("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as Pi,useState as Ei}from"react";import{jsx as yt,jsxs as wi}from"react/jsx-runtime";function xi({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=Ei([]),a=t.join(","),c=r.join(",");return Pi(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>Ae(v,{at:Date.now(),kind:l,text:g},o)),f=[];f.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);f.push(g.on("track",v=>u("track",`${l}: ${v?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);f.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>f.forEach(l=>l())},[e,a,c,o]),yt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?yt("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,f)=>wi("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[yt("span",{className:"urun-event-spine-kind",children:u.kind})," ",yt("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${f}`))})}import{describeSessionPhase as Bi,isWakingPhase as ji}from"@urun-sh/core";import{useEffect as Ui,useState as Ai}from"react";function me(e){let[t,r]=Ai(e?.phase??null);return Ui(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as Ii}from"@urun-sh/core";import{useEffect as Mi,useRef as _i,useState as Ni}from"react";import{isWakingPhase as Oi}from"@urun-sh/core";function er(e){let t=me(e),r=Oi(t?.name),o=_i(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=Ni(s);return Mi(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as Li,jsx as gn,jsxs as Sn}from"react/jsx-runtime";function tr({session:e,render:t,className:r}){let o=er(e);return!o.waking||!o.phase?null:gn("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Sn(Li,{children:[gn("span",{className:"urun-session-waking-label",children:Ii(o.phase)})," ",Sn("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Fi,useState as qi}from"react";import{useEffect as hn,useRef as Di,useState as vn}from"react";var Vi={event:null,elapsedMs:0};function rr(e,t){let[r,o]=vn(null),n=Di(0);hn(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=vn(0);return hn(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:Vi}import{jsx as yn,jsxs as bn}from"react/jsx-runtime";var Hi={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function Wi(e){let[t,r]=qi(!1);return Fi(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function nr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=rr(e,t),i=Wi(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return yn("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):bn("div",{className:"urun-activation-overlay-card",children:[yn("span",{className:"urun-activation-overlay-copy",children:a.hint??Hi[c]})," ",bn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ie,jsxs as or}from"react/jsx-runtime";var Ki={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function $i({session:e,className:t}){let r=me(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return or("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ie("span",{className:"urun-session-status-dot","data-phase":o}),Ie("span",{className:"urun-session-status-label",children:Ki[o]}),n?Ie("span",{className:"urun-session-status-detail",children:n}):null]})}function Gi({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=me(e);if(s?.name==="live")return or("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ie(nr,{session:e})]});let i=r?r(s):Ie("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&ji(s.name)?Ie(tr,{session:e}):s&&s.name!=="idle"?Bi(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return or("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ie("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Xi,useState as zi}from"react";import{jsx as Zi}from"react/jsx-runtime";function kn(e){return me(e)?.endsAt??null}function Ji(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Yi({session:e,urgentMs:t=6e4,className:r}){let n=kn(e)?.getTime()??null,[s,i]=zi(()=>n===null?null:Math.max(0,n-Date.now()));if(Xi(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=Ji(s);return Zi("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{describeSessionPhase as Qi}from"@urun-sh/core";import{jsx as sr,jsxs as ra}from"react/jsx-runtime";var ea=new Set(["paused","error"]);function Tn({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=me(e);if(!s||!ea.has(s.name))return null;let i=o?o(s):sr("span",{className:"urun-session-paused-copy",children:Qi(s)});return ra("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?sr("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?sr("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var ta=Tn;import{useEffect as Rn,useMemo as na,useState as Cn}from"react";import{jsx as bt,jsxs as ia}from"react/jsx-runtime";function ir(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Pn(e){let t=na(()=>e?e.doc("control"):null,[e]),[r,o]=Cn(()=>t?ir(t.get("idle")):null);return Rn(()=>{if(!t){o(null);return}return o(ir(t.get("idle"))),t.on("change",()=>o(ir(t.get("idle"))))},[t]),r}function oa(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function sa({session:e,onStillHere:t,className:r}){let o=Pn(e),n=o?.deadlineEpochS??null,[s,i]=Cn(null);if(Rn(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return bt("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:ia("div",{className:"urun-idle-warning-card",children:[bt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),bt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${oa(s)} due to inactivity.`:"This session will end soon due to inactivity."}),bt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useCallback as En,useEffect as aa,useRef as ua,useState as ar}from"react";function ca(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function ur(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=ar(null),[s,i]=ar(e!==null),[a,c]=ar(null),u=ua(e),f=En(async g=>{i(!0);try{let v=await g.getBalance();if(u.current!==g)return;n(v),c(null)}catch(v){if(u.current!==g)return;c(v instanceof Error?v:new Error(String(v)))}finally{u.current===g&&i(!1)}},[]);aa(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(f(e),r!==void 0&&r>0){let g=setInterval(()=>{f(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,f]);let l=En(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:ca(o),loading:s,error:a,refresh:l}}import{jsx as cr}from"react/jsx-runtime";function la({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=ur(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return cr("div",{className:i,children:t});let a=r?r(n):cr("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return cr("div",{className:i,children:a})}import{CreditsClient as zd,createCreditsClient as Jd,CreditsError as Yd,CreditsUnauthorizedError as Zd}from"@urun-sh/core";import{useContext as da,useEffect as pa,useState as ma}from"react";import{prewake as fa}from"@urun-sh/core";function ga(e){let t=da(Ce),[r,o]=ma(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,f=t?.getAccessToken,l=t?.authProvider;return pa(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{fa({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(h=>{g||o(h)}).catch(()=>{})};v();let R=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(R)}},[n,s,i,a,c,u,f,l]),r}import{useEffect as Sa,useState as ha}from"react";function va(e){let[t,r]=ha(null);return Sa(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as ip,isWakingPhase as ap}from"@urun-sh/core";export{pt as Audio,dn as Camera,Bo as ComponentRenderer,zd as CreditsClient,Yd as CreditsError,Zd as CreditsUnauthorizedError,ln as DEFAULT_CAMERA_CONSTRAINTS,Ne as DEFAULT_LOG_CAP,tn as DEFAULT_SMOOTH_CHARS_PER_FRAME,rn as DEFAULT_SMOOTH_THRESHOLD,sn as DEFAULT_VOICE_CONSTRAINTS,vt as DocPatchForm,hs as Image,rs as ImageFrame,ts as ImageFrameSchema,ss as MetricsPanel,os as MetricsPanelSchema,Bs as Mic,Dn as OPERATOR_CHORD_LABEL,Ln as OPERATOR_TOKEN_STORAGE_KEY,$o as ProgressCard,Ko as ProgressCardSchema,qo as ReprojectedVideo,xo as Session,zo as StatusBadge,Go as StatusBadgeSchema,fs as Text,Qo as TextStream,Xe as TextStreamError,Zo as TextStreamSchema,nr as UrunActivationOverlay,Ps as UrunAudio,kt as UrunAuthProvider,Zs as UrunCamera,Ci as UrunControlSender,la as UrunCreditsGate,ki as UrunDocPanel,Ke as UrunErrorBoundary,xi as UrunEventSpine,sa as UrunIdleWarning,Un as UrunJwtProvider,Xn as UrunProvider,Yi as UrunSessionClock,ta as UrunSessionEnded,Gi as UrunSessionGate,Tn as UrunSessionPaused,$i as UrunSessionStatus,tr as UrunSessionWaking,yi as UrunStreamTail,Os as UrunVoice,We as Video,ft as Voice,rt as authMode,Jd as createCreditsClient,Yt as createDocStore,ip as describeSessionPhase,Qe as formatPayload,at as getUrunAudioContext,ap as isWakingPhase,Zt as parseJsonObject,Ae as pushCapped,fr as readOperatorToken,Wo as registerComponent,He as resumeUrunAudioContext,en as textDelta,ge as urunPublicEnv,rr as useActivation,ro as useApp,yo as useChat,go as useCompletion,Ct as useConfirmOnLeave,ur as useCredits,Ze as useDocStore,Si as useGenerationTick,Yr as useImageFrame,Co as useInputPresence,Zr as useMetricsPanel,Rt as useOperatorOverride,jr as useProgressCard,ni as useReferenceImage,lo as useRequest,wo as useSession,io as useSessionDirectory,mi as useSessionDoc,kn as useSessionEndsAt,Pn as useSessionIdle,me as useSessionPhase,va as useSessionStats,ii as useSessionTrack,er as useSessionWake,$r as useStatusBadge,Qt as useStreamMessages,on as useText,ms as useTextMeter,zr as useTextStream,Gt as useUrunAudioLevel,Tt as useUrunAuth,ga as useUrunPrewake,Nn as usesWorkOSAuth};
|