@urun-sh/react 0.2.21 → 0.2.23

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.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as react from 'react';
3
- import { RefObject, ReactNode, Component, ErrorInfo, ComponentType } from 'react';
3
+ import { RefObject, ReactNode, Component, ErrorInfo, ComponentType, CSSProperties } from 'react';
4
4
  import { SessionInterface, SessionDocument, SessionStream, SessionPhase, SessionStatus, SessionDiagnostic, CaptureController, ActivationEvent, PrewakeResult, RuntimeAvailability } from '@urun-sh/core';
5
5
  export { ActivationEvent, ActivationState, App as AppInterface, AppOptions, PrewakeResult, PrewakeStatus, RuntimeAvailability, SessionDocument, Session as SessionInterface, SessionPhase, SessionPhaseName, SessionStream, describeSessionPhase, isWakingPhase } from '@urun-sh/core';
6
6
  import { ZodSchema, z } from 'zod';
@@ -375,18 +375,114 @@ declare function useMetricsPanel(props: MetricsPanelProps): {
375
375
  };
376
376
  declare function MetricsPanel(props: MetricsPanelProps): react_jsx_runtime.JSX.Element;
377
377
 
378
- interface UrunAudioStreamSource {
378
+ interface ScopedStreamSource {
379
+
380
+ readonly track: MediaStreamTrack | null;
381
+
382
+ on(event: 'track', handler: (track: MediaStreamTrack | null) => void): () => void;
383
+
384
+ attach(track: MediaStreamTrack): Promise<void>;
385
+
386
+ detach(): Promise<void>;
387
+
388
+ attachVideo(track: MediaStreamTrack): Promise<void>;
389
+
390
+ detachVideo(): Promise<void>;
391
+ }
392
+
393
+ interface ScopedSession {
394
+
395
+ stream(name: string): ScopedStreamSource;
396
+
397
+ whenLive(options?: {
398
+ timeout?: number;
399
+ signal?: AbortSignal;
400
+ }): Promise<void>;
401
+
402
+ readonly status?: SessionStatus;
403
+
404
+ onRecovery?(hook: () => void): () => void;
405
+ }
406
+
407
+ interface SessionScopeProps {
408
+
409
+ session: ScopedSession | null;
410
+ children: ReactNode;
411
+ }
412
+
413
+ declare function SessionScope({ session, children }: SessionScopeProps): react_jsx_runtime.JSX.Element;
414
+
415
+ interface VideoStreamSource {
416
+
417
+ readonly track: MediaStreamTrack | null;
418
+
419
+ on(event: 'track', handler: (track: MediaStreamTrack | null) => void): () => void;
420
+ }
421
+
422
+ interface VideoSessionSource {
423
+ stream(name: string): VideoStreamSource;
424
+ }
425
+
426
+ interface VideoHandle {
427
+
428
+ readonly element: HTMLVideoElement | null;
429
+
430
+ readonly live: boolean;
431
+ }
432
+
433
+ interface VideoProps {
434
+
435
+ session?: VideoSessionSource | null;
436
+
437
+ stream?: string;
438
+
439
+ track?: MediaStreamTrack | null;
440
+
441
+ muted?: boolean;
442
+
443
+ mirror?: boolean;
444
+
445
+ objectFit?: CSSProperties['objectFit'];
446
+
447
+ className?: string;
448
+
449
+ style?: CSSProperties;
450
+
451
+ videoClassName?: string;
452
+
453
+ placeholder?: ReactNode;
454
+
455
+ children?: ReactNode;
456
+
457
+ onTrack?: (track: MediaStreamTrack | null) => void;
458
+ }
459
+
460
+ declare const Video: react.ForwardRefExoticComponent<VideoProps & react.RefAttributes<VideoHandle>>;
461
+
462
+ type ImageProps = Omit<VideoProps, 'muted' | 'mirror' | 'stream'> & {
463
+
464
+ stream?: string;
465
+ };
466
+
467
+ type ImageHandle = VideoHandle;
468
+
469
+ declare const Image: react.ForwardRefExoticComponent<Omit<VideoProps, "stream" | "muted" | "mirror"> & {
470
+
471
+ stream?: string;
472
+ } & react.RefAttributes<VideoHandle>>;
473
+
474
+ interface AudioStreamSource {
379
475
 
380
476
  readonly track: MediaStreamTrack | null;
381
477
 
382
478
  on(event: 'track', handler: (track: MediaStreamTrack | null) => void): () => void;
383
479
  }
384
480
 
385
- interface UrunAudioSessionSource {
386
- stream(name: string): UrunAudioStreamSource;
481
+ interface AudioSessionSource {
482
+ stream(name: string): AudioStreamSource;
387
483
  }
388
484
 
389
- interface UrunAudioHandle {
485
+ interface AudioHandle {
390
486
 
391
487
  unlock(): void;
392
488
 
@@ -395,9 +491,9 @@ interface UrunAudioHandle {
395
491
  readonly element: HTMLAudioElement | null;
396
492
  }
397
493
 
398
- interface UrunAudioProps {
494
+ interface AudioProps {
399
495
 
400
- session?: UrunAudioSessionSource | null;
496
+ session?: AudioSessionSource | null;
401
497
 
402
498
  stream?: string;
403
499
 
@@ -414,15 +510,25 @@ interface UrunAudioProps {
414
510
  onAudioElement?: (el: HTMLAudioElement | null) => void;
415
511
  }
416
512
 
417
- declare const UrunAudio: react.ForwardRefExoticComponent<UrunAudioProps & react.RefAttributes<UrunAudioHandle>>;
513
+ declare const Audio: react.ForwardRefExoticComponent<AudioProps & react.RefAttributes<AudioHandle>>;
514
+
515
+ declare const UrunAudio: react.ForwardRefExoticComponent<AudioProps & react.RefAttributes<AudioHandle>>;
516
+
517
+ type UrunAudioProps = AudioProps;
518
+
519
+ type UrunAudioHandle = AudioHandle;
418
520
 
419
- interface UrunVoiceStreamSource extends UrunAudioStreamSource {
521
+ type UrunAudioStreamSource = AudioStreamSource;
522
+
523
+ type UrunAudioSessionSource = AudioSessionSource;
524
+
525
+ interface VoiceStreamSource extends AudioStreamSource {
420
526
  attach(track: MediaStreamTrack): Promise<void>;
421
527
  detach(): Promise<void>;
422
528
  }
423
529
 
424
- interface UrunVoiceSessionSource {
425
- stream(name: string): UrunVoiceStreamSource;
530
+ interface VoiceSessionSource {
531
+ stream(name: string): VoiceStreamSource;
426
532
 
427
533
  whenLive(options?: {
428
534
  timeout?: number;
@@ -434,7 +540,7 @@ interface UrunVoiceSessionSource {
434
540
  onRecovery?(hook: () => void): () => void;
435
541
  }
436
542
 
437
- interface UrunVoiceHandle {
543
+ interface VoiceHandle {
438
544
 
439
545
  start(): Promise<void>;
440
546
 
@@ -446,15 +552,17 @@ interface UrunVoiceHandle {
446
552
 
447
553
  unlock(): void;
448
554
 
449
- readonly audio: UrunAudioHandle | null;
555
+ readonly audio: AudioHandle | null;
450
556
  }
451
557
 
452
- interface UrunVoiceProps {
558
+ interface VoiceProps {
453
559
 
454
- session: UrunVoiceSessionSource;
560
+ session?: VoiceSessionSource | null;
455
561
 
456
562
  stream?: string;
457
563
 
564
+ playback?: boolean;
565
+
458
566
  constraints?: MediaTrackConstraints;
459
567
 
460
568
  connectTimeoutMs?: number;
@@ -478,15 +586,61 @@ interface UrunVoiceProps {
478
586
 
479
587
  declare const DEFAULT_VOICE_CONSTRAINTS: MediaTrackConstraints;
480
588
 
481
- declare const UrunVoice: react.ForwardRefExoticComponent<UrunVoiceProps & react.RefAttributes<UrunVoiceHandle>>;
589
+ declare const Voice: react.ForwardRefExoticComponent<VoiceProps & react.RefAttributes<VoiceHandle>>;
590
+
591
+ declare const UrunVoice: react.ForwardRefExoticComponent<VoiceProps & react.RefAttributes<VoiceHandle>>;
592
+
593
+ type UrunVoiceProps = VoiceProps;
594
+
595
+ type UrunVoiceHandle = VoiceHandle;
596
+
597
+ type UrunVoiceStreamSource = VoiceStreamSource;
598
+
599
+ type UrunVoiceSessionSource = VoiceSessionSource;
600
+
601
+ interface MicHandle {
602
+
603
+ start(): Promise<void>;
604
+
605
+ stop(): Promise<void>;
606
+
607
+ readonly active: boolean;
608
+
609
+ readonly micStream: MediaStream | null;
610
+ }
611
+
612
+ interface MicProps {
613
+
614
+ session?: VoiceSessionSource | null;
615
+
616
+ stream?: string;
617
+
618
+ constraints?: MediaTrackConstraints;
619
+
620
+ autoStart?: boolean;
621
+
622
+ visible?: boolean;
623
+
624
+ className?: string;
625
+
626
+ onActiveChange?: (active: boolean) => void;
627
+
628
+ onError?: (error: Error) => void;
629
+
630
+ onMicStream?: (stream: MediaStream | null) => void;
631
+
632
+ capture?: CaptureController;
633
+ }
634
+
635
+ declare const Mic: react.ForwardRefExoticComponent<MicProps & react.RefAttributes<MicHandle>>;
482
636
 
483
- interface UrunCameraStreamSource {
637
+ interface CameraStreamSource {
484
638
  attachVideo(track: MediaStreamTrack): Promise<void>;
485
639
  detachVideo(): Promise<void>;
486
640
  }
487
641
 
488
- interface UrunCameraSessionSource {
489
- stream(name: string): UrunCameraStreamSource;
642
+ interface CameraSessionSource {
643
+ stream(name: string): CameraStreamSource;
490
644
 
491
645
  whenLive(options?: {
492
646
  timeout?: number;
@@ -496,44 +650,50 @@ interface UrunCameraSessionSource {
496
650
  readonly status?: SessionStatus;
497
651
  }
498
652
 
499
- type UrunCameraFacing = 'user' | 'environment';
653
+ type CameraFacing = 'user' | 'environment';
500
654
 
501
- interface UrunCameraHandle {
655
+ interface CameraHandle {
502
656
 
503
657
  start(options?: {
504
- facingMode?: UrunCameraFacing;
658
+ facingMode?: CameraFacing;
505
659
  }): Promise<void>;
506
660
 
507
661
  stop(): Promise<void>;
508
662
 
509
663
  flip(): Promise<void>;
510
664
 
511
- setFacingMode(mode: UrunCameraFacing): Promise<void>;
665
+ setFacingMode(mode: CameraFacing): Promise<void>;
512
666
 
513
667
  readonly active: boolean;
514
668
 
515
- readonly facingMode: UrunCameraFacing;
669
+ readonly facingMode: CameraFacing;
516
670
 
517
671
  readonly stream: MediaStream | null;
518
672
 
519
673
  readonly element: HTMLVideoElement | null;
520
674
  }
521
675
 
522
- interface UrunCameraProps {
676
+ interface CameraProps {
523
677
 
524
- session: UrunCameraSessionSource;
678
+ session?: CameraSessionSource | null;
525
679
 
526
680
  stream?: string;
527
681
 
528
682
  constraints?: MediaTrackConstraints;
529
683
 
530
- facingMode?: UrunCameraFacing;
684
+ front?: boolean;
685
+
686
+ back?: boolean;
687
+
688
+ facingMode?: CameraFacing;
689
+
690
+ autoStart?: boolean;
531
691
 
532
692
  mirror?: boolean | 'auto';
533
693
 
534
694
  connectTimeoutMs?: number;
535
695
 
536
- preview?: boolean;
696
+ visible?: boolean;
537
697
 
538
698
  className?: string;
539
699
 
@@ -560,7 +720,24 @@ interface UrunCameraProps {
560
720
 
561
721
  declare const DEFAULT_CAMERA_CONSTRAINTS: MediaTrackConstraints;
562
722
 
563
- declare const UrunCamera: react.ForwardRefExoticComponent<UrunCameraProps & react.RefAttributes<UrunCameraHandle>>;
723
+ declare const Camera: react.ForwardRefExoticComponent<CameraProps & react.RefAttributes<CameraHandle>>;
724
+
725
+ interface UrunCameraProps extends Omit<CameraProps, 'session' | 'front' | 'back' | 'autoStart' | 'visible'> {
726
+
727
+ session: CameraSessionSource;
728
+
729
+ preview?: boolean;
730
+ }
731
+
732
+ declare const UrunCamera: react.ForwardRefExoticComponent<UrunCameraProps & react.RefAttributes<CameraHandle>>;
733
+
734
+ type UrunCameraHandle = CameraHandle;
735
+
736
+ type UrunCameraFacing = CameraFacing;
737
+
738
+ type UrunCameraStreamSource = CameraStreamSource;
739
+
740
+ type UrunCameraSessionSource = CameraSessionSource;
564
741
 
565
742
  interface UseUrunAudioLevelOptions {
566
743
 
@@ -885,4 +1062,4 @@ interface UrunActivationOverlayProps {
885
1062
 
886
1063
  declare function UrunActivationOverlay({ session, stream, videoElement, render, className, }: UrunActivationOverlayProps): react_jsx_runtime.JSX.Element | null;
887
1064
 
888
- export { type ActivationProgress, type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, ImageFrame, ImageFrameSchema, type InputPresenceControls, type InputPresenceSession, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type RegisteredComponent, type RequestCapableSession, type RequestStream, type SessionIdleState, type SessionRequestOptions, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunActivationOverlay, type UrunActivationOverlayProps, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunIdleWarning, type UrunIdleWarningProps, UrunJwtProvider, UrunProvider, UrunSessionClock, type UrunSessionClockProps, UrunSessionEnded, type UrunSessionEndedProps, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseInputPresenceOptions, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseUrunAudioLevelOptions, type UseUrunPrewakeOptions, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, registerComponent, resumeUrunAudioContext, urunPublicEnv, useActivation, useApp, useChat, useCompletion, useDocStore, useImageFrame, useInputPresence, useMetricsPanel, useProgressCard, useRequest, useSessionDoc, useSessionEndsAt, useSessionIdle, useSessionPhase, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useTextStream, useUrunAudioLevel, useUrunAuth, useUrunPrewake, usesWorkOSAuth };
1065
+ export { type ActivationProgress, Audio, type AudioHandle, type AudioProps, type AudioSessionSource, type AudioStreamSource, Camera, type CameraFacing, type CameraHandle, type CameraProps, type CameraSessionSource, type CameraStreamSource, type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, Image, ImageFrame, ImageFrameSchema, type ImageHandle, type ImageProps, type InputPresenceControls, type InputPresenceSession, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, Mic, type MicHandle, type MicProps, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type RegisteredComponent, type RequestCapableSession, type RequestStream, type ScopedSession, type ScopedStreamSource, type SessionIdleState, type SessionRequestOptions, SessionScope, type SessionScopeProps, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunActivationOverlay, type UrunActivationOverlayProps, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunIdleWarning, type UrunIdleWarningProps, UrunJwtProvider, UrunProvider, UrunSessionClock, type UrunSessionClockProps, UrunSessionEnded, type UrunSessionEndedProps, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseInputPresenceOptions, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseUrunAudioLevelOptions, type UseUrunPrewakeOptions, Video, type VideoHandle, type VideoProps, type VideoSessionSource, type VideoStreamSource, Voice, type VoiceHandle, type VoiceProps, type VoiceSessionSource, type VoiceStreamSource, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, registerComponent, resumeUrunAudioContext, urunPublicEnv, useActivation, useApp, useChat, useCompletion, useDocStore, useImageFrame, useInputPresence, useMetricsPanel, useProgressCard, useRequest, useSessionDoc, useSessionEndsAt, useSessionIdle, useSessionPhase, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useTextStream, useUrunAudioLevel, useUrunAuth, useUrunPrewake, usesWorkOSAuth };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client"
2
- "use strict";var Ut=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var ar=(t,e)=>{for(var n in e)Ut(t,n,{get:e[n],enumerable:!0})},ur=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sr(e))!ir.call(t,o)&&o!==n&&Ut(t,o,{get:()=>e[o],enumerable:!(r=or(e,o))||r.enumerable});return t};var cr=t=>ur(Ut({},"__esModule",{value:!0}),t);var Er={};ar(Er,{ComponentRenderer:()=>gn,DEFAULT_CAMERA_CONSTRAINTS:()=>Vt,DEFAULT_LOG_CAP:()=>ue,DEFAULT_VOICE_CONSTRAINTS:()=>Ft,DocPatchForm:()=>ze,ImageFrame:()=>Pn,ImageFrameSchema:()=>Cn,MetricsPanel:()=>xn,MetricsPanelSchema:()=>Tn,ProgressCard:()=>Sn,ProgressCardSchema:()=>hn,StatusBadge:()=>yn,StatusBadgeSchema:()=>vn,TextStream:()=>bn,TextStreamSchema:()=>kn,UrunActivationOverlay:()=>kt,UrunAudio:()=>rt,UrunAuthProvider:()=>Rt,UrunCamera:()=>_n,UrunControlSender:()=>Vn,UrunDocPanel:()=>Fn,UrunErrorBoundary:()=>be,UrunEventSpine:()=>Bn,UrunIdleWarning:()=>Gn,UrunJwtProvider:()=>Qt,UrunProvider:()=>tn,UrunSessionClock:()=>Jn,UrunSessionEnded:()=>Xn,UrunSessionGate:()=>Kn,UrunSessionStatus:()=>jn,UrunSessionWaking:()=>St,UrunStreamTail:()=>qn,UrunVoice:()=>wn,authMode:()=>Fe,createDocStore:()=>ut,describeSessionPhase:()=>Pt.describeSessionPhase,formatPayload:()=>Me,getUrunAudioContext:()=>je,isWakingPhase:()=>Pt.isWakingPhase,parseJsonObject:()=>lt,pushCapped:()=>oe,registerComponent:()=>mn,resumeUrunAudioContext:()=>Ke,urunPublicEnv:()=>ne,useActivation:()=>vt,useApp:()=>rn,useChat:()=>ln,useCompletion:()=>an,useDocStore:()=>_e,useImageFrame:()=>Lt,useInputPresence:()=>dn,useMetricsPanel:()=>Ot,useProgressCard:()=>Nt,useRequest:()=>on,useSessionDoc:()=>On,useSessionEndsAt:()=>Ht,useSessionIdle:()=>jt,useSessionPhase:()=>G,useSessionTrack:()=>Nn,useSessionWake:()=>ht,useStatusBadge:()=>It,useStreamMessages:()=>pt,useTextStream:()=>Dt,useUrunAudioLevel:()=>Mn,useUrunAuth:()=>Ye,useUrunPrewake:()=>Yn,usesWorkOSAuth:()=>Zt});module.exports=cr(Er);var Te=require("react");var Xt=require("react"),qe=require("react/jsx-runtime"),be=class extends Xt.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,n){console.error("[urun] Error caught by UrunErrorBoundary:",e,n)}render(){if(this.state.error){let{fallback:e}=this.props;return typeof e=="function"?e(this.state.error):e||(0,qe.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,qe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,qe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var Gt=require("react"),Ce=(0,Gt.createContext)(null);function me(t){return t&&t.trim()?t.trim():void 0}function ne(t){switch(t){case"NEXT_PUBLIC_AUTH_MODE":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return me(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return me(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return me(typeof process<"u"?process.env?.[t]:void 0)}}function Fe(){let t=ne("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return t==="jwt"||t==="customer-jwt"||t==="test-jwt"?"jwt":t==="workos"||ne("VERCEL_ENV")==="production"?"workos":ne("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Zt(){return Fe()==="workos"}var Pe=require("react"),en=require("react/jsx-runtime"),Yt=(0,Pe.createContext)(null);function Rt({getAccessToken:t,children:e}){let n=(0,Pe.useMemo)(()=>({getAccessToken:t}),[t]);return(0,en.jsx)(Yt.Provider,{value:n,children:e})}var Qt=Rt;function Ye(){return(0,Pe.useContext)(Yt)}var Qe=require("react/jsx-runtime");function tn({baseUrl:t,orgId:e,appId:n,jwt:r,authProvider:o,eventsUrl:s,fallback:a,children:i}){let[u,c]=(0,Te.useState)(),p=Ye(),l=ne("NEXT_PUBLIC_SESSION_TOKEN")??ne("NEXT_PUBLIC_URUN_JWT"),f=Fe(),g=f==="workos"&&!r,v=r??(f==="jwt"?l:void 0)??u,b=o??ne("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),S=g&&!v,k=(0,Te.useMemo)(()=>({appId:n,baseUrl:t,orgId:e,jwt:v,getAccessToken:g?p?.getAccessToken:void 0,authProvider:b,eventsUrl:s}),[n,p,t,b,v,s,e,g]);return(0,Te.useEffect)(()=>{if(!g||!p)return;let x=!1,P=p;async function E(){try{let w=await P.getAccessToken();x||c(w??void 0)}catch{x||c(void 0)}}E();let h=window.setInterval(()=>{E()},6e4);return()=>{x=!0,window.clearInterval(h)}},[p,g]),(0,Qe.jsx)(be,{fallback:a,children:S?(0,Qe.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Qe.jsx)(Ce.Provider,{value:k,children:i})})}var X=require("react"),nn=require("@urun-sh/core");function lr(t,e){return`${t}:${JSON.stringify(e??{})}`}function dr(t,e,n){return JSON.stringify({appId:t.appId,baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,fnName:e,args:n??{}})}var xe=new Map;var Et=class{constructor(e,n){this._doc=e;this._notify=n;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(e,n){return this._doc.get(e,n)}set(e){this._doc.set(e),this._notify()}on(e,n){return this._doc.on(e,r=>n(r))}get synced(){return this._doc.synced}onSynced(e){return this._doc.onSynced(()=>{e(),this._notify()})}text(e){let n=this._doc.text(e),r=this._notify;return{append(o){n.append(o),r()},toString:()=>n.toString(),get length(){return n.length},on:(o,s)=>n.on(o,a=>{s(a),r()})}}dispose(){this._unsubscribeChange()}},wt=class{constructor(e,n){this._stream=e;this._notify=n;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(e){return this._stream.attach(e)}attachVideo(e){return this._stream.attachVideo(e)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(e){return this._stream.seek(e)}chunks(e){return this._stream.chunks(e)}onSeeked(e){return this._stream.onSeeked(e)}on(e,n){return this._stream.on(e,n)}messages(){return this._stream.messages()}emit(e,n){return this._stream.emit(e,n)}dispose(){this._unsubscribeTrack()}},At=class{constructor(e,n,r){this._session=e;this._notifiers.add(n),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),r&&this._attachReporter(r)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(e){let n=!1,r=!1,o=i=>{fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0}).catch(()=>{r||(r=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(o);let s=this._session.onPhase(i=>{if(i.name==="error"||i.name==="expired"){let u=i.error,c=u?.reason??(i.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);o({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else i.name==="live"&&!n&&(n=!0,o({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),a=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{a(),s()}}addNotifier(e){this._notifiers.add(e)}removeNotifier(e){this._notifiers.delete(e)}_notifyAll(){for(let e of this._notifiers)e()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(e){return this._session.onPhase(e)}onDiagnostic(e){return this._session.onDiagnostic(e)}whenLive(e){return this._session.whenLive(e)}recover(){this._session.recover()}onRecovery(e){return this._session.onRecovery(e)}request(e,n){return this._session.request(e,n)}requestStream(e,n){return this._session.requestStream(e,n)}complete(e,n){return this._session.complete(e,n)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(e){let n=this._docs.get(e);return n||(n=new Et(this._session.doc(e),()=>this._notifyAll()),this._docs.set(e,n)),n}stream(e){let n=this._streams.get(e);return n||(n=new wt(this._session.stream(e),()=>this._notifyAll()),this._streams.set(e,n)),n}async end(){let e=await this._session.end();return this._disposeHandle(),e}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let e of this._docs.values())e.dispose();for(let e of this._streams.values())e.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function rn(){let t=(0,X.useContext)(Ce);if(!t)throw new Error("useApp must be used within <UrunProvider>");if(!t.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,e]=(0,X.useReducer)(s=>s+1,0),n=(0,X.useRef)(new Map),r=(0,X.useRef)(new Map),o=(0,X.useMemo)(()=>(0,nn.App)(t.appId,{baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),[t.appId,t.baseUrl,t.orgId,t.jwt,t.getAccessToken,t.authProvider]);return(0,X.useEffect)(()=>()=>{for(let[s,a]of r.current){let i=xe.get(s);i===a&&(i.handle.removeNotifier(e),i.refCount=Math.max(0,i.refCount-1),i.refCount===0&&(i.disposeTimer=setTimeout(()=>{let u=xe.get(s);!u||u.refCount!==0||(xe.delete(s),u.handle.disconnect())},0)))}r.current.clear(),n.current.clear()},[]),(0,X.useMemo)(()=>new Proxy({},{get(s,a){if(typeof a=="string")return i=>{let u=lr(a,i),c=n.current.get(u);if(c&&!c.disposed)return c;let p=dr(t,a,i),l=xe.get(p);return l?.handle.disposed&&(l.disposeTimer&&clearTimeout(l.disposeTimer),xe.delete(p),r.current.get(p)===l&&r.current.delete(p),l=void 0),l?l.disposeTimer&&(clearTimeout(l.disposeTimer),l.disposeTimer=null):(l={handle:new At(o[a](i),e,t.eventsUrl),refCount:0,disposeTimer:null},xe.set(p,l)),r.current.get(p)!==l&&(r.current.set(p,l),l.handle.addNotifier(e),l.refCount+=1),n.current.set(u,l.handle),l.handle}}}),[t,o])}var F=require("react");function Ue(t){let e=t;if(!e||typeof e.request!="function"||typeof e.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 e}function pr(t){return t instanceof Error?t:new Error(String(t))}function on(t,e){let n=(0,F.useMemo)(()=>Ue(t),[t]),[r,o]=(0,F.useState)(void 0),[s,a]=(0,F.useState)(null),[i,u]=(0,F.useState)(!1),c=(0,F.useRef)(e);c.current=e;let p=(0,F.useRef)(0),l=(0,F.useRef)(null),f=(0,F.useRef)(!0);(0,F.useEffect)(()=>(f.current=!0,()=>{f.current=!1,l.current?.abort()}),[]);let g=(0,F.useCallback)(async S=>{l.current?.abort();let k=new AbortController;l.current=k;let x=++p.current,P=()=>f.current&&p.current===x;P()&&(u(!0),a(null));try{let E=await n.request(S,{...c.current,signal:k.signal});return P()&&(o(E),u(!1),c.current?.onSuccess?.(E)),E}catch(E){let h=pr(E);throw P()&&(a(h),u(!1),c.current?.onError?.(h)),h}},[n]),v=(0,F.useCallback)(S=>{g(S).catch(()=>{})},[g]),b=(0,F.useCallback)(()=>{p.current++,l.current?.abort(),l.current=null,o(void 0),a(null),u(!1)},[]);return{mutate:v,mutateAsync:g,data:r,error:s,isPending:i,reset:b}}var V=require("react");function sn(t){return t instanceof Error?t:new Error(String(t))}var mr=t=>typeof t=="string"?t:String(t);function an(t,e){let n=(0,V.useMemo)(()=>Ue(t),[t]),[r,o]=(0,V.useState)(""),[s,a]=(0,V.useState)(!1),[i,u]=(0,V.useState)(null),c=(0,V.useRef)(e);c.current=e;let p=(0,V.useRef)(0),l=(0,V.useRef)(null),f=(0,V.useRef)(!0);(0,V.useEffect)(()=>(f.current=!0,()=>{f.current=!1,l.current?.cancel(),l.current=null}),[]);let g=(0,V.useCallback)(()=>{p.current++,l.current?.cancel(),l.current=null,f.current&&a(!1)},[]),v=(0,V.useCallback)(async b=>{l.current?.cancel();let S=++p.current,k=()=>f.current&&p.current===S,x=c.current,P=x?.parseChunk??mr,E=x?.buildPayload??(T=>({prompt:T}));k()&&(o(""),u(null),a(!0));let{parseChunk:h,buildPayload:w,onFinish:_,onError:d,...C}=x??{},U="",R;try{R=n.requestStream(E(b),C),l.current=R}catch(T){let j=sn(T);k()&&(u(j),a(!1),x?.onError?.(j));return}try{for await(let T of R){if(p.current!==S)break;U+=P(T),k()&&o(U)}k()&&(a(!1),x?.onFinish?.(U))}catch(T){let j=sn(T);k()&&(u(j),a(!1),x?.onError?.(j))}finally{l.current===R&&(l.current=null)}},[n]);return{completion:r,complete:v,stop:g,isStreaming:s,error:i}}var O=require("react");function un(t){return t instanceof Error?t:new Error(String(t))}var fr=t=>typeof t=="string"?t:String(t),cn=0;function _t(t){return cn+=1,`${t}-${cn}`}function ln(t,e){let n=(0,O.useMemo)(()=>Ue(t),[t]),[r,o]=(0,O.useState)(()=>(e?.initialMessages??[]).map(P=>({id:P.id??_t("msg"),role:P.role,content:P.content}))),[s,a]=(0,O.useState)(""),[i,u]=(0,O.useState)(!1),[c,p]=(0,O.useState)(null),l=(0,O.useRef)(e);l.current=e;let f=(0,O.useRef)(r);f.current=r;let g=(0,O.useRef)(s);g.current=s;let v=(0,O.useRef)(0),b=(0,O.useRef)(null),S=(0,O.useRef)(!0);(0,O.useEffect)(()=>(S.current=!0,()=>{S.current=!1,b.current?.cancel(),b.current=null}),[]);let k=(0,O.useCallback)(()=>{v.current++,b.current?.cancel(),b.current=null,S.current&&u(!1)},[]),x=(0,O.useCallback)(async P=>{let E=P===void 0,h=(E?g.current:P)??"";if(!h.trim())return;b.current?.cancel();let _=++v.current,d=()=>S.current&&v.current===_,C=l.current,U=C?.parseChunk??fr,R={id:_t("msg"),role:"user",content:h},T={id:_t("msg"),role:"assistant",content:""},j=[...f.current,R].map(H=>({role:H.role,content:H.content})),m=[...f.current,R,T];f.current=m,o(m),E&&a(""),p(null),u(!0);let L=C?.buildPayload??(H=>({messages:H})),{initialMessages:B,parseChunk:K,buildPayload:q,onFinish:ie,onError:Ge,...Ze}=C??{},ve=H=>{o(W=>W.map(ae=>ae.id===T.id?{...ae,content:H}:ae))},pe="",ee;try{ee=n.requestStream(L(j),Ze),b.current=ee}catch(H){let W=un(H);d()&&(p(W),u(!1),C?.onError?.(W));return}try{for await(let H of ee){if(v.current!==_)break;pe+=U(H),d()&&ve(pe)}d()&&(u(!1),C?.onFinish?.({...T,content:pe}))}catch(H){let W=un(H);d()&&(p(W),u(!1),C?.onError?.(W))}finally{b.current===ee&&(b.current=null)}},[n]);return{messages:r,input:s,setInput:a,sendMessage:x,stop:k,isStreaming:i,error:c}}var D=require("react"),Re=require("@urun-sh/core"),Mt=[];function dn(t,e={}){let{field:n=Re.INPUT_PRESENCE_FIELD,hz:r=Re.INPUT_PRESENCE_DEFAULT_HZ}=e,o=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null,s=t?.presence??null,a=(0,D.useMemo)(()=>s?(0,Re.createInputPresencePublisher)({awareness:{setLocalStateField:(h,w)=>s.setField(h,w)},field:n,hz:r}):null,[s,n,r]),i=(0,D.useRef)(null);i.current=a;let[u,c]=(0,D.useState)(!1),[p,l]=(0,D.useState)(Mt),f=(0,D.useRef)(!1);(0,D.useEffect)(()=>{if(a)return()=>a.dispose()},[a]);let g=(0,D.useCallback)(()=>{let h=i.current;l(h?h.heldKeys():Mt)},[]),v=(0,D.useCallback)(()=>{i.current?.clear(),l(Mt)},[]);(0,D.useEffect)(()=>{if(!o)return;let h=()=>!!o.pointerLockElement,w=()=>{if(h()){f.current=!1,c(!0);return}f.current||(c(!1),v())},_=T=>{h()&&(i.current?.keyDown(T.key),g())},d=T=>{i.current?.keyUp(T.key),g()},C=T=>{h()&&i.current?.movePointer(T.movementX,T.movementY)},U=T=>{h()&&i.current?.setButtons(T.buttons)},R=()=>{v()};return o.addEventListener("pointerlockchange",w),o.addEventListener("keydown",_),o.addEventListener("keyup",d),o.addEventListener("mousemove",C),o.addEventListener("mousedown",U),o.addEventListener("mouseup",U),o.defaultView?.addEventListener("blur",R),()=>{o.removeEventListener("pointerlockchange",w),o.removeEventListener("keydown",_),o.removeEventListener("keyup",d),o.removeEventListener("mousemove",C),o.removeEventListener("mousedown",U),o.removeEventListener("mouseup",U),o.defaultView?.removeEventListener("blur",R)}},[o,v,g]);let b=(0,D.useCallback)(h=>{h.requestPointerLock?.()},[]),S=(0,D.useCallback)(()=>{f.current=!0,c(!0)},[]),k=(0,D.useCallback)(()=>{f.current=!1,o?.pointerLockElement&&o.exitPointerLock?.(),c(!1),v()},[o,v]),x=(0,D.useCallback)(h=>{i.current?.keyDown(h),g()},[g]),P=(0,D.useCallback)(h=>{i.current?.keyUp(h),g()},[g]),E=(0,D.useCallback)((h,w)=>{i.current?.movePointer(h,w)},[]);return{engage:b,engageTouch:S,release:k,engaged:u,heldKeys:p,pressKey:x,releaseKey:P,movePointer:E}}var pn=new Map;function mn(t,e,n){if(!n||typeof n.safeParse!="function")throw new Error(`registerComponent("${t}"): schema must be a valid Zod schema`);pn.set(t,{component:e,schema:n})}function fn(t,e){let n=pn.get(t);if(!n)return{error:`Unknown component: "${t}"`};let r=n.schema.safeParse(e);return r.success?{Component:n.component,validatedProps:r.data}:{error:`Validation failed for "${t}": ${r.error.message}`}}var fe=require("react/jsx-runtime");function gn({name:t,props:e,fallback:n}){let r=fn(t,e);if(r.error)return console.warn(`[urun] ComponentRenderer: ${r.error}`),n?(0,fe.jsx)(fe.Fragment,{children:n}):(0,fe.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,fe.jsx)("span",{className:"urun-component-error-text",children:r.error})});let o=r.Component;return(0,fe.jsx)(o,{...r.validatedProps})}var Ee=require("zod"),ge=require("react/jsx-runtime"),hn=Ee.z.object({step:Ee.z.number().min(0),total:Ee.z.number().min(1),label:Ee.z.string().optional(),variant:Ee.z.enum(["default","success","error"]).default("default")});function Nt(t){let{step:e,total:n,label:r,variant:o="default"}=t,s=Math.min(e/n*100,100),a=e>=n;return{step:e,total:n,label:r,variant:o,percentage:s,isComplete:a}}function Sn(t){let{step:e,total:n,label:r,variant:o,percentage:s}=Nt(t);return(0,ge.jsxs)("div",{className:"urun-progress-card","data-variant":o,children:[r&&(0,ge.jsx)("div",{className:"urun-progress-label",children:r}),(0,ge.jsx)("div",{className:"urun-progress-bar",children:(0,ge.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,ge.jsxs)("div",{className:"urun-progress-text",children:[e,"/",n]})]})}var et=require("zod"),We=require("react/jsx-runtime"),vn=et.z.object({state:et.z.enum(["thinking","generating","idle","error"]),message:et.z.string().optional()}),gr={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function It(t){let{state:e,message:n}=t,r=e==="thinking"||e==="generating",o=n??gr[e]??e;return{state:e,message:o,isActive:r}}function yn(t){let{state:e,message:n,isActive:r}=It(t);return(0,We.jsxs)("span",{className:"urun-status-badge","data-state":e,children:[(0,We.jsx)("span",{className:`urun-status-indicator${r?" urun-status-pulse":""}`}),(0,We.jsx)("span",{className:"urun-status-message",children:n})]})}var Ve=require("react"),tt=require("zod"),Be=require("react/jsx-runtime"),kn=tt.z.object({text:tt.z.string(),streaming:tt.z.boolean().default(!1)});function Dt(t){let{text:e,streaming:n=!1}=t,r=e.length===0;return{text:e,streaming:n,isEmpty:r}}function bn(t){let{text:e,streaming:n}=Dt(t),r=(0,Ve.useRef)(null),o=(0,Ve.useRef)(0);return(0,Ve.useEffect)(()=>{let s=r.current;s&&e.length!==o.current&&(s.textContent=e,o.current=e.length)},[e]),(0,Be.jsxs)("div",{className:"urun-text-stream",children:[(0,Be.jsx)("span",{ref:r,className:"urun-text-content"}),n&&(0,Be.jsx)("span",{className:"urun-text-cursor"})]})}var He=require("zod"),$e=require("react/jsx-runtime"),Cn=He.z.object({src:He.z.string().url(),alt:He.z.string().optional(),caption:He.z.string().optional()});function Lt(t){let{src:e,alt:n,caption:r}=t;return{src:e,alt:n??"",caption:r}}function Pn(t){let{src:e,alt:n,caption:r}=Lt(t);return(0,$e.jsxs)("figure",{className:"urun-image-frame",children:[(0,$e.jsx)("img",{className:"urun-image",src:e,alt:n}),r&&(0,$e.jsx)("figcaption",{className:"urun-image-caption",children:r})]})}var re=require("zod"),we=require("react/jsx-runtime"),Tn=re.z.object({metrics:re.z.array(re.z.object({label:re.z.string(),value:re.z.union([re.z.string(),re.z.number()]),unit:re.z.string().optional()}))});function Ot(t){return{metrics:t.metrics.map(n=>({...n,displayValue:n.unit?`${n.value} ${n.unit}`:String(n.value)}))}}function xn(t){let{metrics:e}=Ot(t);return(0,we.jsx)("div",{className:"urun-metrics-panel",children:e.map((n,r)=>(0,we.jsxs)("div",{className:"urun-metric-card",children:[(0,we.jsx)("div",{className:"urun-metric-label",children:n.label}),(0,we.jsx)("div",{className:"urun-metric-value",children:n.displayValue})]},r))})}var N=require("react"),Rn=require("@urun-sh/core");var nt=null;function hr(){if(typeof window>"u")return null;let t=window;return t.AudioContext??t.webkitAudioContext??null}function je(){if(nt)return nt;let t=hr();return t?(nt=new t,nt):null}function Ke(){let t=je();t&&t.state==="suspended"&&t.resume().catch(()=>{})}var En=require("react/jsx-runtime"),Sr=1e3,Un=200;function qt(...t){console.debug("[urun-audio]",...t)}var rt=(0,N.forwardRef)(function(e,n){let{session:r,stream:o="audio",track:s,controls:a=!1,className:i,onTrack:u,onUnlockChange:c,onAudioElement:p}=e,l=(0,N.useRef)(null),f=(0,N.useRef)(null),g=(0,N.useRef)(null),v=(0,N.useRef)(null),b=(0,N.useRef)(u);b.current=u;let S=(0,N.useRef)(c);S.current=c;let k=(0,N.useCallback)(d=>{g.current!==d&&(g.current=d,S.current?.(d))},[]),x=(0,N.useCallback)(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let d=l.current;return d&&d.srcObject!==f.current&&(d.srcObject=f.current),f.current},[]),P=(0,N.useCallback)(d=>{let C=l.current;if(!C)return;let U=C.play();!U||typeof U.then!="function"||U.then(()=>{C.muted||k(!0)}).catch(R=>{let T=R instanceof Error?R.name:String(R);if(T==="AbortError"){qt(`play() aborted (${d}); retrying in ${Un}ms`),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,P(`${d}:retry`)},Un);return}if(T==="NotAllowedError"){qt(`play() blocked pending a user gesture (${d})`),k(!1);return}qt(`play() failed (${d})`,R)})},[k]),E=(0,N.useCallback)(d=>{let C=x();if(C){for(let U of C.getAudioTracks())U!==d&&C.removeTrack(U);d&&!C.getAudioTracks().includes(d)&&C.addTrack(d),d&&P("track-attach"),b.current?.(d)}},[x,P]),h=(0,N.useCallback)(()=>{let d=l.current;d&&(x(),d.muted=!1,P("gesture"),Ke(),k(!0))},[x,P,k]);(0,N.useImperativeHandle)(n,()=>({unlock:h,get unlocked(){return g.current===!0},get element(){return l.current}}),[h]);let w=(0,N.useCallback)(d=>{l.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),x()),p?.(d)},[x,p]),_=s!==void 0;return(0,N.useEffect)(()=>{if(_){E(s??null);return}if(!r)return;let d=r.stream(o),C=()=>{let m=f.current;return m?m.getAudioTracks()[0]??null:null},U=m=>{if(m!==C()&&(E(m),m)){let L=()=>{C()===m&&E(null)};m.addEventListener("ended",L)}},R=d.track;R&&R.readyState==="live"&&U(R);let T=d.on("track",m=>{m&&m.readyState!=="live"||U(m)}),j=setInterval(()=>{let m=d.track;m&&m.readyState==="live"&&U(m)},Sr);return()=>{T(),clearInterval(j)}},[r,o,_,s,E]),(0,N.useEffect)(()=>(0,Rn.observePageLifecycle)(()=>{Ke(),g.current===!0&&P("foreground")}),[P]),(0,N.useEffect)(()=>()=>{v.current&&clearTimeout(v.current)},[]),(0,En.jsx)("audio",{ref:w,className:i,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})});var M=require("react"),Ae=require("@urun-sh/core");var An=require("react/jsx-runtime"),Ft={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function ot(...t){console.debug("[urun-voice]",...t)}var wn=(0,M.forwardRef)(function(e,n){let{session:r,stream:o="audio",constraints:s=Ft,connectTimeoutMs:a,attempts:i=3,retryDelayMs:u=1500,onActiveChange:c,onError:p,onMicStream:l,onTrack:f,onUnlockChange:g,capture:v}=e,b=(0,M.useRef)(null),S=(0,M.useRef)(null),k=(0,M.useRef)(null),x=(0,M.useRef)([]),P=(0,M.useRef)(!1),E=(0,M.useRef)(c);E.current=c;let h=(0,M.useRef)(p);h.current=p;let w=(0,M.useRef)(l);w.current=l;let _=(0,M.useCallback)(m=>{P.current!==m&&(P.current=m,E.current?.(m))},[]),d=(0,M.useCallback)(()=>{for(let m of x.current)m();x.current=[],k.current?.release(),k.current=null,S.current&&(S.current=null,w.current?.(null))},[]),C=(0,M.useCallback)(async()=>{let m=k.current;if(m){let q=await m.update(s);return S.current=m.stream,w.current?.(m.stream),q}let B=await(v??(0,Ae.sharedCaptureController)()).claim("audio",s);k.current=B,x.current=[B.onTrack((q,ie)=>{S.current=ie,w.current?.(ie),P.current&&r.stream(o).attach(q).catch(Ge=>ot("mic re-attach after one-capture re-acquire failed",Ge))}),B.onLost(q=>{k.current=null,x.current=[],S.current=null,w.current?.(null),_(!1),h.current?.(q)})],S.current=B.stream,w.current?.(B.stream);let K=B.track;if(!K)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return K},[v,s,r,o,_]),U=(0,M.useCallback)(async()=>{d(),_(!1),await r.stream(o).detach().catch(()=>{})},[r,o,d,_]),R=(0,M.useCallback)(async()=>{b.current?.unlock();let m;try{m=await C()}catch(K){d();let q=(0,Ae.sessionFailureFromMediaError)(K,r.status);throw h.current?.(q),q}r.connect?.();let L;for(let K=1;K<=i;K++)try{await r.whenLive(a!==void 0?{timeout:a}:void 0),await r.stream(o).attach(m),_(!0);return}catch(q){L=q,ot(`start attempt ${K}/${i} failed`,q),K<i&&await new Promise(ie=>setTimeout(ie,u))}d(),_(!1);let B=L instanceof Error?L:new Error(String(L??"voice start failed"));throw h.current?.(B),B},[r,o,a,i,u,C,d,_]);(0,M.useImperativeHandle)(n,()=>({start:R,stop:U,unlock:()=>b.current?.unlock(),get active(){return P.current},get micStream(){return S.current},get audio(){return b.current}}),[R,U]);let T=(0,M.useRef)(!1),j=(0,M.useCallback)(async()=>{if(!P.current||T.current)return;let m=S.current?.getAudioTracks()[0]??null;if(m&&m.readyState==="live"){try{await r.stream(o).attach(m)}catch(L){ot("foreground mic re-assert failed (will retry on next pass)",L)}return}T.current=!0;try{let L=await C();await r.stream(o).attach(L)}catch(L){let B=L instanceof Error?L:new Error(String(L));ot("foreground mic re-acquire failed",B),h.current?.(B)}finally{T.current=!1}},[r,o,C]);return(0,M.useEffect)(()=>{let m=()=>{j()};return typeof r.onRecovery=="function"?r.onRecovery(m):(0,Ae.observePageLifecycle)(m)},[r,j]),(0,M.useEffect)(()=>d,[d]),(0,An.jsx)(rt,{ref:b,session:r,stream:o,onTrack:f,onUnlockChange:g})});var st=require("@urun-sh/core"),y=require("react"),Y=require("react/jsx-runtime"),Vt={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Wt(...t){console.debug("[urun-camera]",...t)}function vr(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function yr(){let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof t?.enumerateDevices!="function")return null;try{return(await t.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch{return null}}var _n=(0,y.forwardRef)(function(e,n){let{session:r,stream:o="video",constraints:s,facingMode:a="environment",mirror:i="auto",connectTimeoutMs:u,preview:c=!0,className:p,videoClassName:l,onActiveChange:f,onError:g,onStream:v,onTrack:b,children:S,capture:k,flipControl:x="auto",flipControlClassName:P,onDevices:E}=e,h=(0,y.useRef)(null),w=(0,y.useRef)(null),_=(0,y.useRef)(null),d=(0,y.useRef)([]),C=(0,y.useRef)(null),U=(0,y.useRef)(!1),R=(0,y.useRef)(a),[T,j]=(0,y.useState)(a),[m,L]=(0,y.useState)(!1),[B,K]=(0,y.useState)(null),[q,ie]=(0,y.useState)(!1),[Ge]=(0,y.useState)(vr),Ze=(0,y.useRef)(f);Ze.current=f;let ve=(0,y.useRef)(g);ve.current=g;let pe=(0,y.useRef)(v);pe.current=v;let ee=(0,y.useRef)(b);ee.current=b;let H=(0,y.useRef)(E);H.current=E;let W=(0,y.useCallback)(A=>{U.current!==A&&(U.current=A,L(A),Ze.current?.(A))},[]);(0,y.useEffect)(()=>{if(!m){K(null);return}let A=!1,I=()=>{yr().then(z=>{A||(K(z),z&&H.current?.(z))})};I();let $=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof $?.addEventListener=="function"?($.addEventListener("devicechange",I),()=>{A=!0,$.removeEventListener?.("devicechange",I)}):()=>{A=!0}},[m]);let ae=(0,y.useCallback)(A=>{let I=h.current;I&&(I.muted=!0,I.defaultMuted=!0,I.setAttribute("muted",""),I.setAttribute("playsinline",""),I.setAttribute("webkit-playsinline",""),I.srcObject=A,A&&I.play()?.catch?.($=>Wt("preview play() failed",$)))},[]),te=(0,y.useCallback)(()=>{C.current?.(),C.current=null;for(let A of d.current)A();d.current=[],_.current?.release(),_.current=null,w.current&&(w.current=null,pe.current?.(null),ee.current?.(null)),ae(null)},[ae]),Tt=(0,y.useCallback)((A,I)=>{C.current?.(),w.current=I,ae(I),pe.current?.(I);let $=()=>{w.current===I&&(Wt("camera track ended (device removed or permission revoked)"),te(),W(!1))};A.addEventListener("ended",$),C.current=()=>A.removeEventListener("ended",$)},[ae,te,W]),ye=(0,y.useCallback)(async A=>{let I={...Vt,...s,facingMode:A},$;try{let z=_.current;if(z)$=await z.update(I);else{let Le=await(k??(0,st.sharedCaptureController)()).claim("video",I);if(_.current=Le,d.current=[Le.onTrack((Oe,nr)=>{Tt(Oe,nr),U.current&&r.stream(o).attachVideo(Oe).then(()=>ee.current?.(Oe)).catch(rr=>Wt("camera re-publish after one-capture re-acquire failed",rr))}),Le.onLost(Oe=>{_.current=null,d.current=[],te(),W(!1),ve.current?.(Oe)})],!Le.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});$=Le.track}}catch(z){let ke=(0,st.sessionFailureFromMediaError)(z,r.status);throw ve.current?.(ke),ke}R.current=A,j(A),Tt($,_.current?.stream??new MediaStream([$]));try{r.connect?.(),await r.whenLive(u!==void 0?{timeout:u}:void 0),await r.stream(o).attachVideo($)}catch(z){te(),W(!1);let ke=z instanceof Error?z:new Error(String(z));throw ve.current?.(ke),ke}ee.current?.($),W(!0)},[r,o,s,u,k,Tt,te,W]),Kt=(0,y.useCallback)(A=>ye(A?.facingMode??R.current),[ye]),Jt=(0,y.useCallback)(async A=>{U.current&&R.current===A||await ye(A)},[ye]),xt=(0,y.useCallback)(()=>ye(R.current==="environment"?"user":"environment"),[ye]),zt=(0,y.useCallback)(async()=>{te(),W(!1),await r.stream(o).detachVideo().catch(()=>{})},[r,o,te,W]);if((0,y.useImperativeHandle)(n,()=>({start:Kt,stop:zt,flip:xt,setFacingMode:Jt,get active(){return U.current},get facingMode(){return R.current},get stream(){return w.current},get element(){return h.current}}),[Kt,zt,xt,Jt]),(0,y.useEffect)(()=>te,[te]),!c)return null;let Qn=i==="auto"?T==="user":i,er=m&&(x===!0||x==="auto"&&Ge&&(B?.length??0)>1),tr=()=>{q||(ie(!0),xt().catch(()=>{}).finally(()=>ie(!1)))};return(0,Y.jsxs)("div",{className:p,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":T,children:[(0,Y.jsx)("video",{ref:h,className:l,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Qn?{transform:"scaleX(-1)"}:{}}}),er?(0,Y.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:tr,disabled:q,className:P,style:P?{opacity:q?.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:q?.6:1},children:(0,Y.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,Y.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,Y.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,Y.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,Y.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,Y.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,S]})});var it=require("react");var Bt={level:0,speaking:!1};function Mn(t,e={}){let{fftSize:n=512,intervalMs:r=100,speakingThreshold:o=.02}=e,[s,a]=(0,it.useState)(Bt);return(0,it.useEffect)(()=>{if(!t){a(Bt);return}let i=je();if(!i||typeof MediaStream>"u")return;let u;t instanceof MediaStream?u=t:(u=new MediaStream,u.addTrack(t));let c,p;try{c=i.createMediaStreamSource(u),p=i.createAnalyser(),p.fftSize=n,c.connect(p)}catch{return}let l=new Uint8Array(p.fftSize),g=setInterval(()=>{p.getByteTimeDomainData(l);let v=0;for(let S=0;S<l.length;S++){let k=(l[S]-128)/128;v+=k*k}let b=Math.sqrt(v/l.length);a(S=>{let k=b>o;return Math.abs(S.level-b)<.005&&S.speaking===k?S:{level:b,speaking:k}})},r);return()=>{clearInterval(g),c.disconnect(),a(Bt)}},[t,n,r,o]),s}var at=require("react");function Nn(t,e){let[n,r]=(0,at.useState)(null);return(0,at.useEffect)(()=>{if(!t||!e){r(null);return}let o=t.stream(e);return r(o.track),o.on("track",r)},[t,e]),n}var Ln=require("react");var ct=require("react");var In=require("zustand/vanilla"),Dn=require("zustand"),kr=()=>{};function ut(t,e={}){let n=c=>{t?.set(c)},r=()=>t?t.get()??{}:{},o=(0,In.createStore)(()=>({doc:r(),synced:t?t.synced:!1,set:n})),s=null,a=()=>{if(s){for(let c of s)c();s=null}},i=()=>t?(s||(o.setState({doc:r(),synced:t.synced}),s=[t.on("change",c=>o.setState({doc:c})),t.onSynced(()=>o.setState({synced:!0}))]),a):kr,u=(c=>(0,Dn.useStore)(o,c));return Object.assign(u,{getState:o.getState,getInitialState:o.getInitialState,subscribe:o.subscribe,set:n,bind:i,unbind:a}),e.bind!==!1&&i(),u}function _e(t,e){let n=(0,ct.useMemo)(()=>ut(t&&e?t.doc(e):null,{bind:!1}),[t,e]);return(0,ct.useEffect)(()=>n.bind(),[n]),n}function On(t,e,n){let o=_e(t,e)(n??(i=>i)),s=(0,Ln.useCallback)(i=>{t&&e&&t.doc(e).set(i)},[t,e]);if(n)return o;let a=o;return{snapshot:t&&e?a.doc:null,synced:a.synced,set:s}}var dt=require("react");var ue=200;function oe(t,e,n=200){let r=[...t,e];return r.length>n?r.slice(r.length-n):r}function Me(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function lt(t){let e=t.trim();if(!e)return{ok:!1,error:"Enter a JSON object."};let n;try{n=JSON.parse(e)}catch(r){return{ok:!1,error:r instanceof Error?r.message:"Invalid JSON."}}return n===null||typeof n!="object"||Array.isArray(n)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:n}}function pt(t,e,n={}){let r=n.cap??200,[o,s]=(0,dt.useState)([]);return(0,dt.useEffect)(()=>{if(s([]),!t||!e)return;let a=!0,i=t.stream(e).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await i.next();if(!a||u.done)break;s(c=>oe(c,{at:Date.now(),payload:u.value},r))}})(),()=>{a=!1,i.return?.()}},[t,e,r]),o}var Q=require("react/jsx-runtime");function qn({session:t,name:e,cap:n,className:r}){let o=pt(t,e,{cap:n});return(0,Q.jsxs)("div",{className:["urun-stream-tail",r].filter(Boolean).join(" "),children:[(0,Q.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,Q.jsx)("code",{children:e}),(0,Q.jsxs)("span",{className:"urun-stream-tail-count",children:[o.length," messages"]})]}),(0,Q.jsx)("div",{className:"urun-stream-tail-log",children:o.length===0?(0,Q.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,Q.jsx)("code",{children:e})," messages\u2026"]}):o.map((s,a)=>(0,Q.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,Q.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Me(s.payload)]},`${s.at}-${a}`))})]})}var Je=require("react");var J=require("react/jsx-runtime");function ze({placeholder:t,buttonLabel:e,disabled:n,onApply:r}){let[o,s]=(0,Je.useState)(""),[a,i]=(0,Je.useState)(null),u=(0,Je.useCallback)(()=>{let c=lt(o);if(!c.ok){i(c.error);return}i(null),r(c.value,o.trim()),s("")},[o,r]);return(0,J.jsxs)("div",{className:"urun-doc-patch",children:[(0,J.jsx)("textarea",{className:"urun-doc-patch-input",value:o,onChange:c=>s(c.target.value),placeholder:t,rows:3}),(0,J.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,J.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:n||!o.trim(),onClick:u,children:e}),a?(0,J.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function Fn({session:t,docKey:e,editable:n=!0,patchPlaceholder:r='{"desired": {"prompt": {"text": "a sunset"}}}',className:o}){let s=_e(t,e),a=s(c=>c.doc),i=s(c=>c.synced),u=s(c=>c.set);return(0,J.jsxs)("div",{className:["urun-doc-panel",o].filter(Boolean).join(" "),children:[(0,J.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,J.jsx)("code",{children:e}),(0,J.jsx)("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),(0,J.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),n?(0,J.jsx)(ze,{placeholder:r,buttonLabel:"Apply patch",disabled:!t,onApply:c=>u(c)}):null]})}var mt=require("react");var se=require("react/jsx-runtime");function Wn(t,e=600){return t.length>e?`${t.slice(0,e)}\u2026`:t}function Vn({session:t,docKey:e="control",cap:n=200,className:r}){let[o,s]=(0,mt.useState)([]);return(0,mt.useEffect)(()=>(s([]),t?t.doc(e).on("change",i=>{s(u=>oe(u,{at:Date.now(),direction:"in",text:Wn(Me(i))},n))}):void 0),[t,e,n]),(0,se.jsxs)("div",{className:["urun-control-sender",r].filter(Boolean).join(" "),children:[(0,se.jsx)(ze,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${e}`,disabled:!t,onApply:(a,i)=>{t?.doc(e).set(a),s(u=>oe(u,{at:Date.now(),direction:"out",text:Wn(i)},n))}}),(0,se.jsx)("div",{className:"urun-control-sender-log",children:o.length===0?(0,se.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...o].reverse().map((a,i)=>(0,se.jsxs)("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[(0,se.jsx)("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",(0,se.jsx)("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${i}`))})]})}var ft=require("react");var he=require("react/jsx-runtime");function Bn({session:t,trackNames:e=["video","audio"],docKeys:n=["control"],cap:r=200,className:o}){let[s,a]=(0,ft.useState)([]),i=e.join(","),u=n.join(",");return(0,ft.useEffect)(()=>{if(a([]),!t)return;let c=(l,f)=>a(g=>oe(g,{at:Date.now(),kind:l,text:f},r)),p=[];p.push(t.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of e){let f=t.stream(l);p.push(f.on("track",g=>c("track",`${l}: ${g?"track arrived":"track ended"}`)))}for(let l of n){let f=t.doc(l);p.push(f.on("change",()=>c("doc",`${l} changed`)))}return()=>p.forEach(l=>l())},[t,i,u,r]),(0,he.jsx)("div",{className:["urun-event-spine",o].filter(Boolean).join(" "),children:s.length===0?(0,he.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((c,p)=>(0,he.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,he.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,he.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${p}`))})}var bt=require("@urun-sh/core");var gt=require("react");function G(t){let[e,n]=(0,gt.useState)(t?.phase??null);return(0,gt.useEffect)(()=>{if(!t){n(null);return}return t.onPhase(n)},[t]),e}var $n=require("@urun-sh/core");var Ne=require("react"),Hn=require("@urun-sh/core");function ht(t){let e=G(t),n=(0,Hn.isWakingPhase)(e?.name),r=(0,Ne.useRef)(void 0);n?r.current??=Date.now():r.current=void 0;let o=n?e?.wakingSince??r.current:void 0,s=()=>o!==void 0?Math.max(0,Math.floor((Date.now()-o)/1e3)):0,[a,i]=(0,Ne.useState)(s);return(0,Ne.useEffect)(()=>{if(o===void 0){i(0);return}i(Math.max(0,Math.floor((Date.now()-o)/1e3)));let u=setInterval(()=>{i(Math.max(0,Math.floor((Date.now()-o)/1e3)))},1e3);return()=>clearInterval(u)},[o]),{waking:n,phase:e,state:n?e?.runtime?.state:void 0,reason:n?e?.runtime?.reason:void 0,since:o,seconds:n?a:0}}var ce=require("react/jsx-runtime");function St({session:t,render:e,className:n}){let r=ht(t);return!r.waking||!r.phase?null:(0,ce.jsx)("span",{className:["urun-session-waking",n].filter(Boolean).join(" "),"data-phase":r.phase.name,"data-runtime-state":r.state,children:e?e(r):(0,ce.jsxs)(ce.Fragment,{children:[(0,ce.jsx)("span",{className:"urun-session-waking-label",children:(0,$n.describeSessionPhase)(r.phase)})," ",(0,ce.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",r.seconds,"s)"]})]})})}var yt=require("react");var le=require("react"),br={event:null,elapsedMs:0};function vt(t,e){let[n,r]=(0,le.useState)(null),o=(0,le.useRef)(0);(0,le.useEffect)(()=>{if(r(null),!!t?.onActivation)return t.onActivation(i=>{e!==void 0&&i.stream!==e||(o.current=Date.now(),r(i))})},[t,e]);let[s,a]=(0,le.useState)(0);return(0,le.useEffect)(()=>{if(!n){a(0);return}if(n.state==="first-media"){a(n.elapsedMs);return}let i=o.current,u=()=>n.elapsedMs+Math.max(0,Date.now()-i);a(u());let c=setInterval(()=>a(u()),1e3);return()=>clearInterval(c)},[n]),n?{event:n,elapsedMs:s}:br}var Ie=require("react/jsx-runtime"),Cr={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 Pr(t){let[e,n]=(0,yt.useState)(!1);return(0,yt.useEffect)(()=>{if(n(!1),!t)return;let r=t;if(typeof r.requestVideoFrameCallback=="function"){let s=r.requestVideoFrameCallback(()=>n(!0));return()=>r.cancelVideoFrameCallback?.(s)}let o=()=>{let s=r.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:r.readyState>=2)&&n(!0)};return o(),r.addEventListener("loadeddata",o),r.addEventListener("timeupdate",o),()=>{r.removeEventListener("loadeddata",o),r.removeEventListener("timeupdate",o)}},[t]),e}function kt({session:t,stream:e,videoElement:n,render:r,className:o}){let s=vt(t,e),a=Pr(n),i=s.event;if(!i||i.state==="first-media"||a)return null;let u=i.state;return(0,Ie.jsx)("div",{className:["urun-activation-overlay",o].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:r?r(s):(0,Ie.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,Ie.jsx)("span",{className:"urun-activation-overlay-copy",children:i.hint??Cr[u]})," ",(0,Ie.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var Z=require("react/jsx-runtime"),Tr={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function jn({session:t,className:e}){let n=G(t),r=n?.name??"idle",o=n?.name==="queued"&&n.queue?`pos ${n.queue.position} / depth ${n.queue.depth}`:(n?.name==="error"||n?.name==="expired")&&n.error?n.error.reason:n?.runtime?.reason??null;return(0,Z.jsxs)("span",{className:["urun-session-status",e].filter(Boolean).join(" "),"data-phase":r,children:[(0,Z.jsx)("span",{className:"urun-session-status-dot","data-phase":r}),(0,Z.jsx)("span",{className:"urun-session-status-label",children:Tr[r]}),o?(0,Z.jsx)("span",{className:"urun-session-status-detail",children:o}):null]})}function Kn({session:t,children:e,fallback:n,onStartOver:r,className:o}){let s=G(t);if(s?.name==="live")return(0,Z.jsxs)("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:[e,(0,Z.jsx)(kt,{session:t})]});let a=n?n(s):(0,Z.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,bt.isWakingPhase)(s.name)?(0,Z.jsx)(St,{session:t}):s&&s.name!=="idle"?(0,bt.describeSessionPhase)(s):"Waiting for a live session\u2026"}),i=r!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,Z.jsxs)("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:[a,i?(0,Z.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:r,children:"Start over"}):null]})}var Ct=require("react");var zn=require("react/jsx-runtime");function Ht(t){return G(t)?.endsAt??null}function xr(t){let e=Math.max(0,Math.floor(t/1e3)),n=Math.floor(e/60),r=e%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function Jn({session:t,urgentMs:e=6e4,className:n}){let o=Ht(t)?.getTime()??null,[s,a]=(0,Ct.useState)(()=>o===null?null:Math.max(0,o-Date.now()));if((0,Ct.useEffect)(()=>{if(o===null){a(null);return}let u=()=>a(Math.max(0,o-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[o]),s===null)return null;let i=xr(s);return(0,zn.jsx)("span",{className:["urun-session-clock",n].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${i}`,"data-urgent":s<e?"":void 0,"data-expired":s<=0?"":void 0,children:i})}var Xe=require("react/jsx-runtime"),Ur=new Set(["expired","ended","error"]);function Xn({session:t,onNewSession:e,children:n,className:r}){let o=G(t);if(!o||!Ur.has(o.name))return null;let s=n?n(o):(0,Xe.jsx)("span",{className:"urun-session-ended-copy",children:o.name==="expired"?"Session ended \u2014 start a new session":o.name==="error"?`Session failed${o.error?.reason?` \u2014 ${o.error.reason}`:""}.`:"Session ended."});return(0,Xe.jsxs)("div",{className:["urun-session-ended",r].filter(Boolean).join(" "),"data-phase":o.name,children:[s,e?(0,Xe.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:e,children:"New session"}):null]})}var de=require("react"),Se=require("react/jsx-runtime");function $t(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.warning!==!0?null:{warning:!0,deadlineEpochS:typeof e.deadline_epoch_s=="number"?e.deadline_epoch_s:null,idleSinceEpochS:typeof e.idle_since_epoch_s=="number"?e.idle_since_epoch_s:null}}function jt(t){let e=(0,de.useMemo)(()=>t?t.doc("control"):null,[t]),[n,r]=(0,de.useState)(()=>e?$t(e.get("idle")):null);return(0,de.useEffect)(()=>{if(!e){r(null);return}return r($t(e.get("idle"))),e.on("change",()=>r($t(e.get("idle"))))},[e]),n}function Rr(t){let e=Math.max(0,Math.floor(t));return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function Gn({session:t,onStillHere:e,className:n}){let r=jt(t),o=r?.deadlineEpochS??null,[s,a]=(0,de.useState)(null);if((0,de.useEffect)(()=>{if(o===null){a(null);return}let u=()=>a(Math.max(0,o-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[o]),!r||!t)return null;let i=()=>{t.touch?.(),e?.()};return(0,Se.jsx)("div",{className:["urun-idle-warning",n].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,Se.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Se.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Se.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Rr(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Se.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:i,children:"I'm still here"})]})})}var De=require("react"),Zn=require("@urun-sh/core");function Yn(t){let e=(0,De.useContext)(Ce),[n,r]=(0,De.useState)(null),o=t.app??e?.appId,s=t.function,a=t.intervalS??60,i=e?.baseUrl,u=e?.orgId,c=e?.jwt,p=e?.getAccessToken,l=e?.authProvider;return(0,De.useEffect)(()=>{if(!i||!u||!o||!s)return;let f=!1,g=()=>{(0,Zn.prewake)({baseUrl:i,app:o,functionName:s,orgId:u,jwt:c,getAccessToken:p,authProvider:l}).then(b=>{f||r(b)}).catch(()=>{})};g();let v=setInterval(g,Math.max(1,a)*1e3);return()=>{f=!0,clearInterval(v)}},[o,s,a,i,u,c,p,l]),n}var Pt=require("@urun-sh/core");0&&(module.exports={ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,ProgressCard,ProgressCardSchema,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useProgressCard,useRequest,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
2
+ "use strict";var Wt=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var An=Object.getOwnPropertyNames;var Un=Object.prototype.hasOwnProperty;var Mn=(t,e)=>{for(var r in e)Wt(t,r,{get:e[r],enumerable:!0})},_n=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of An(e))!Un.call(t,n)&&n!==r&&Wt(t,n,{get:()=>e[n],enumerable:!(o=wn(e,n))||o.enumerable});return t};var Nn=t=>_n(Wt({},"__esModule",{value:!0}),t);var ro={};Mn(ro,{Audio:()=>et,Camera:()=>or,ComponentRenderer:()=>Mr,DEFAULT_CAMERA_CONSTRAINTS:()=>nr,DEFAULT_LOG_CAP:()=>ge,DEFAULT_VOICE_CONSTRAINTS:()=>er,DocPatchForm:()=>nt,Image:()=>Kr,ImageFrame:()=>qr,ImageFrameSchema:()=>Vr,MetricsPanel:()=>Wr,MetricsPanelSchema:()=>Fr,Mic:()=>en,ProgressCard:()=>Nr,ProgressCardSchema:()=>_r,SessionScope:()=>Br,StatusBadge:()=>Lr,StatusBadgeSchema:()=>Ir,TextStream:()=>Or,TextStreamSchema:()=>Dr,UrunActivationOverlay:()=>It,UrunAudio:()=>Gr,UrunAuthProvider:()=>Ht,UrunCamera:()=>tn,UrunControlSender:()=>dn,UrunDocPanel:()=>un,UrunErrorBoundary:()=>we,UrunEventSpine:()=>pn,UrunIdleWarning:()=>kn,UrunJwtProvider:()=>gr,UrunProvider:()=>vr,UrunSessionClock:()=>hn,UrunSessionEnded:()=>yn,UrunSessionGate:()=>gn,UrunSessionStatus:()=>Sn,UrunSessionWaking:()=>Mt,UrunStreamTail:()=>cn,UrunVoice:()=>Zr,Video:()=>ft,Voice:()=>tt,authMode:()=>Ke,createDocStore:()=>Ct,describeSessionPhase:()=>Ot.describeSessionPhase,formatPayload:()=>qe,getUrunAudioContext:()=>Ze,isWakingPhase:()=>Ot.isWakingPhase,parseJsonObject:()=>xt,pushCapped:()=>de,registerComponent:()=>Ar,resumeUrunAudioContext:()=>Qe,urunPublicEnv:()=>ce,useActivation:()=>_t,useApp:()=>kr,useChat:()=>Rr,useCompletion:()=>Pr,useDocStore:()=>Ve,useImageFrame:()=>Yt,useInputPresence:()=>Er,useMetricsPanel:()=>Zt,useProgressCard:()=>zt,useRequest:()=>br,useSessionDoc:()=>an,useSessionEndsAt:()=>sr,useSessionIdle:()=>ar,useSessionPhase:()=>ee,useSessionTrack:()=>rn,useSessionWake:()=>Ut,useStatusBadge:()=>Xt,useStreamMessages:()=>Rt,useTextStream:()=>Gt,useUrunAudioLevel:()=>yt,useUrunAuth:()=>ut,useUrunPrewake:()=>Cn,usesWorkOSAuth:()=>fr});module.exports=Nn(ro);var Me=require("react");var pr=require("react"),je=require("react/jsx-runtime"),we=class extends pr.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,r){console.error("[urun] Error caught by UrunErrorBoundary:",e,r)}render(){if(this.state.error){let{fallback:e}=this.props;return typeof e=="function"?e(this.state.error):e||(0,je.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,je.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,je.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var mr=require("react"),Ae=(0,mr.createContext)(null);function ke(t){return t&&t.trim()?t.trim():void 0}function ce(t){switch(t){case"NEXT_PUBLIC_AUTH_MODE":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return ke(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ke(typeof process<"u"?process.env?.[t]:void 0)}}function Ke(){let t=ce("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return t==="jwt"||t==="customer-jwt"||t==="test-jwt"?"jwt":t==="workos"||ce("VERCEL_ENV")==="production"?"workos":ce("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function fr(){return Ke()==="workos"}var Ue=require("react"),hr=require("react/jsx-runtime"),Sr=(0,Ue.createContext)(null);function Ht({getAccessToken:t,children:e}){let r=(0,Ue.useMemo)(()=>({getAccessToken:t}),[t]);return(0,hr.jsx)(Sr.Provider,{value:r,children:e})}var gr=Ht;function ut(){return(0,Ue.useContext)(Sr)}var lt=require("react/jsx-runtime");function vr({baseUrl:t,orgId:e,appId:r,jwt:o,authProvider:n,eventsUrl:s,fallback:a,children:i}){let[c,u]=(0,Me.useState)(),m=ut(),l=ce("NEXT_PUBLIC_SESSION_TOKEN")??ce("NEXT_PUBLIC_URUN_JWT"),v=Ke(),y=v==="workos"&&!o,C=o??(v==="jwt"?l:void 0)??c,k=n??ce("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),b=y&&!C,S=(0,Me.useMemo)(()=>({appId:r,baseUrl:t,orgId:e,jwt:C,getAccessToken:y?m?.getAccessToken:void 0,authProvider:k,eventsUrl:s}),[r,m,t,k,C,s,e,y]);return(0,Me.useEffect)(()=>{if(!y||!m)return;let x=!1,T=m;async function E(){try{let w=await T.getAccessToken();x||u(w??void 0)}catch{x||u(void 0)}}E();let g=window.setInterval(()=>{E()},6e4);return()=>{x=!0,window.clearInterval(g)}},[m,y]),(0,lt.jsx)(we,{fallback:a,children:b?(0,lt.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,lt.jsx)(Ae.Provider,{value:S,children:i})})}var Z=require("react"),yr=require("@urun-sh/core");function In(t,e){return`${t}:${JSON.stringify(e??{})}`}function Ln(t,e,r){return JSON.stringify({appId:t.appId,baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,fnName:e,args:r??{}})}var _e=new Map;var Bt=class{constructor(e,r){this._doc=e;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(e,r){return this._doc.get(e,r)}set(e){this._doc.set(e),this._notify()}on(e,r){return this._doc.on(e,o=>r(o))}get synced(){return this._doc.synced}onSynced(e){return this._doc.onSynced(()=>{e(),this._notify()})}text(e){let r=this._doc.text(e),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,a=>{s(a),o()})}}dispose(){this._unsubscribeChange()}},$t=class{constructor(e,r){this._stream=e;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(e){return this._stream.attach(e)}attachVideo(e){return this._stream.attachVideo(e)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(e){return this._stream.seek(e)}chunks(e){return this._stream.chunks(e)}onSeeked(e){return this._stream.onSeeked(e)}on(e,r){return this._stream.on(e,r)}messages(){return this._stream.messages()}emit(e,r){return this._stream.emit(e,r)}dispose(){this._unsubscribeTrack()}},jt=class{constructor(e,r,o){this._session=e;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(e){let r=!1,o=!1,n=i=>{fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),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(i=>{if(i.name==="error"||i.name==="expired"){let c=i.error,u=c?.reason??(i.name==="expired"?`session ${this._session.id} expired`:`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 i.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),a=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{a(),s()}}addNotifier(e){this._notifiers.add(e)}removeNotifier(e){this._notifiers.delete(e)}_notifyAll(){for(let e of this._notifiers)e()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(e){return this._session.onPhase(e)}onDiagnostic(e){return this._session.onDiagnostic(e)}whenLive(e){return this._session.whenLive(e)}recover(){this._session.recover()}onRecovery(e){return this._session.onRecovery(e)}request(e,r){return this._session.request(e,r)}requestStream(e,r){return this._session.requestStream(e,r)}complete(e,r){return this._session.complete(e,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(e){let r=this._docs.get(e);return r||(r=new Bt(this._session.doc(e),()=>this._notifyAll()),this._docs.set(e,r)),r}stream(e){let r=this._streams.get(e);return r||(r=new $t(this._session.stream(e),()=>this._notifyAll()),this._streams.set(e,r)),r}async end(){let e=await this._session.end();return this._disposeHandle(),e}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let e of this._docs.values())e.dispose();for(let e of this._streams.values())e.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function kr(){let t=(0,Z.useContext)(Ae);if(!t)throw new Error("useApp must be used within <UrunProvider>");if(!t.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,e]=(0,Z.useReducer)(s=>s+1,0),r=(0,Z.useRef)(new Map),o=(0,Z.useRef)(new Map),n=(0,Z.useMemo)(()=>(0,yr.App)(t.appId,{baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),[t.appId,t.baseUrl,t.orgId,t.jwt,t.getAccessToken,t.authProvider]);return(0,Z.useEffect)(()=>()=>{for(let[s,a]of o.current){let i=_e.get(s);i===a&&(i.handle.removeNotifier(e),i.refCount=Math.max(0,i.refCount-1),i.refCount===0&&(i.disposeTimer=setTimeout(()=>{let c=_e.get(s);!c||c.refCount!==0||(_e.delete(s),c.handle.disconnect())},0)))}o.current.clear(),r.current.clear()},[]),(0,Z.useMemo)(()=>new Proxy({},{get(s,a){if(typeof a=="string")return i=>{let c=In(a,i),u=r.current.get(c);if(u&&!u.disposed)return u;let m=Ln(t,a,i),l=_e.get(m);return l?.handle.disposed&&(l.disposeTimer&&clearTimeout(l.disposeTimer),_e.delete(m),o.current.get(m)===l&&o.current.delete(m),l=void 0),l?l.disposeTimer&&(clearTimeout(l.disposeTimer),l.disposeTimer=null):(l={handle:new jt(n[a](i),e,t.eventsUrl),refCount:0,disposeTimer:null},_e.set(m,l)),o.current.get(m)!==l&&(o.current.set(m,l),l.handle.addNotifier(e),l.refCount+=1),r.current.set(c,l.handle),l.handle}}}),[t,n])}var W=require("react");function Ne(t){let e=t;if(!e||typeof e.request!="function"||typeof e.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 e}function Dn(t){return t instanceof Error?t:new Error(String(t))}function br(t,e){let r=(0,W.useMemo)(()=>Ne(t),[t]),[o,n]=(0,W.useState)(void 0),[s,a]=(0,W.useState)(null),[i,c]=(0,W.useState)(!1),u=(0,W.useRef)(e);u.current=e;let m=(0,W.useRef)(0),l=(0,W.useRef)(null),v=(0,W.useRef)(!0);(0,W.useEffect)(()=>(v.current=!0,()=>{v.current=!1,l.current?.abort()}),[]);let y=(0,W.useCallback)(async b=>{l.current?.abort();let S=new AbortController;l.current=S;let x=++m.current,T=()=>v.current&&m.current===x;T()&&(c(!0),a(null));try{let E=await r.request(b,{...u.current,signal:S.signal});return T()&&(n(E),c(!1),u.current?.onSuccess?.(E)),E}catch(E){let g=Dn(E);throw T()&&(a(g),c(!1),u.current?.onError?.(g)),g}},[r]),C=(0,W.useCallback)(b=>{y(b).catch(()=>{})},[y]),k=(0,W.useCallback)(()=>{m.current++,l.current?.abort(),l.current=null,n(void 0),a(null),c(!1)},[]);return{mutate:C,mutateAsync:y,data:o,error:s,isPending:i,reset:k}}var B=require("react");function Cr(t){return t instanceof Error?t:new Error(String(t))}var On=t=>typeof t=="string"?t:String(t);function Pr(t,e){let r=(0,B.useMemo)(()=>Ne(t),[t]),[o,n]=(0,B.useState)(""),[s,a]=(0,B.useState)(!1),[i,c]=(0,B.useState)(null),u=(0,B.useRef)(e);u.current=e;let m=(0,B.useRef)(0),l=(0,B.useRef)(null),v=(0,B.useRef)(!0);(0,B.useEffect)(()=>(v.current=!0,()=>{v.current=!1,l.current?.cancel(),l.current=null}),[]);let y=(0,B.useCallback)(()=>{m.current++,l.current?.cancel(),l.current=null,v.current&&a(!1)},[]),C=(0,B.useCallback)(async k=>{l.current?.cancel();let b=++m.current,S=()=>v.current&&m.current===b,x=u.current,T=x?.parseChunk??On,E=x?.buildPayload??(f=>({prompt:f}));S()&&(n(""),c(null),a(!0));let{parseChunk:g,buildPayload:w,onFinish:F,onError:U,...M}=x??{},d="",p;try{p=r.requestStream(E(k),M),l.current=p}catch(f){let P=Cr(f);S()&&(c(P),a(!1),x?.onError?.(P));return}try{for await(let f of p){if(m.current!==b)break;d+=T(f),S()&&n(d)}S()&&(a(!1),x?.onFinish?.(d))}catch(f){let P=Cr(f);S()&&(c(P),a(!1),x?.onError?.(P))}finally{l.current===p&&(l.current=null)}},[r]);return{completion:o,complete:C,stop:y,isStreaming:s,error:i}}var q=require("react");function xr(t){return t instanceof Error?t:new Error(String(t))}var Vn=t=>typeof t=="string"?t:String(t),Tr=0;function Kt(t){return Tr+=1,`${t}-${Tr}`}function Rr(t,e){let r=(0,q.useMemo)(()=>Ne(t),[t]),[o,n]=(0,q.useState)(()=>(e?.initialMessages??[]).map(T=>({id:T.id??Kt("msg"),role:T.role,content:T.content}))),[s,a]=(0,q.useState)(""),[i,c]=(0,q.useState)(!1),[u,m]=(0,q.useState)(null),l=(0,q.useRef)(e);l.current=e;let v=(0,q.useRef)(o);v.current=o;let y=(0,q.useRef)(s);y.current=s;let C=(0,q.useRef)(0),k=(0,q.useRef)(null),b=(0,q.useRef)(!0);(0,q.useEffect)(()=>(b.current=!0,()=>{b.current=!1,k.current?.cancel(),k.current=null}),[]);let S=(0,q.useCallback)(()=>{C.current++,k.current?.cancel(),k.current=null,b.current&&c(!1)},[]),x=(0,q.useCallback)(async T=>{let E=T===void 0,g=(E?y.current:T)??"";if(!g.trim())return;k.current?.cancel();let F=++C.current,U=()=>b.current&&C.current===F,M=l.current,d=M?.parseChunk??Vn,p={id:Kt("msg"),role:"user",content:g},f={id:Kt("msg"),role:"assistant",content:""},P=[...v.current,p].map(K=>({role:K.role,content:K.content})),L=[...v.current,p,f];v.current=L,n(L),E&&a(""),m(null),c(!0);let z=M?.buildPayload??(K=>({messages:K})),{initialMessages:A,parseChunk:h,buildPayload:V,onFinish:$,onError:X,...j}=M??{},me=K=>{n(ie=>ie.map(Te=>Te.id===f.id?{...Te,content:K}:Te))},fe="",se;try{se=r.requestStream(z(P),j),k.current=se}catch(K){let ie=xr(K);U()&&(m(ie),c(!1),M?.onError?.(ie));return}try{for await(let K of se){if(C.current!==F)break;fe+=d(K),U()&&me(fe)}U()&&(c(!1),M?.onFinish?.({...f,content:fe}))}catch(K){let ie=xr(K);U()&&(m(ie),c(!1),M?.onError?.(ie))}finally{k.current===se&&(k.current=null)}},[r]);return{messages:o,input:s,setInput:a,sendMessage:x,stop:S,isStreaming:i,error:u}}var O=require("react"),Ie=require("@urun-sh/core"),Jt=[];function Er(t,e={}){let{field:r=Ie.INPUT_PRESENCE_FIELD,hz:o=Ie.INPUT_PRESENCE_DEFAULT_HZ}=e,n=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null,s=t?.presence??null,a=(0,O.useMemo)(()=>s?(0,Ie.createInputPresencePublisher)({awareness:{setLocalStateField:(g,w)=>s.setField(g,w)},field:r,hz:o}):null,[s,r,o]),i=(0,O.useRef)(null);i.current=a;let[c,u]=(0,O.useState)(!1),[m,l]=(0,O.useState)(Jt),v=(0,O.useRef)(!1);(0,O.useEffect)(()=>{if(a)return()=>a.dispose()},[a]);let y=(0,O.useCallback)(()=>{let g=i.current;l(g?g.heldKeys():Jt)},[]),C=(0,O.useCallback)(()=>{i.current?.clear(),l(Jt)},[]);(0,O.useEffect)(()=>{if(!n)return;let g=()=>!!n.pointerLockElement,w=()=>{if(g()){v.current=!1,u(!0);return}v.current||(u(!1),C())},F=f=>{g()&&(i.current?.keyDown(f.key),y())},U=f=>{i.current?.keyUp(f.key),y()},M=f=>{g()&&i.current?.movePointer(f.movementX,f.movementY)},d=f=>{g()&&i.current?.setButtons(f.buttons)},p=()=>{C()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",F),n.addEventListener("keyup",U),n.addEventListener("mousemove",M),n.addEventListener("mousedown",d),n.addEventListener("mouseup",d),n.defaultView?.addEventListener("blur",p),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",F),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",M),n.removeEventListener("mousedown",d),n.removeEventListener("mouseup",d),n.defaultView?.removeEventListener("blur",p)}},[n,C,y]);let k=(0,O.useCallback)(g=>{g.requestPointerLock?.()},[]),b=(0,O.useCallback)(()=>{v.current=!0,u(!0)},[]),S=(0,O.useCallback)(()=>{v.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),C()},[n,C]),x=(0,O.useCallback)(g=>{i.current?.keyDown(g),y()},[y]),T=(0,O.useCallback)(g=>{i.current?.keyUp(g),y()},[y]),E=(0,O.useCallback)((g,w)=>{i.current?.movePointer(g,w)},[]);return{engage:k,engageTouch:b,release:S,engaged:c,heldKeys:m,pressKey:x,releaseKey:T,movePointer:E}}var wr=new Map;function Ar(t,e,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${t}"): schema must be a valid Zod schema`);wr.set(t,{component:e,schema:r})}function Ur(t,e){let r=wr.get(t);if(!r)return{error:`Unknown component: "${t}"`};let o=r.schema.safeParse(e);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${t}": ${o.error.message}`}}var be=require("react/jsx-runtime");function Mr({name:t,props:e,fallback:r}){let o=Ur(t,e);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,be.jsx)(be.Fragment,{children:r}):(0,be.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,be.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,be.jsx)(n,{...o.validatedProps})}var Le=require("zod"),Ce=require("react/jsx-runtime"),_r=Le.z.object({step:Le.z.number().min(0),total:Le.z.number().min(1),label:Le.z.string().optional(),variant:Le.z.enum(["default","success","error"]).default("default")});function zt(t){let{step:e,total:r,label:o,variant:n="default"}=t,s=Math.min(e/r*100,100),a=e>=r;return{step:e,total:r,label:o,variant:n,percentage:s,isComplete:a}}function Nr(t){let{step:e,total:r,label:o,variant:n,percentage:s}=zt(t);return(0,Ce.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Ce.jsx)("div",{className:"urun-progress-label",children:o}),(0,Ce.jsx)("div",{className:"urun-progress-bar",children:(0,Ce.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Ce.jsxs)("div",{className:"urun-progress-text",children:[e,"/",r]})]})}var dt=require("zod"),Je=require("react/jsx-runtime"),Ir=dt.z.object({state:dt.z.enum(["thinking","generating","idle","error"]),message:dt.z.string().optional()}),qn={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Xt(t){let{state:e,message:r}=t,o=e==="thinking"||e==="generating",n=r??qn[e]??e;return{state:e,message:n,isActive:o}}function Lr(t){let{state:e,message:r,isActive:o}=Xt(t);return(0,Je.jsxs)("span",{className:"urun-status-badge","data-state":e,children:[(0,Je.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,Je.jsx)("span",{className:"urun-status-message",children:r})]})}var ze=require("react"),pt=require("zod"),Xe=require("react/jsx-runtime"),Dr=pt.z.object({text:pt.z.string(),streaming:pt.z.boolean().default(!1)});function Gt(t){let{text:e,streaming:r=!1}=t,o=e.length===0;return{text:e,streaming:r,isEmpty:o}}function Or(t){let{text:e,streaming:r}=Gt(t),o=(0,ze.useRef)(null),n=(0,ze.useRef)(0);return(0,ze.useEffect)(()=>{let s=o.current;s&&e.length!==n.current&&(s.textContent=e,n.current=e.length)},[e]),(0,Xe.jsxs)("div",{className:"urun-text-stream",children:[(0,Xe.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Xe.jsx)("span",{className:"urun-text-cursor"})]})}var Ge=require("zod"),Ye=require("react/jsx-runtime"),Vr=Ge.z.object({src:Ge.z.string().url(),alt:Ge.z.string().optional(),caption:Ge.z.string().optional()});function Yt(t){let{src:e,alt:r,caption:o}=t;return{src:e,alt:r??"",caption:o}}function qr(t){let{src:e,alt:r,caption:o}=Yt(t);return(0,Ye.jsxs)("figure",{className:"urun-image-frame",children:[(0,Ye.jsx)("img",{className:"urun-image",src:e,alt:r}),o&&(0,Ye.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var ue=require("zod"),De=require("react/jsx-runtime"),Fr=ue.z.object({metrics:ue.z.array(ue.z.object({label:ue.z.string(),value:ue.z.union([ue.z.string(),ue.z.number()]),unit:ue.z.string().optional()}))});function Zt(t){return{metrics:t.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Wr(t){let{metrics:e}=Zt(t);return(0,De.jsx)("div",{className:"urun-metrics-panel",children:e.map((r,o)=>(0,De.jsxs)("div",{className:"urun-metric-card",children:[(0,De.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,De.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var mt=require("react"),$r=require("react/jsx-runtime"),Hr=(0,mt.createContext)(null);function Br({session:t,children:e}){return(0,$r.jsx)(Hr.Provider,{value:t,children:e})}function oe(){return(0,mt.useContext)(Hr)}var H=require("react");var St=require("react/jsx-runtime"),Fn=1e3;function Wn(...t){console.debug("[video]",...t)}var ft=(0,H.forwardRef)(function(e,r){let{session:o,stream:n="video",track:s,muted:a=!0,mirror:i=!1,objectFit:c="contain",className:u,style:m,videoClassName:l,placeholder:v,children:y,onTrack:C}=e,k=oe(),b=o??k,S=(0,H.useRef)(null),x=(0,H.useRef)(null),[T,E]=(0,H.useState)(!1),g=(0,H.useRef)(C);g.current=C;let w=(0,H.useCallback)(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let p=S.current;return p&&p.srcObject!==x.current&&(p.srcObject=x.current),x.current},[]),F=(0,H.useCallback)(p=>{let f=S.current;if(!f)return;let P=f.play();!P||typeof P.catch!="function"||P.catch(L=>Wn(`play() failed (${p})`,L))},[]),U=(0,H.useCallback)(p=>{let f=w();if(f){for(let P of f.getVideoTracks())P!==p&&f.removeTrack(P);if(p&&!f.getVideoTracks().includes(p)){f.addTrack(p);let P=S.current;P&&(P.srcObject=f)}p&&F("track-attach"),E(p!==null),g.current?.(p)}},[w,F]),M=(0,H.useCallback)(p=>{S.current=p,p&&(a&&(p.muted=!0,p.defaultMuted=!0,p.setAttribute("muted","")),p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),w())},[w,a]);(0,H.useImperativeHandle)(r,()=>({get element(){return S.current},get live(){return x.current?x.current.getVideoTracks().length>0:!1}}),[]);let d=s!==void 0;return(0,H.useEffect)(()=>{if(d){U(s??null);return}if(!b)return;let p=b.stream(n),f=()=>{let h=x.current;return h?h.getVideoTracks()[0]??null:null},P=h=>{if(h!==f()&&(U(h),h)){let V=()=>{f()===h&&U(null)};h.addEventListener("ended",V)}},L=p.track;L&&L.readyState==="live"&&P(L);let z=p.on("track",h=>{h&&h.readyState!=="live"||P(h)}),A=setInterval(()=>{let h=p.track;h&&h.readyState==="live"&&P(h)},Fn);return()=>{z(),clearInterval(A)}},[b,n,d,s,U]),(0,St.jsxs)("div",{className:u,style:{position:"relative",width:"100%",height:"100%",...m},"data-urun-video":"","data-urun-video-live":T?"true":"false",children:[(0,St.jsx)("video",{ref:M,className:l,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...i?{transform:"scaleX(-1)"}:{}}}),T?null:v,y]})});var jr=require("react");var Jr=require("react/jsx-runtime"),Kr=(0,jr.forwardRef)(function(e,r){let{stream:o="image",...n}=e;return(0,Jr.jsx)(ft,{ref:r,stream:o,...n})});var I=require("react"),Xr=require("@urun-sh/core");var gt=null;function Hn(){if(typeof window>"u")return null;let t=window;return t.AudioContext??t.webkitAudioContext??null}function Ze(){if(gt)return gt;let t=Hn();return t?(gt=new t,gt):null}function Qe(){let t=Ze();t&&t.state==="suspended"&&t.resume().catch(()=>{})}var Yr=require("react/jsx-runtime"),Bn=1e3,zr=200;function Qt(...t){console.debug("[audio]",...t)}var et=(0,I.forwardRef)(function(e,r){let{session:o,stream:n="audio",track:s,controls:a=!1,className:i,onTrack:c,onUnlockChange:u,onAudioElement:m}=e,l=oe(),v=o??l,y=(0,I.useRef)(null),C=(0,I.useRef)(null),k=(0,I.useRef)(null),b=(0,I.useRef)(null),S=(0,I.useRef)(c);S.current=c;let x=(0,I.useRef)(u);x.current=u;let T=(0,I.useCallback)(d=>{k.current!==d&&(k.current=d,x.current?.(d))},[]),E=(0,I.useCallback)(()=>{if(typeof MediaStream>"u")return null;C.current||(C.current=new MediaStream);let d=y.current;return d&&d.srcObject!==C.current&&(d.srcObject=C.current),C.current},[]),g=(0,I.useCallback)(d=>{let p=y.current;if(!p)return;let f=p.play();!f||typeof f.then!="function"||f.then(()=>{p.muted||T(!0)}).catch(P=>{let L=P instanceof Error?P.name:String(P);if(L==="AbortError"){Qt(`play() aborted (${d}); retrying in ${zr}ms`),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{b.current=null,g(`${d}:retry`)},zr);return}if(L==="NotAllowedError"){Qt(`play() blocked pending a user gesture (${d})`),T(!1);return}Qt(`play() failed (${d})`,P)})},[T]),w=(0,I.useCallback)(d=>{let p=E();if(p){for(let f of p.getAudioTracks())f!==d&&p.removeTrack(f);d&&!p.getAudioTracks().includes(d)&&p.addTrack(d),d&&g("track-attach"),S.current?.(d)}},[E,g]),F=(0,I.useCallback)(()=>{let d=y.current;d&&(E(),d.muted=!1,g("gesture"),Qe(),T(!0))},[E,g,T]);(0,I.useImperativeHandle)(r,()=>({unlock:F,get unlocked(){return k.current===!0},get element(){return y.current}}),[F]);let U=(0,I.useCallback)(d=>{y.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),E()),m?.(d)},[E,m]),M=s!==void 0;return(0,I.useEffect)(()=>{if(M){w(s??null);return}if(!v)return;let d=v.stream(n),p=()=>{let A=C.current;return A?A.getAudioTracks()[0]??null:null},f=A=>{if(A!==p()&&(w(A),A)){let h=()=>{p()===A&&w(null)};A.addEventListener("ended",h)}},P=d.track;P&&P.readyState==="live"&&f(P);let L=d.on("track",A=>{A&&A.readyState!=="live"||f(A)}),z=setInterval(()=>{let A=d.track;A&&A.readyState==="live"&&f(A)},Bn);return()=>{L(),clearInterval(z)}},[v,n,M,s,w]),(0,I.useEffect)(()=>(0,Xr.observePageLifecycle)(()=>{Qe(),k.current===!0&&g("foreground")}),[g]),(0,I.useEffect)(()=>()=>{b.current&&clearTimeout(b.current)},[]),(0,Yr.jsx)("audio",{ref:U,className:i,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})}),Gr=et;var N=require("react"),Oe=require("@urun-sh/core");var Qr=require("react/jsx-runtime"),er={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function ht(...t){console.debug("[voice]",...t)}var tt=(0,N.forwardRef)(function(e,r){let{session:o,stream:n="audio",playback:s=!0,constraints:a=er,connectTimeoutMs:i,attempts:c=3,retryDelayMs:u=1500,onActiveChange:m,onError:l,onMicStream:v,onTrack:y,onUnlockChange:C,capture:k}=e,b=oe(),S=o??b,x=(0,N.useRef)(null),T=(0,N.useRef)(null),E=(0,N.useRef)(null),g=(0,N.useRef)([]),w=(0,N.useRef)(!1),F=(0,N.useRef)(m);F.current=m;let U=(0,N.useRef)(l);U.current=l;let M=(0,N.useRef)(v);M.current=v;let d=(0,N.useCallback)(h=>{w.current!==h&&(w.current=h,F.current?.(h))},[]),p=(0,N.useCallback)(()=>{for(let h of g.current)h();g.current=[],E.current?.release(),E.current=null,T.current&&(T.current=null,M.current?.(null))},[]),f=(0,N.useCallback)(async()=>{let h=E.current;if(h){let j=await h.update(a);return T.current=h.stream,M.current?.(h.stream),j}let $=await(k??(0,Oe.sharedCaptureController)()).claim("audio",a);E.current=$,g.current=[$.onTrack((j,me)=>{T.current=me,M.current?.(me),w.current&&S?.stream(n).attach(j).catch(fe=>ht("mic re-attach after one-capture re-acquire failed",fe))}),$.onLost(j=>{E.current=null,g.current=[],T.current=null,M.current?.(null),d(!1),U.current?.(j)})],T.current=$.stream,M.current?.($.stream);let X=$.track;if(!X)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return X},[k,a,S,n,d]),P=(0,N.useCallback)(async()=>{p(),d(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,p,d]),L=(0,N.useCallback)(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <SessionScope>");x.current?.unlock();let h;try{h=await f()}catch(X){p();let j=(0,Oe.sessionFailureFromMediaError)(X,S.status);throw U.current?.(j),j}S.connect?.();let V;for(let X=1;X<=c;X++)try{await S.whenLive(i!==void 0?{timeout:i}:void 0),await S.stream(n).attach(h),d(!0);return}catch(j){V=j,ht(`start attempt ${X}/${c} failed`,j),X<c&&await new Promise(me=>setTimeout(me,u))}p(),d(!1);let $=V instanceof Error?V:new Error(String(V??"voice start failed"));throw U.current?.($),$},[S,n,i,c,u,f,p,d]);(0,N.useImperativeHandle)(r,()=>({start:L,stop:P,unlock:()=>x.current?.unlock(),get active(){return w.current},get micStream(){return T.current},get audio(){return x.current}}),[L,P]);let z=(0,N.useRef)(!1),A=(0,N.useCallback)(async()=>{if(!S||!w.current||z.current)return;let h=T.current?.getAudioTracks()[0]??null;if(h&&h.readyState==="live"){try{await S.stream(n).attach(h)}catch(V){ht("foreground mic re-assert failed (will retry on next pass)",V)}return}z.current=!0;try{let V=await f();await S.stream(n).attach(V)}catch(V){let $=V instanceof Error?V:new Error(String(V));ht("foreground mic re-acquire failed",$),U.current?.($)}finally{z.current=!1}},[S,n,f]);return(0,N.useEffect)(()=>{let h=()=>{A()};return S&&typeof S.onRecovery=="function"?S.onRecovery(h):(0,Oe.observePageLifecycle)(h)},[S,A]),(0,N.useEffect)(()=>p,[p]),s?(0,Qr.jsx)(et,{ref:x,session:S,stream:n,onTrack:y,onUnlockChange:C}):null}),Zr=tt;var re=require("react");var vt=require("react");var tr={level:0,speaking:!1};function yt(t,e={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=e,[s,a]=(0,vt.useState)(tr);return(0,vt.useEffect)(()=>{if(!t){a(tr);return}let i=Ze();if(!i||typeof MediaStream>"u")return;let c;t instanceof MediaStream?c=t:(c=new MediaStream,c.addTrack(t));let u,m;try{u=i.createMediaStreamSource(c),m=i.createAnalyser(),m.fftSize=r,u.connect(m)}catch{return}let l=new Uint8Array(m.fftSize),y=setInterval(()=>{m.getByteTimeDomainData(l);let C=0;for(let b=0;b<l.length;b++){let S=(l[b]-128)/128;C+=S*S}let k=Math.sqrt(C/l.length);a(b=>{let S=k>n;return Math.abs(b.level-k)<.005&&b.speaking===S?b:{level:k,speaking:S}})},o);return()=>{clearInterval(y),u.disconnect(),a(tr)}},[t,r,o,n]),s}var le=require("react/jsx-runtime"),$n={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},jn={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},en=(0,re.forwardRef)(function(e,r){let{session:o,stream:n="audio",constraints:s,autoStart:a=!0,visible:i=!1,className:c,onActiveChange:u,onError:m,onMicStream:l,capture:v}=e,y=oe(),C=o??y,k=(0,re.useRef)(null),[b,S]=(0,re.useState)(null),x=(0,re.useRef)(l);x.current=l;let{level:T,speaking:E}=yt(i?b:null);return(0,re.useImperativeHandle)(r,()=>({start:()=>{let g=k.current;return g?g.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>k.current?.stop()??Promise.resolve(),get active(){return k.current?.active??!1},get micStream(){return k.current?.micStream??null}}),[]),(0,re.useEffect)(()=>{!a||!C||k.current?.start().catch(()=>{})},[a,C]),(0,le.jsxs)(le.Fragment,{children:[(0,le.jsx)(tt,{ref:k,session:C,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...v!==void 0?{capture:v}:{},onActiveChange:u,onError:m,onMicStream:g=>{S(g),x.current?.(g)}}),i?(0,le.jsx)("span",{className:c,style:$n,"data-urun-mic":"","data-urun-mic-active":b?"true":"false","data-urun-mic-speaking":E?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(T*100)/100,children:(0,le.jsx)("span",{style:jn,children:(0,le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(T*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var kt=require("@urun-sh/core"),R=require("react");var Q=require("react/jsx-runtime"),nr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function rr(...t){console.debug("[camera]",...t)}function Kn(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Jn(){let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof t?.enumerateDevices!="function")return null;try{return(await t.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var or=(0,R.forwardRef)(function(e,r){let{session:o,stream:n="video",constraints:s,front:a=!1,back:i=!1,facingMode:c,autoStart:u=!0,mirror:m="auto",connectTimeoutMs:l,visible:v=!1,className:y,videoClassName:C,onActiveChange:k,onError:b,onStream:S,onTrack:x,children:T,capture:E,flipControl:g="auto",flipControlClassName:w,onDevices:F}=e;if(a&&i)throw new Error("<Camera> takes `front` OR `back`, not both");let U=a?"user":i?"environment":c??"environment",M=oe(),d=o??M,p=(0,R.useRef)(null),f=(0,R.useRef)(null),P=(0,R.useRef)(null),L=(0,R.useRef)([]),z=(0,R.useRef)(null),A=(0,R.useRef)(!1),h=(0,R.useRef)(U),[V,$]=(0,R.useState)(U),[X,j]=(0,R.useState)(!1),[me,fe]=(0,R.useState)(null),[se,K]=(0,R.useState)(!1),[ie]=(0,R.useState)(Kn),Te=(0,R.useRef)(k);Te.current=k;let st=(0,R.useRef)(b);st.current=b;let Vt=(0,R.useRef)(S);Vt.current=S;let it=(0,R.useRef)(x);it.current=x;let cr=(0,R.useRef)(F);cr.current=F;let Se=(0,R.useCallback)(_=>{A.current!==_&&(A.current=_,j(_),Te.current?.(_))},[]);(0,R.useEffect)(()=>{if(!X){fe(null);return}let _=!1,D=()=>{Jn().then(Y=>{_||(fe(Y),Y&&cr.current?.(Y))})};D();let J=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof J?.addEventListener=="function"?(J.addEventListener("devicechange",D),()=>{_=!0,J.removeEventListener?.("devicechange",D)}):()=>{_=!0}},[X]);let at=(0,R.useCallback)(_=>{let D=p.current;D&&(D.muted=!0,D.defaultMuted=!0,D.setAttribute("muted",""),D.setAttribute("playsinline",""),D.setAttribute("webkit-playsinline",""),D.srcObject=_,_&&D.play()?.catch?.(J=>rr("preview play() failed",J)))},[]),ae=(0,R.useCallback)(()=>{z.current?.(),z.current=null;for(let _ of L.current)_();L.current=[],P.current?.release(),P.current=null,f.current&&(f.current=null,Vt.current?.(null),it.current?.(null)),at(null)},[at]),qt=(0,R.useCallback)((_,D)=>{z.current?.(),f.current=D,at(D),Vt.current?.(D);let J=()=>{f.current===D&&(rr("camera track ended (device removed or permission revoked)"),ae(),Se(!1))};_.addEventListener("ended",J),z.current=()=>_.removeEventListener("ended",J)},[at,ae,Se]),Re=(0,R.useCallback)(async _=>{if(!d)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <SessionScope>");let D={...nr,...s,facingMode:_},J;try{let Y=P.current;if(Y)J=await Y.update(D);else{let Be=await(E??(0,kt.sharedCaptureController)()).claim("video",D);if(P.current=Be,L.current=[Be.onTrack(($e,Rn)=>{qt($e,Rn),A.current&&d.stream(n).attachVideo($e).then(()=>it.current?.($e)).catch(En=>rr("camera re-publish after one-capture re-acquire failed",En))}),Be.onLost($e=>{P.current=null,L.current=[],ae(),Se(!1),st.current?.($e)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});J=Be.track}}catch(Y){let Ee=(0,kt.sessionFailureFromMediaError)(Y,d.status);throw st.current?.(Ee),Ee}h.current=_,$(_),qt(J,P.current?.stream??new MediaStream([J]));try{d.connect?.(),await d.whenLive(l!==void 0?{timeout:l}:void 0),await d.stream(n).attachVideo(J)}catch(Y){ae(),Se(!1);let Ee=Y instanceof Error?Y:new Error(String(Y));throw st.current?.(Ee),Ee}it.current?.(J),Se(!0)},[d,n,s,l,E,qt,ae,Se]),ur=(0,R.useCallback)(_=>Re(_?.facingMode??h.current),[Re]),ct=(0,R.useCallback)(async _=>{A.current&&h.current===_||await Re(_)},[Re]),Ft=(0,R.useCallback)(()=>Re(h.current==="environment"?"user":"environment"),[Re]),lr=(0,R.useCallback)(async()=>{ae(),Se(!1),await d?.stream(n).detachVideo().catch(()=>{})},[d,n,ae,Se]);(0,R.useImperativeHandle)(r,()=>({start:ur,stop:lr,flip:Ft,setFacingMode:ct,get active(){return A.current},get facingMode(){return h.current},get stream(){return f.current},get element(){return p.current}}),[ur,lr,Ft,ct]);let dr=(0,R.useRef)(ct);if(dr.current=ct,(0,R.useEffect)(()=>{!u||!d||dr.current(U).catch(()=>{})},[u,d,U]),(0,R.useEffect)(()=>ae,[ae]),!v)return null;let Pn=m==="auto"?V==="user":m,xn=X&&(g===!0||g==="auto"&&ie&&(me?.length??0)>1),Tn=()=>{se||(K(!0),Ft().catch(()=>{}).finally(()=>K(!1)))};return(0,Q.jsxs)("div",{className:y,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":V,children:[(0,Q.jsx)("video",{ref:p,className:C,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Pn?{transform:"scaleX(-1)"}:{}}}),xn?(0,Q.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Tn,disabled:se,className:w,style:w?{opacity:se?.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:se?.6:1},children:(0,Q.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,Q.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,Q.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,Q.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,Q.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,Q.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,T]})}),tn=(0,R.forwardRef)(function({preview:e=!0,...r},o){return(0,Q.jsx)(or,{ref:o,...r,visible:e,autoStart:!1})});var bt=require("react");function rn(t,e){let[r,o]=(0,bt.useState)(null);return(0,bt.useEffect)(()=>{if(!t||!e){o(null);return}let n=t.stream(e);return o(n.track),n.on("track",o)},[t,e]),r}var sn=require("react");var Pt=require("react");var nn=require("zustand/vanilla"),on=require("zustand"),zn=()=>{};function Ct(t,e={}){let r=u=>{t?.set(u)},o=()=>t?t.get()??{}:{},n=(0,nn.createStore)(()=>({doc:o(),synced:t?t.synced:!1,set:r})),s=null,a=()=>{if(s){for(let u of s)u();s=null}},i=()=>t?(s||(n.setState({doc:o(),synced:t.synced}),s=[t.on("change",u=>n.setState({doc:u})),t.onSynced(()=>n.setState({synced:!0}))]),a):zn,c=(u=>(0,on.useStore)(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:i,unbind:a}),e.bind!==!1&&i(),c}function Ve(t,e){let r=(0,Pt.useMemo)(()=>Ct(t&&e?t.doc(e):null,{bind:!1}),[t,e]);return(0,Pt.useEffect)(()=>r.bind(),[r]),r}function an(t,e,r){let n=Ve(t,e)(r??(i=>i)),s=(0,sn.useCallback)(i=>{t&&e&&t.doc(e).set(i)},[t,e]);if(r)return n;let a=n;return{snapshot:t&&e?a.doc:null,synced:a.synced,set:s}}var Tt=require("react");var ge=200;function de(t,e,r=200){let o=[...t,e];return o.length>r?o.slice(o.length-r):o}function qe(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function xt(t){let e=t.trim();if(!e)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(e)}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 Rt(t,e,r={}){let o=r.cap??200,[n,s]=(0,Tt.useState)([]);return(0,Tt.useEffect)(()=>{if(s([]),!t||!e)return;let a=!0,i=t.stream(e).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await i.next();if(!a||c.done)break;s(u=>de(u,{at:Date.now(),payload:c.value},o))}})(),()=>{a=!1,i.return?.()}},[t,e,o]),n}var ne=require("react/jsx-runtime");function cn({session:t,name:e,cap:r,className:o}){let n=Rt(t,e,{cap:r});return(0,ne.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,ne.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,ne.jsx)("code",{children:e}),(0,ne.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,ne.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,ne.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,ne.jsx)("code",{children:e})," messages\u2026"]}):n.map((s,a)=>(0,ne.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,ne.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",qe(s.payload)]},`${s.at}-${a}`))})]})}var rt=require("react");var G=require("react/jsx-runtime");function nt({placeholder:t,buttonLabel:e,disabled:r,onApply:o}){let[n,s]=(0,rt.useState)(""),[a,i]=(0,rt.useState)(null),c=(0,rt.useCallback)(()=>{let u=xt(n);if(!u.ok){i(u.error);return}i(null),o(u.value,n.trim()),s("")},[n,o]);return(0,G.jsxs)("div",{className:"urun-doc-patch",children:[(0,G.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:t,rows:3}),(0,G.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,G.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:e}),a?(0,G.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function un({session:t,docKey:e,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ve(t,e),a=s(u=>u.doc),i=s(u=>u.synced),c=s(u=>u.set);return(0,G.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,G.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,G.jsx)("code",{children:e}),(0,G.jsx)("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),(0,G.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),r?(0,G.jsx)(nt,{placeholder:o,buttonLabel:"Apply patch",disabled:!t,onApply:u=>c(u)}):null]})}var Et=require("react");var pe=require("react/jsx-runtime");function ln(t,e=600){return t.length>e?`${t.slice(0,e)}\u2026`:t}function dn({session:t,docKey:e="control",cap:r=200,className:o}){let[n,s]=(0,Et.useState)([]);return(0,Et.useEffect)(()=>(s([]),t?t.doc(e).on("change",i=>{s(c=>de(c,{at:Date.now(),direction:"in",text:ln(qe(i))},r))}):void 0),[t,e,r]),(0,pe.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,pe.jsx)(nt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${e}`,disabled:!t,onApply:(a,i)=>{t?.doc(e).set(a),s(c=>de(c,{at:Date.now(),direction:"out",text:ln(i)},r))}}),(0,pe.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,pe.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((a,i)=>(0,pe.jsxs)("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[(0,pe.jsx)("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",(0,pe.jsx)("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${i}`))})]})}var wt=require("react");var Pe=require("react/jsx-runtime");function pn({session:t,trackNames:e=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,a]=(0,wt.useState)([]),i=e.join(","),c=r.join(",");return(0,wt.useEffect)(()=>{if(a([]),!t)return;let u=(l,v)=>a(y=>de(y,{at:Date.now(),kind:l,text:v},o)),m=[];m.push(t.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of e){let v=t.stream(l);m.push(v.on("track",y=>u("track",`${l}: ${y?"track arrived":"track ended"}`)))}for(let l of r){let v=t.doc(l);m.push(v.on("change",()=>u("doc",`${l} changed`)))}return()=>m.forEach(l=>l())},[t,i,c,o]),(0,Pe.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Pe.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,Pe.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,Pe.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,Pe.jsx)("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${m}`))})}var Lt=require("@urun-sh/core");var At=require("react");function ee(t){let[e,r]=(0,At.useState)(t?.phase??null);return(0,At.useEffect)(()=>{if(!t){r(null);return}return t.onPhase(r)},[t]),e}var fn=require("@urun-sh/core");var Fe=require("react"),mn=require("@urun-sh/core");function Ut(t){let e=ee(t),r=(0,mn.isWakingPhase)(e?.name),o=(0,Fe.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?e?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[a,i]=(0,Fe.useState)(s);return(0,Fe.useEffect)(()=>{if(n===void 0){i(0);return}i(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{i(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:e,state:r?e?.runtime?.state:void 0,reason:r?e?.runtime?.reason:void 0,since:n,seconds:r?a:0}}var he=require("react/jsx-runtime");function Mt({session:t,render:e,className:r}){let o=Ut(t);return!o.waking||!o.phase?null:(0,he.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:e?e(o):(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)("span",{className:"urun-session-waking-label",children:(0,fn.describeSessionPhase)(o.phase)})," ",(0,he.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Nt=require("react");var ve=require("react"),Xn={event:null,elapsedMs:0};function _t(t,e){let[r,o]=(0,ve.useState)(null),n=(0,ve.useRef)(0);(0,ve.useEffect)(()=>{if(o(null),!!t?.onActivation)return t.onActivation(i=>{e!==void 0&&i.stream!==e||(n.current=Date.now(),o(i))})},[t,e]);let[s,a]=(0,ve.useState)(0);return(0,ve.useEffect)(()=>{if(!r){a(0);return}if(r.state==="first-media"){a(r.elapsedMs);return}let i=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-i);a(c());let u=setInterval(()=>a(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:Xn}var We=require("react/jsx-runtime"),Gn={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 Yn(t){let[e,r]=(0,Nt.useState)(!1);return(0,Nt.useEffect)(()=>{if(r(!1),!t)return;let o=t;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)}},[t]),e}function It({session:t,stream:e,videoElement:r,render:o,className:n}){let s=_t(t,e),a=Yn(r),i=s.event;if(!i||i.state==="first-media"||a)return null;let c=i.state;return(0,We.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):(0,We.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,We.jsx)("span",{className:"urun-activation-overlay-copy",children:i.hint??Gn[c]})," ",(0,We.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var te=require("react/jsx-runtime"),Zn={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Sn({session:t,className:e}){let r=ee(t),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime?.reason??null;return(0,te.jsxs)("span",{className:["urun-session-status",e].filter(Boolean).join(" "),"data-phase":o,children:[(0,te.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,te.jsx)("span",{className:"urun-session-status-label",children:Zn[o]}),n?(0,te.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function gn({session:t,children:e,fallback:r,onStartOver:o,className:n}){let s=ee(t);if(s?.name==="live")return(0,te.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[e,(0,te.jsx)(It,{session:t})]});let a=r?r(s):(0,te.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,Lt.isWakingPhase)(s.name)?(0,te.jsx)(Mt,{session:t}):s&&s.name!=="idle"?(0,Lt.describeSessionPhase)(s):"Waiting for a live session\u2026"}),i=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,te.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[a,i?(0,te.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var Dt=require("react");var vn=require("react/jsx-runtime");function sr(t){return ee(t)?.endsAt??null}function Qn(t){let e=Math.max(0,Math.floor(t/1e3)),r=Math.floor(e/60),o=e%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function hn({session:t,urgentMs:e=6e4,className:r}){let n=sr(t)?.getTime()??null,[s,a]=(0,Dt.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,Dt.useEffect)(()=>{if(n===null){a(null);return}let c=()=>a(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let i=Qn(s);return(0,vn.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${i}`,"data-urgent":s<e?"":void 0,"data-expired":s<=0?"":void 0,children:i})}var ot=require("react/jsx-runtime"),eo=new Set(["expired","ended","error"]);function yn({session:t,onNewSession:e,children:r,className:o}){let n=ee(t);if(!n||!eo.has(n.name))return null;let s=r?r(n):(0,ot.jsx)("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return(0,ot.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,e?(0,ot.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:e,children:"New session"}):null]})}var ye=require("react"),xe=require("react/jsx-runtime");function ir(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.warning!==!0?null:{warning:!0,deadlineEpochS:typeof e.deadline_epoch_s=="number"?e.deadline_epoch_s:null,idleSinceEpochS:typeof e.idle_since_epoch_s=="number"?e.idle_since_epoch_s:null}}function ar(t){let e=(0,ye.useMemo)(()=>t?t.doc("control"):null,[t]),[r,o]=(0,ye.useState)(()=>e?ir(e.get("idle")):null);return(0,ye.useEffect)(()=>{if(!e){o(null);return}return o(ir(e.get("idle"))),e.on("change",()=>o(ir(e.get("idle"))))},[e]),r}function to(t){let e=Math.max(0,Math.floor(t));return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function kn({session:t,onStillHere:e,className:r}){let o=ar(t),n=o?.deadlineEpochS??null,[s,a]=(0,ye.useState)(null);if((0,ye.useEffect)(()=>{if(n===null){a(null);return}let c=()=>a(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!t)return null;let i=()=>{t.touch?.(),e?.()};return(0,xe.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,xe.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,xe.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,xe.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${to(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,xe.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:i,children:"I'm still here"})]})})}var He=require("react"),bn=require("@urun-sh/core");function Cn(t){let e=(0,He.useContext)(Ae),[r,o]=(0,He.useState)(null),n=t.app??e?.appId,s=t.function,a=t.intervalS??60,i=e?.baseUrl,c=e?.orgId,u=e?.jwt,m=e?.getAccessToken,l=e?.authProvider;return(0,He.useEffect)(()=>{if(!i||!c||!n||!s)return;let v=!1,y=()=>{(0,bn.prewake)({baseUrl:i,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:m,authProvider:l}).then(k=>{v||o(k)}).catch(()=>{})};y();let C=setInterval(y,Math.max(1,a)*1e3);return()=>{v=!0,clearInterval(C)}},[n,s,a,i,c,u,m,l]),r}var Ot=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,ProgressCard,ProgressCardSchema,SessionScope,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useProgressCard,useRequest,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});