@urun-sh/react 0.2.28 → 0.2.29

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/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.29
4
+
5
+ - **`useApp()` render-safety hardened to full reference stability** (owner contract
6
+ 2026-07-16: "the app from useApp is supposed to come back render safe automatically";
7
+ rolling-sink PR #7 finding). `app.<fn>` is now the **same function reference** on every
8
+ property access and every re-render (bound proxy methods are cached per function name and
9
+ reset exactly when the provider config changes). Session reference stability
10
+ (same handle across calls/re-renders; new reference only after disconnect/end) was already
11
+ guaranteed and is now pinned by `use-app-identity.test.tsx`.
12
+ - **React Compiler compatibility grounded and pinned.** The `react-hooks/purity`
13
+ misclassification of event handlers (Date.now() rejected as render-scope with the
14
+ unmemoized one-liner) is NOT an identity bug: the compiler freezes only values flowing
15
+ through hook-*named* calls (`/^use[A-Z0-9]/`). Canonical zero-memoization composition:
16
+ read the session through a hook you want anyway (`useSessionPhase(session)`), which
17
+ freezes it for the compiler; writing handlers with impure stamps then lint clean under
18
+ the default create-next-app config. Both sides pinned by lint fixtures in
19
+ `react-compiler-lint.test.ts` (canonical composition = clean; unhooked
20
+ single-component write boundary = still rejected, flips loudly on plugin upgrades).
21
+ - `useApp()` JSDoc + README now document the identity contract and the compiler note.
22
+
3
23
  ## 0.2.24
4
24
 
5
25
  - Docs-only release: README accuracy pass against the 0.2.23+ surface — the quick start now
package/README.md CHANGED
@@ -46,7 +46,21 @@ export default function App() {
46
46
  }
47
47
  ```
48
48
 
49
- `useApp()` is render-safe: repeated `app.generate(args)` calls during React re-renders reuse the same session for the same function and args.
49
+ `useApp()` is render-safe with zero user-side memoization: `app` is the same proxy across
50
+ re-renders, `app.generate` is the same function reference on every access, and repeated
51
+ `app.generate(args)` calls during React re-renders return the **same session reference** for the
52
+ same function and args (a new reference appears only after the session actually changed, i.e. it
53
+ was disconnected/ended and the next call dials fresh). Treat `app.<function>()` like a hook: call
54
+ it unconditionally during render and let it own the session lifecycle.
55
+
56
+ **React Compiler note** (default Next lint, `react-hooks/purity`): the compiler only freezes
57
+ values that flow through hook-*named* calls. If nothing hook-shaped touches the session, an event
58
+ handler in the same component that both writes through it (`session.doc(...).set(...)`) and calls
59
+ an impure function (`Date.now()`, `Math.random()`) is conservatively flagged as render-scope.
60
+ Keep it compiler-clean without memoization by reading the session through a hook you want anyway —
61
+ e.g. `const phase = useSessionPhase(session)` for the wake/status UI — which freezes the session
62
+ for the compiler. This contract is pinned by the fixtures in
63
+ `src/__tests__/react-compiler-lint.test.ts`.
50
64
 
51
65
  > Drive the app by writing **desired state** into the control doc (`doc('control').set({ desired: … })`),
52
66
  > not an imperative `start/update/stop`. The Python runtime reads cheap config inline from the live
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client"
2
- "use strict";var Bt=Object.defineProperty;var Dn=Object.getOwnPropertyDescriptor;var Vn=Object.getOwnPropertyNames;var qn=Object.prototype.hasOwnProperty;var Fn=(e,t)=>{for(var r in t)Bt(e,r,{get:t[r],enumerable:!0})},Hn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vn(t))!qn.call(e,n)&&n!==r&&Bt(e,n,{get:()=>t[n],enumerable:!(o=Dn(t,n))||o.enumerable});return e};var Wn=e=>Hn(Bt({},"__esModule",{value:!0}),e);var So={};Fn(So,{Audio:()=>rt,Camera:()=>ur,ComponentRenderer:()=>Fr,DEFAULT_CAMERA_CONSTRAINTS:()=>ar,DEFAULT_LOG_CAP:()=>ve,DEFAULT_VOICE_CONSTRAINTS:()=>or,DocPatchForm:()=>st,Image:()=>tn,ImageFrame:()=>zr,ImageFrameSchema:()=>Jr,MetricsPanel:()=>Gr,MetricsPanelSchema:()=>Xr,Mic:()=>ln,OPERATOR_CHORD_LABEL:()=>Tr,OPERATOR_TOKEN_STORAGE_KEY:()=>Cr,ProgressCard:()=>Wr,ProgressCardSchema:()=>Hr,Session:()=>Yr,StatusBadge:()=>$r,StatusBadgeSchema:()=>Br,TextStream:()=>jr,TextStreamSchema:()=>Kr,UrunActivationOverlay:()=>Lt,UrunAudio:()=>sn,UrunAuthProvider:()=>$t,UrunCamera:()=>dn,UrunControlSender:()=>kn,UrunDocPanel:()=>vn,UrunErrorBoundary:()=>Me,UrunEventSpine:()=>bn,UrunIdleWarning:()=>An,UrunJwtProvider:()=>kr,UrunProvider:()=>wr,UrunSessionClock:()=>En,UrunSessionEnded:()=>Rn,UrunSessionGate:()=>Tn,UrunSessionStatus:()=>xn,UrunSessionWaking:()=>Nt,UrunStreamTail:()=>hn,UrunVoice:()=>un,Video:()=>St,Voice:()=>nt,authMode:()=>Je,createDocStore:()=>xt,describeSessionPhase:()=>qt.describeSessionPhase,formatPayload:()=>Fe,getUrunAudioContext:()=>et,isWakingPhase:()=>qt.isWakingPhase,parseJsonObject:()=>Et,pushCapped:()=>fe,readOperatorToken:()=>Kt,registerComponent:()=>Vr,resumeUrunAudioContext:()=>tt,urunPublicEnv:()=>de,useActivation:()=>It,useApp:()=>Ar,useChat:()=>Or,useCompletion:()=>_r,useDocStore:()=>qe,useImageFrame:()=>er,useInputPresence:()=>Lr,useMetricsPanel:()=>tr,useOperatorOverride:()=>mt,useProgressCard:()=>Yt,useRequest:()=>Ur,useSession:()=>Zr,useSessionDoc:()=>Sn,useSessionEndsAt:()=>cr,useSessionIdle:()=>dr,useSessionPhase:()=>oe,useSessionTrack:()=>pn,useSessionWake:()=>_t,useStatusBadge:()=>Zt,useStreamMessages:()=>Rt,useTextStream:()=>Qt,useUrunAudioLevel:()=>bt,useUrunAuth:()=>dt,useUrunPrewake:()=>Mn,usesWorkOSAuth:()=>vr});module.exports=Wn(So);var ue=require("react");var Sr=require("react"),je=require("react/jsx-runtime"),Me=class extends Sr.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,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 hr=require("react"),_e=(0,hr.createContext)(null);function Pe(e){return e&&e.trim()?e.trim():void 0}function de(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return Pe(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Pe(typeof process<"u"?process.env?.[e]:void 0)}}function Je(){let e=de("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||de("VERCEL_ENV")==="production"?"workos":de("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function vr(){return Je()==="workos"}var Ne=require("react"),br=require("react/jsx-runtime"),yr=(0,Ne.createContext)(null);function $t({getAccessToken:e,children:t}){let r=(0,Ne.useMemo)(()=>({getAccessToken:e}),[e]);return(0,br.jsx)(yr.Provider,{value:r,children:t})}var kr=$t;function dt(){return(0,Ne.useContext)(yr)}var pt=require("react"),Cr="urun.operator_token",xr=null,Pr="op",Tr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Er(){return typeof window<"u"}function Kt(){return xr}function Bn(){if(!Er())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Pr);if(!r)return null;xr=r,t.delete(Pr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function $n(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function mt(e){let t=(0,pt.useRef)(e);t.current=e,(0,pt.useEffect)(()=>{if(!Er())return;Bn();let r=o=>{if(!$n(o))return;let n=Kt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var he=require("react/jsx-runtime"),Kn="/api/urun-token";function jn(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,he.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,he.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,he.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function wr({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:a,sessionKey:i,tokenEndpoint:c,fallback:u,errorFallback:g,children:p}){let d=n===void 0&&t===void 0;if(!d&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!d&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let k=r??o;if(d&&(typeof k!="string"||k.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);let[x,b]=(0,ue.useState)(),[y,S]=(0,ue.useState)(),[E,C]=(0,ue.useState)(null),[w,h]=(0,ue.useState)(null);mt(K=>h({jwt:K}));let R=dt(),D=de("NEXT_PUBLIC_SESSION_TOKEN")??de("NEXT_PUBLIC_URUN_JWT"),M=Je(),U=w!==null,l=M==="workos"&&!n&&!U&&!d,m=n??(M==="jwt"?D:void 0)??x??y?.token,f=U?w.jwt:m,P=s??de("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),I=l&&!f,J=t??y?.orgId,A=e??y?.gatewayUrl,v=d&&y===void 0,L=d&&y!==void 0&&!A?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,$=E??L,G=(0,ue.useMemo)(()=>({appId:k,baseUrl:A??"",orgId:J??"",jwt:f,getAccessToken:l?R?.getAccessToken:void 0,authProvider:P,eventsUrl:a,sessionKey:i,priority:U?"preempt":void 0}),[k,R,A,P,f,a,J,i,l,U]),V=c??Kn;return(0,ue.useEffect)(()=>{if(!d)return;let K=new AbortController;return C(null),(async()=>{try{let j=await fetch(V,{method:"POST",signal:K.signal});if(!j.ok)throw new Error(`[urun] token endpoint ${V} answered ${j.status}`);let W=await j.json(),q=typeof W.token=="string"?W.token:"",Q=typeof W.orgId=="string"?W.orgId:"";if(!q||!Q)throw new Error(`[urun] token endpoint ${V} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);S({token:q,orgId:Q,gatewayUrl:typeof W.gatewayUrl=="string"?W.gatewayUrl:void 0})}catch(j){if(K.signal.aborted)return;C(j instanceof Error?j:new Error(String(j)))}})(),()=>K.abort()},[d,V]),(0,ue.useEffect)(()=>{if(!l||!R)return;let K=!1,j=R;async function W(){try{let Q=await j.getAccessToken();K||b(Q??void 0)}catch{K||b(void 0)}}W();let q=window.setInterval(()=>{W()},6e4);return()=>{K=!0,window.clearInterval(q)}},[R,l]),(0,he.jsx)(Me,{fallback:u,children:$?jn(g,$):I||v?(0,he.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,he.jsx)(_e.Provider,{value:G,children:p})})}var ee=require("react"),Rr=require("@urun-sh/core");function Jn(e,t){return`${e}:${JSON.stringify(t??{})}`}function zn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var Ce=new Map;var jt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,a=>{s(a),o()})}}dispose(){this._unsubscribeChange()}},Jt=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},zt=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=i=>{fetch(t,{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(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new jt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Jt(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Ar(){let e=(0,ee.useContext)(_e);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,ee.useReducer)(a=>a+1,0),r=(0,ee.useRef)(new Map),o=(0,ee.useRef)(new Map),n=(0,ee.useRef)(null),s=(0,ee.useMemo)(()=>(0,Rr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.priority]);return(0,ee.useEffect)(()=>{let a=n.current;if(a){n.current=null;for(let[i,c]of a){let u=Ce.get(i);u===c&&o.current.get(i)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let i=new Map;for(let[c,u]of o.current){let g=Ce.get(c);g===u&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),i.set(c,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let p=Ce.get(c);!p||p.refCount!==0||(Ce.delete(c),p.handle.disconnect())},0)))}n.current=i}},[]),(0,ee.useMemo)(()=>new Proxy({},{get(a,i){if(typeof i=="string")return c=>{let u=Jn(i,c),g=r.current.get(u);if(g&&!g.disposed)return g;let p=zn(e,i,c),d=Ce.get(p);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),Ce.delete(p),o.current.get(p)===d&&o.current.delete(p),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new zt(s[i](c),t,e.eventsUrl),refCount:0,disposeTimer:null},Ce.set(p,d)),o.current.get(p)!==d&&(o.current.set(p,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(u,d.handle),d.handle}}}),[e,s])}var z=require("react");function Ie(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Xn(e){return e instanceof Error?e:new Error(String(e))}function Ur(e,t){let r=(0,z.useMemo)(()=>Ie(e),[e]),[o,n]=(0,z.useState)(void 0),[s,a]=(0,z.useState)(null),[i,c]=(0,z.useState)(!1),u=(0,z.useRef)(t);u.current=t;let g=(0,z.useRef)(0),p=(0,z.useRef)(null),d=(0,z.useRef)(!0);(0,z.useEffect)(()=>(d.current=!0,()=>{d.current=!1,p.current?.abort()}),[]);let k=(0,z.useCallback)(async y=>{p.current?.abort();let S=new AbortController;p.current=S;let E=++g.current,C=()=>d.current&&g.current===E;C()&&(c(!0),a(null));try{let w=await r.request(y,{...u.current,signal:S.signal});return C()&&(n(w),c(!1),u.current?.onSuccess?.(w)),w}catch(w){let h=Xn(w);throw C()&&(a(h),c(!1),u.current?.onError?.(h)),h}},[r]),x=(0,z.useCallback)(y=>{k(y).catch(()=>{})},[k]),b=(0,z.useCallback)(()=>{g.current++,p.current?.abort(),p.current=null,n(void 0),a(null),c(!1)},[]);return{mutate:x,mutateAsync:k,data:o,error:s,isPending:i,reset:b}}var Y=require("react");function Mr(e){return e instanceof Error?e:new Error(String(e))}var Gn=e=>typeof e=="string"?e:String(e);function _r(e,t){let r=(0,Y.useMemo)(()=>Ie(e),[e]),[o,n]=(0,Y.useState)(""),[s,a]=(0,Y.useState)(!1),[i,c]=(0,Y.useState)(null),u=(0,Y.useRef)(t);u.current=t;let g=(0,Y.useRef)(0),p=(0,Y.useRef)(null),d=(0,Y.useRef)(!0);(0,Y.useEffect)(()=>(d.current=!0,()=>{d.current=!1,p.current?.cancel(),p.current=null}),[]);let k=(0,Y.useCallback)(()=>{g.current++,p.current?.cancel(),p.current=null,d.current&&a(!1)},[]),x=(0,Y.useCallback)(async b=>{p.current?.cancel();let y=++g.current,S=()=>d.current&&g.current===y,E=u.current,C=E?.parseChunk??Gn,w=E?.buildPayload??(f=>({prompt:f}));S()&&(n(""),c(null),a(!0));let{parseChunk:h,buildPayload:R,onFinish:D,onError:M,...U}=E??{},l="",m;try{m=r.requestStream(w(b),U),p.current=m}catch(f){let P=Mr(f);S()&&(c(P),a(!1),E?.onError?.(P));return}try{for await(let f of m){if(g.current!==y)break;l+=C(f),S()&&n(l)}S()&&(a(!1),E?.onFinish?.(l))}catch(f){let P=Mr(f);S()&&(c(P),a(!1),E?.onError?.(P))}finally{p.current===m&&(p.current=null)}},[r]);return{completion:o,complete:x,stop:k,isStreaming:s,error:i}}var B=require("react");function Nr(e){return e instanceof Error?e:new Error(String(e))}var Yn=e=>typeof e=="string"?e:String(e),Ir=0;function Xt(e){return Ir+=1,`${e}-${Ir}`}function Or(e,t){let r=(0,B.useMemo)(()=>Ie(e),[e]),[o,n]=(0,B.useState)(()=>(t?.initialMessages??[]).map(C=>({id:C.id??Xt("msg"),role:C.role,content:C.content}))),[s,a]=(0,B.useState)(""),[i,c]=(0,B.useState)(!1),[u,g]=(0,B.useState)(null),p=(0,B.useRef)(t);p.current=t;let d=(0,B.useRef)(o);d.current=o;let k=(0,B.useRef)(s);k.current=s;let x=(0,B.useRef)(0),b=(0,B.useRef)(null),y=(0,B.useRef)(!0);(0,B.useEffect)(()=>(y.current=!0,()=>{y.current=!1,b.current?.cancel(),b.current=null}),[]);let S=(0,B.useCallback)(()=>{x.current++,b.current?.cancel(),b.current=null,y.current&&c(!1)},[]),E=(0,B.useCallback)(async C=>{let w=C===void 0,h=(w?k.current:C)??"";if(!h.trim())return;b.current?.cancel();let D=++x.current,M=()=>y.current&&x.current===D,U=p.current,l=U?.parseChunk??Yn,m={id:Xt("msg"),role:"user",content:h},f={id:Xt("msg"),role:"assistant",content:""},P=[...d.current,m].map(q=>({role:q.role,content:q.content})),I=[...d.current,m,f];d.current=I,n(I),w&&a(""),g(null),c(!0);let J=U?.buildPayload??(q=>({messages:q})),{initialMessages:A,parseChunk:v,buildPayload:L,onFinish:$,onError:G,...V}=U??{},K=q=>{n(Q=>Q.map(Re=>Re.id===f.id?{...Re,content:q}:Re))},j="",W;try{W=r.requestStream(J(P),V),b.current=W}catch(q){let Q=Nr(q);M()&&(g(Q),c(!1),U?.onError?.(Q));return}try{for await(let q of W){if(x.current!==D)break;j+=l(q),M()&&K(j)}M()&&(c(!1),U?.onFinish?.({...f,content:j}))}catch(q){let Q=Nr(q);M()&&(g(Q),c(!1),U?.onError?.(Q))}finally{b.current===W&&(b.current=null)}},[r]);return{messages:o,input:s,setInput:a,sendMessage:E,stop:S,isStreaming:i,error:u}}var H=require("react"),Oe=require("@urun-sh/core"),Gt=[];function Lr(e,t={}){let{field:r=Oe.INPUT_PRESENCE_FIELD,hz:o=Oe.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,a=(0,H.useMemo)(()=>s?(0,Oe.createInputPresencePublisher)({awareness:{setLocalStateField:(h,R)=>s.setField(h,R)},field:r,hz:o}):null,[s,r,o]),i=(0,H.useRef)(null);i.current=a;let[c,u]=(0,H.useState)(!1),[g,p]=(0,H.useState)(Gt),d=(0,H.useRef)(!1);(0,H.useEffect)(()=>{if(a)return()=>a.dispose()},[a]);let k=(0,H.useCallback)(()=>{let h=i.current;p(h?h.heldKeys():Gt)},[]),x=(0,H.useCallback)(()=>{i.current?.clear(),p(Gt)},[]);(0,H.useEffect)(()=>{if(!n)return;let h=()=>!!n.pointerLockElement,R=()=>{if(h()){d.current=!1,u(!0);return}d.current||(u(!1),x())},D=f=>{h()&&(i.current?.keyDown(f.key),k())},M=f=>{i.current?.keyUp(f.key),k()},U=f=>{h()&&i.current?.movePointer(f.movementX,f.movementY)},l=f=>{h()&&i.current?.setButtons(f.buttons)},m=()=>{x()};return n.addEventListener("pointerlockchange",R),n.addEventListener("keydown",D),n.addEventListener("keyup",M),n.addEventListener("mousemove",U),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",m),()=>{n.removeEventListener("pointerlockchange",R),n.removeEventListener("keydown",D),n.removeEventListener("keyup",M),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",m)}},[n,x,k]);let b=(0,H.useCallback)(h=>{h.requestPointerLock?.()},[]),y=(0,H.useCallback)(()=>{d.current=!0,u(!0)},[]),S=(0,H.useCallback)(()=>{d.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),x()},[n,x]),E=(0,H.useCallback)(h=>{i.current?.keyDown(h),k()},[k]),C=(0,H.useCallback)(h=>{i.current?.keyUp(h),k()},[k]),w=(0,H.useCallback)((h,R)=>{i.current?.movePointer(h,R)},[]);return{engage:b,engageTouch:y,release:S,engaged:c,heldKeys:g,pressKey:E,releaseKey:C,movePointer:w}}var Dr=new Map;function Vr(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Dr.set(e,{component:t,schema:r})}function qr(e,t){let r=Dr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var xe=require("react/jsx-runtime");function Fr({name:e,props:t,fallback:r}){let o=qr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,xe.jsx)(xe.Fragment,{children:r}):(0,xe.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,xe.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,xe.jsx)(n,{...o.validatedProps})}var Le=require("zod"),Te=require("react/jsx-runtime"),Hr=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 Yt(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),a=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:a}}function Wr(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Yt(e);return(0,Te.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Te.jsx)("div",{className:"urun-progress-label",children:o}),(0,Te.jsx)("div",{className:"urun-progress-bar",children:(0,Te.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Te.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var ft=require("zod"),ze=require("react/jsx-runtime"),Br=ft.z.object({state:ft.z.enum(["thinking","generating","idle","error"]),message:ft.z.string().optional()}),Zn={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Zt(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Zn[t]??t;return{state:t,message:n,isActive:o}}function $r(e){let{state:t,message:r,isActive:o}=Zt(e);return(0,ze.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,ze.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,ze.jsx)("span",{className:"urun-status-message",children:r})]})}var Xe=require("react"),gt=require("zod"),Ge=require("react/jsx-runtime"),Kr=gt.z.object({text:gt.z.string(),streaming:gt.z.boolean().default(!1)});function Qt(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function jr(e){let{text:t,streaming:r}=Qt(e),o=(0,Xe.useRef)(null),n=(0,Xe.useRef)(0);return(0,Xe.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Ge.jsxs)("div",{className:"urun-text-stream",children:[(0,Ge.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Ge.jsx)("span",{className:"urun-text-cursor"})]})}var Ye=require("zod"),Ze=require("react/jsx-runtime"),Jr=Ye.z.object({src:Ye.z.string().url(),alt:Ye.z.string().optional(),caption:Ye.z.string().optional()});function er(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function zr(e){let{src:t,alt:r,caption:o}=er(e);return(0,Ze.jsxs)("figure",{className:"urun-image-frame",children:[(0,Ze.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,Ze.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var pe=require("zod"),De=require("react/jsx-runtime"),Xr=pe.z.object({metrics:pe.z.array(pe.z.object({label:pe.z.string(),value:pe.z.union([pe.z.string(),pe.z.number()]),unit:pe.z.string().optional()}))});function tr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Gr(e){let{metrics:t}=tr(e);return(0,De.jsx)("div",{className:"urun-metrics-panel",children:t.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 Qe=require("react"),Qr=require("react/jsx-runtime"),rr=(0,Qe.createContext)(null);function Yr({session:e,children:t}){return(0,Qr.jsx)(rr.Provider,{value:e,children:t})}function ce(){return(0,Qe.useContext)(rr)}function Zr(){let e=(0,Qe.useContext)(rr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var X=require("react");var ht=require("react/jsx-runtime"),Qn=1e3;function eo(...e){console.debug("[video]",...e)}var St=(0,X.forwardRef)(function(t,r){let{session:o,stream:n="video",track:s,muted:a=!0,mirror:i=!1,objectFit:c="contain",className:u,style:g,videoClassName:p,placeholder:d,children:k,onTrack:x}=t,b=ce(),y=o??b,S=(0,X.useRef)(null),E=(0,X.useRef)(null),[C,w]=(0,X.useState)(!1),h=(0,X.useRef)(x);h.current=x;let R=(0,X.useCallback)(()=>{if(typeof MediaStream>"u")return null;E.current||(E.current=new MediaStream);let m=S.current;return m&&m.srcObject!==E.current&&(m.srcObject=E.current),E.current},[]),D=(0,X.useCallback)(m=>{let f=S.current;if(!f)return;let P=f.play();!P||typeof P.catch!="function"||P.catch(I=>eo(`play() failed (${m})`,I))},[]),M=(0,X.useCallback)(m=>{let f=R();if(f){for(let P of f.getVideoTracks())P!==m&&f.removeTrack(P);if(m&&!f.getVideoTracks().includes(m)){f.addTrack(m);let P=S.current;P&&(P.srcObject=f)}m&&D("track-attach"),w(m!==null),h.current?.(m)}},[R,D]),U=(0,X.useCallback)(m=>{S.current=m,m&&(a&&(m.muted=!0,m.defaultMuted=!0,m.setAttribute("muted","")),m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),R())},[R,a]);(0,X.useImperativeHandle)(r,()=>({get element(){return S.current},get live(){return E.current?E.current.getVideoTracks().length>0:!1}}),[]);let l=s!==void 0;return(0,X.useEffect)(()=>{if(l){M(s??null);return}if(!y)return;let m=y.stream(n),f=()=>{let v=E.current;return v?v.getVideoTracks()[0]??null:null},P=v=>{if(v!==f()&&(M(v),v)){let L=()=>{f()===v&&M(null)};v.addEventListener("ended",L)}},I=m.track;I&&I.readyState==="live"&&P(I);let J=m.on("track",v=>{v&&v.readyState!=="live"||P(v)}),A=setInterval(()=>{let v=m.track;v&&v.readyState==="live"&&P(v)},Qn);return()=>{J(),clearInterval(A)}},[y,n,l,s,M]),(0,ht.jsxs)("div",{className:u,style:{position:"relative",width:"100%",height:"100%",...g},"data-urun-video":"","data-urun-video-live":C?"true":"false",children:[(0,ht.jsx)("video",{ref:U,className:p,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...i?{transform:"scaleX(-1)"}:{}}}),C?null:d,k]})});var en=require("react");var rn=require("react/jsx-runtime"),tn=(0,en.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,rn.jsx)(St,{ref:r,stream:o,...n})});var O=require("react"),on=require("@urun-sh/core");var vt=null;function to(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function et(){if(vt)return vt;let e=to();return e?(vt=new e,vt):null}function tt(){let e=et();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var an=require("react/jsx-runtime"),ro=1e3,nn=200;function nr(...e){console.debug("[audio]",...e)}var rt=(0,O.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:a=!1,className:i,onTrack:c,onUnlockChange:u,onAudioElement:g}=t,p=ce(),d=o??p,k=(0,O.useRef)(null),x=(0,O.useRef)(null),b=(0,O.useRef)(null),y=(0,O.useRef)(null),S=(0,O.useRef)(c);S.current=c;let E=(0,O.useRef)(u);E.current=u;let C=(0,O.useCallback)(l=>{b.current!==l&&(b.current=l,E.current?.(l))},[]),w=(0,O.useCallback)(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let l=k.current;return l&&l.srcObject!==x.current&&(l.srcObject=x.current),x.current},[]),h=(0,O.useCallback)(l=>{let m=k.current;if(!m)return;let f=m.play();!f||typeof f.then!="function"||f.then(()=>{m.muted||C(!0)}).catch(P=>{let I=P instanceof Error?P.name:String(P);if(I==="AbortError"){nr(`play() aborted (${l}); retrying in ${nn}ms`),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,h(`${l}:retry`)},nn);return}if(I==="NotAllowedError"){nr(`play() blocked pending a user gesture (${l})`),C(!1);return}nr(`play() failed (${l})`,P)})},[C]),R=(0,O.useCallback)(l=>{let m=w();if(m){for(let f of m.getAudioTracks())f!==l&&m.removeTrack(f);l&&!m.getAudioTracks().includes(l)&&m.addTrack(l),l&&h("track-attach"),S.current?.(l)}},[w,h]),D=(0,O.useCallback)(()=>{let l=k.current;l&&(w(),l.muted=!1,h("gesture"),tt(),C(!0))},[w,h,C]);(0,O.useImperativeHandle)(r,()=>({unlock:D,get unlocked(){return b.current===!0},get element(){return k.current}}),[D]);let M=(0,O.useCallback)(l=>{k.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),w()),g?.(l)},[w,g]),U=s!==void 0;return(0,O.useEffect)(()=>{if(U){R(s??null);return}if(!d)return;let l=d.stream(n),m=()=>{let A=x.current;return A?A.getAudioTracks()[0]??null:null},f=A=>{if(A!==m()&&(R(A),A)){let v=()=>{m()===A&&R(null)};A.addEventListener("ended",v)}},P=l.track;P&&P.readyState==="live"&&f(P);let I=l.on("track",A=>{A&&A.readyState!=="live"||f(A)}),J=setInterval(()=>{let A=l.track;A&&A.readyState==="live"&&f(A)},ro);return()=>{I(),clearInterval(J)}},[d,n,U,s,R]),(0,O.useEffect)(()=>(0,on.observePageLifecycle)(()=>{tt(),b.current===!0&&h("foreground")}),[h]),(0,O.useEffect)(()=>()=>{y.current&&clearTimeout(y.current)},[]),(0,an.jsx)("audio",{ref:M,className:i,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})}),sn=rt;var N=require("react"),Ve=require("@urun-sh/core");var cn=require("react/jsx-runtime"),or={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function yt(...e){console.debug("[voice]",...e)}var nt=(0,N.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:a=or,connectTimeoutMs:i,attempts:c=3,retryDelayMs:u=1500,onActiveChange:g,onError:p,onMicStream:d,onTrack:k,onUnlockChange:x,capture:b}=t,y=ce(),S=o??y,E=(0,N.useRef)(null),C=(0,N.useRef)(null),w=(0,N.useRef)(null),h=(0,N.useRef)([]),R=(0,N.useRef)(!1),D=(0,N.useRef)(g);D.current=g;let M=(0,N.useRef)(p);M.current=p;let U=(0,N.useRef)(d);U.current=d;let l=(0,N.useCallback)(v=>{R.current!==v&&(R.current=v,D.current?.(v))},[]),m=(0,N.useCallback)(()=>{for(let v of h.current)v();h.current=[],w.current?.release(),w.current=null,C.current&&(C.current=null,U.current?.(null))},[]),f=(0,N.useCallback)(async()=>{let v=w.current;if(v){let V=await v.update(a);return C.current=v.stream,U.current?.(v.stream),V}let $=await(b??(0,Ve.sharedCaptureController)()).claim("audio",a);w.current=$,h.current=[$.onTrack((V,K)=>{C.current=K,U.current?.(K),R.current&&S?.stream(n).attach(V).catch(j=>yt("mic re-attach after one-capture re-acquire failed",j))}),$.onLost(V=>{w.current=null,h.current=[],C.current=null,U.current?.(null),l(!1),M.current?.(V)})],C.current=$.stream,U.current?.($.stream);let G=$.track;if(!G)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return G},[b,a,S,n,l]),P=(0,N.useCallback)(async()=>{m(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,m,l]),I=(0,N.useCallback)(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");E.current?.unlock();let v;try{v=await f()}catch(G){m();let V=(0,Ve.sessionFailureFromMediaError)(G,S.status);throw M.current?.(V),V}S.connect?.();let L;for(let G=1;G<=c;G++)try{await S.whenLive(i!==void 0?{timeout:i}:void 0),await S.stream(n).attach(v),l(!0);return}catch(V){L=V,yt(`start attempt ${G}/${c} failed`,V),G<c&&await new Promise(K=>setTimeout(K,u))}m(),l(!1);let $=L instanceof Error?L:new Error(String(L??"voice start failed"));throw M.current?.($),$},[S,n,i,c,u,f,m,l]);(0,N.useImperativeHandle)(r,()=>({start:I,stop:P,unlock:()=>E.current?.unlock(),get active(){return R.current},get micStream(){return C.current},get audio(){return E.current}}),[I,P]);let J=(0,N.useRef)(!1),A=(0,N.useCallback)(async()=>{if(!S||!R.current||J.current)return;let v=C.current?.getAudioTracks()[0]??null;if(v&&v.readyState==="live"){try{await S.stream(n).attach(v)}catch(L){yt("foreground mic re-assert failed (will retry on next pass)",L)}return}J.current=!0;try{let L=await f();await S.stream(n).attach(L)}catch(L){let $=L instanceof Error?L:new Error(String(L));yt("foreground mic re-acquire failed",$),M.current?.($)}finally{J.current=!1}},[S,n,f]);return(0,N.useEffect)(()=>{let v=()=>{A()};return S&&typeof S.onRecovery=="function"?S.onRecovery(v):(0,Ve.observePageLifecycle)(v)},[S,A]),(0,N.useEffect)(()=>m,[m]),s?(0,cn.jsx)(rt,{ref:E,session:S,stream:n,onTrack:k,onUnlockChange:x}):null}),un=nt;var ie=require("react");var kt=require("react");var sr={level:0,speaking:!1};function bt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,a]=(0,kt.useState)(sr);return(0,kt.useEffect)(()=>{if(!e){a(sr);return}let i=et();if(!i||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,g;try{u=i.createMediaStreamSource(c),g=i.createAnalyser(),g.fftSize=r,u.connect(g)}catch{return}let p=new Uint8Array(g.fftSize),k=setInterval(()=>{g.getByteTimeDomainData(p);let x=0;for(let y=0;y<p.length;y++){let S=(p[y]-128)/128;x+=S*S}let b=Math.sqrt(x/p.length);a(y=>{let S=b>n;return Math.abs(y.level-b)<.005&&y.speaking===S?y:{level:b,speaking:S}})},o);return()=>{clearInterval(k),u.disconnect(),a(sr)}},[e,r,o,n]),s}var me=require("react/jsx-runtime"),no={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},oo={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},ln=(0,ie.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:a=!0,visible:i=!1,className:c,onActiveChange:u,onError:g,onMicStream:p,capture:d}=t,k=ce(),x=o??k,b=(0,ie.useRef)(null),[y,S]=(0,ie.useState)(null),E=(0,ie.useRef)(p);E.current=p;let{level:C,speaking:w}=bt(i?y:null);return(0,ie.useImperativeHandle)(r,()=>({start:()=>{let h=b.current;return h?h.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>b.current?.stop()??Promise.resolve(),get active(){return b.current?.active??!1},get micStream(){return b.current?.micStream??null}}),[]),(0,ie.useEffect)(()=>{!a||!x||b.current?.start().catch(()=>{})},[a,x]),(0,me.jsxs)(me.Fragment,{children:[(0,me.jsx)(nt,{ref:b,session:x,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...d!==void 0?{capture:d}:{},onActiveChange:u,onError:g,onMicStream:h=>{S(h),E.current?.(h)}}),i?(0,me.jsx)("span",{className:c,style:no,"data-urun-mic":"","data-urun-mic-active":y?"true":"false","data-urun-mic-speaking":w?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(C*100)/100,children:(0,me.jsx)("span",{style:oo,children:(0,me.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(C*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var Pt=require("@urun-sh/core"),T=require("react");var ne=require("react/jsx-runtime"),ar={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function ir(...e){console.debug("[camera]",...e)}function so(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function io(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var ur=(0,T.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:a=!1,back:i=!1,facingMode:c,autoStart:u=!0,mirror:g="auto",connectTimeoutMs:p,visible:d=!1,className:k,videoClassName:x,onActiveChange:b,onError:y,onStream:S,onTrack:E,children:C,capture:w,flipControl:h="auto",flipControlClassName:R,onDevices:D}=t;if(a&&i)throw new Error("<Camera> takes `front` OR `back`, not both");let M=a?"user":i?"environment":c??"environment",U=ce(),l=o??U,m=(0,T.useRef)(null),f=(0,T.useRef)(null),P=(0,T.useRef)(null),I=(0,T.useRef)([]),J=(0,T.useRef)(null),A=(0,T.useRef)(!1),v=(0,T.useRef)(M),[L,$]=(0,T.useState)(M),[G,V]=(0,T.useState)(!1),[K,j]=(0,T.useState)(null),[W,q]=(0,T.useState)(!1),[Q]=(0,T.useState)(so),Re=(0,T.useRef)(b);Re.current=b;let at=(0,T.useRef)(y);at.current=y;let Ft=(0,T.useRef)(S);Ft.current=S;let ut=(0,T.useRef)(E);ut.current=E;let pr=(0,T.useRef)(D);pr.current=D;let Se=(0,T.useCallback)(_=>{A.current!==_&&(A.current=_,V(_),Re.current?.(_))},[]);(0,T.useEffect)(()=>{if(!G){j(null);return}let _=!1,F=()=>{io().then(re=>{_||(j(re),re&&pr.current?.(re))})};F();let Z=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof Z?.addEventListener=="function"?(Z.addEventListener("devicechange",F),()=>{_=!0,Z.removeEventListener?.("devicechange",F)}):()=>{_=!0}},[G]);let ct=(0,T.useCallback)(_=>{let F=m.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=_,_&&F.play()?.catch?.(Z=>ir("preview play() failed",Z)))},[]),le=(0,T.useCallback)(()=>{J.current?.(),J.current=null;for(let _ of I.current)_();I.current=[],P.current?.release(),P.current=null,f.current&&(f.current=null,Ft.current?.(null),ut.current?.(null)),ct(null)},[ct]),Ht=(0,T.useCallback)((_,F)=>{J.current?.(),f.current=F,ct(F),Ft.current?.(F);let Z=()=>{f.current===F&&(ir("camera track ended (device removed or permission revoked)"),le(),Se(!1))};_.addEventListener("ended",Z),J.current=()=>_.removeEventListener("ended",Z)},[ct,le,Se]),Ae=(0,T.useCallback)(async _=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let F={...ar,...s,facingMode:_},Z;try{let re=P.current;if(re)Z=await re.update(F);else{let $e=await(w??(0,Pt.sharedCaptureController)()).claim("video",F);if(P.current=$e,I.current=[$e.onTrack((Ke,On)=>{Ht(Ke,On),A.current&&l.stream(n).attachVideo(Ke).then(()=>ut.current?.(Ke)).catch(Ln=>ir("camera re-publish after one-capture re-acquire failed",Ln))}),$e.onLost(Ke=>{P.current=null,I.current=[],le(),Se(!1),at.current?.(Ke)})],!$e.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});Z=$e.track}}catch(re){let Ue=(0,Pt.sessionFailureFromMediaError)(re,l.status);throw at.current?.(Ue),Ue}v.current=_,$(_),Ht(Z,P.current?.stream??new MediaStream([Z]));try{l.connect?.(),await l.whenLive(p!==void 0?{timeout:p}:void 0),await l.stream(n).attachVideo(Z)}catch(re){le(),Se(!1);let Ue=re instanceof Error?re:new Error(String(re));throw at.current?.(Ue),Ue}ut.current?.(Z),Se(!0)},[l,n,s,p,w,Ht,le,Se]),mr=(0,T.useCallback)(_=>Ae(_?.facingMode??v.current),[Ae]),lt=(0,T.useCallback)(async _=>{A.current&&v.current===_||await Ae(_)},[Ae]),Wt=(0,T.useCallback)(()=>Ae(v.current==="environment"?"user":"environment"),[Ae]),fr=(0,T.useCallback)(async()=>{le(),Se(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,le,Se]);(0,T.useImperativeHandle)(r,()=>({start:mr,stop:fr,flip:Wt,setFacingMode:lt,get active(){return A.current},get facingMode(){return v.current},get stream(){return f.current},get element(){return m.current}}),[mr,fr,Wt,lt]);let gr=(0,T.useRef)(lt);if(gr.current=lt,(0,T.useEffect)(()=>{!u||!l||gr.current(M).catch(()=>{})},[u,l,M]),(0,T.useEffect)(()=>le,[le]),!d)return null;let _n=g==="auto"?L==="user":g,Nn=G&&(h===!0||h==="auto"&&Q&&(K?.length??0)>1),In=()=>{W||(q(!0),Wt().catch(()=>{}).finally(()=>q(!1)))};return(0,ne.jsxs)("div",{className:k,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":L,children:[(0,ne.jsx)("video",{ref:m,className:x,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",..._n?{transform:"scaleX(-1)"}:{}}}),Nn?(0,ne.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:In,disabled:W,className:R,style:R?{opacity:W?.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:W?.6:1},children:(0,ne.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,ne.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ne.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ne.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ne.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ne.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,C]})}),dn=(0,T.forwardRef)(function({preview:t=!0,...r},o){return(0,ne.jsx)(ur,{ref:o,...r,visible:t,autoStart:!1})});var Ct=require("react");function pn(e,t){let[r,o]=(0,Ct.useState)(null);return(0,Ct.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var gn=require("react");var Tt=require("react");var mn=require("zustand/vanilla"),fn=require("zustand"),ao=()=>{};function xt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=(0,mn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,a=()=>{if(s){for(let u of s)u();s=null}},i=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),a):ao,c=(u=>(0,fn.useStore)(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:i,unbind:a}),t.bind!==!1&&i(),c}function qe(e,t){let r=(0,Tt.useMemo)(()=>xt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Tt.useEffect)(()=>r.bind(),[r]),r}function Sn(e,t,r){let n=qe(e,t)(r??(i=>i)),s=(0,gn.useCallback)(i=>{e&&t&&e.doc(t).set(i)},[e,t]);if(r)return n;let a=n;return{snapshot:e&&t?a.doc:null,synced:a.synced,set:s}}var wt=require("react");var ve=200;function fe(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Fe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Et(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Rt(e,t,r={}){let o=r.cap??200,[n,s]=(0,wt.useState)([]);return(0,wt.useEffect)(()=>{if(s([]),!e||!t)return;let a=!0,i=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await i.next();if(!a||c.done)break;s(u=>fe(u,{at:Date.now(),payload:c.value},o))}})(),()=>{a=!1,i.return?.()}},[e,t,o]),n}var ae=require("react/jsx-runtime");function hn({session:e,name:t,cap:r,className:o}){let n=Rt(e,t,{cap:r});return(0,ae.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,ae.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,ae.jsx)("code",{children:t}),(0,ae.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,ae.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,ae.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,ae.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,a)=>(0,ae.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,ae.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Fe(s.payload)]},`${s.at}-${a}`))})]})}var ot=require("react");var te=require("react/jsx-runtime");function st({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,ot.useState)(""),[a,i]=(0,ot.useState)(null),c=(0,ot.useCallback)(()=>{let u=Et(n);if(!u.ok){i(u.error);return}i(null),o(u.value,n.trim()),s("")},[n,o]);return(0,te.jsxs)("div",{className:"urun-doc-patch",children:[(0,te.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),(0,te.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,te.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),a?(0,te.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function vn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=qe(e,t),a=s(u=>u.doc),i=s(u=>u.synced),c=s(u=>u.set);return(0,te.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,te.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,te.jsx)("code",{children:t}),(0,te.jsx)("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),(0,te.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),r?(0,te.jsx)(st,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}var At=require("react");var ge=require("react/jsx-runtime");function yn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function kn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,At.useState)([]);return(0,At.useEffect)(()=>(s([]),e?e.doc(t).on("change",i=>{s(c=>fe(c,{at:Date.now(),direction:"in",text:yn(Fe(i))},r))}):void 0),[e,t,r]),(0,ge.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,ge.jsx)(st,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(a,i)=>{e?.doc(t).set(a),s(c=>fe(c,{at:Date.now(),direction:"out",text:yn(i)},r))}}),(0,ge.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,ge.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((a,i)=>(0,ge.jsxs)("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[(0,ge.jsx)("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",(0,ge.jsx)("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${i}`))})]})}var Ut=require("react");var Ee=require("react/jsx-runtime");function bn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,a]=(0,Ut.useState)([]),i=t.join(","),c=r.join(",");return(0,Ut.useEffect)(()=>{if(a([]),!e)return;let u=(p,d)=>a(k=>fe(k,{at:Date.now(),kind:p,text:d},o)),g=[];g.push(e.onPhase(p=>u("phase",`phase \u2192 ${p.name}`)));for(let p of t){let d=e.stream(p);g.push(d.on("track",k=>u("track",`${p}: ${k?"track arrived":"track ended"}`)))}for(let p of r){let d=e.doc(p);g.push(d.on("change",()=>u("doc",`${p} changed`)))}return()=>g.forEach(p=>p())},[e,i,c,o]),(0,Ee.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Ee.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,g)=>(0,Ee.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,Ee.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,Ee.jsx)("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${g}`))})}var Dt=require("@urun-sh/core");var Mt=require("react");function oe(e){let[t,r]=(0,Mt.useState)(e?.phase??null);return(0,Mt.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var Cn=require("@urun-sh/core");var He=require("react"),Pn=require("@urun-sh/core");function _t(e){let t=oe(e),r=(0,Pn.isWakingPhase)(t?.name),o=(0,He.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[a,i]=(0,He.useState)(s);return(0,He.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:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?a:0}}var ye=require("react/jsx-runtime");function Nt({session:e,render:t,className:r}){let o=_t(e);return!o.waking||!o.phase?null:(0,ye.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,ye.jsxs)(ye.Fragment,{children:[(0,ye.jsx)("span",{className:"urun-session-waking-label",children:(0,Cn.describeSessionPhase)(o.phase)})," ",(0,ye.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Ot=require("react");var ke=require("react"),uo={event:null,elapsedMs:0};function It(e,t){let[r,o]=(0,ke.useState)(null),n=(0,ke.useRef)(0);(0,ke.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(i=>{t!==void 0&&i.stream!==t||(n.current=Date.now(),o(i))})},[e,t]);let[s,a]=(0,ke.useState)(0);return(0,ke.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}:uo}var We=require("react/jsx-runtime"),co={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 lo(e){let[t,r]=(0,Ot.useState)(!1);return(0,Ot.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function Lt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=It(e,t),a=lo(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??co[c]})," ",(0,We.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var se=require("react/jsx-runtime"),po={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function xn({session:e,className:t}){let r=oe(e),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,se.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,se.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,se.jsx)("span",{className:"urun-session-status-label",children:po[o]}),n?(0,se.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function Tn({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=oe(e);if(s?.name==="live")return(0,se.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,se.jsx)(Lt,{session:e})]});let a=r?r(s):(0,se.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,Dt.isWakingPhase)(s.name)?(0,se.jsx)(Nt,{session:e}):s&&s.name!=="idle"?(0,Dt.describeSessionPhase)(s):"Waiting for a live session\u2026"}),i=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,se.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[a,i?(0,se.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var Vt=require("react");var wn=require("react/jsx-runtime");function cr(e){return oe(e)?.endsAt??null}function mo(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function En({session:e,urgentMs:t=6e4,className:r}){let n=cr(e)?.getTime()??null,[s,a]=(0,Vt.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,Vt.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=mo(s);return(0,wn.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${i}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:i})}var it=require("react/jsx-runtime"),fo=new Set(["expired","ended","error"]);function Rn({session:e,onNewSession:t,children:r,className:o}){let n=oe(e);if(!n||!fo.has(n.name))return null;let s=r?r(n):(0,it.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,it.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,it.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var be=require("react"),we=require("react/jsx-runtime");function lr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function dr(e){let t=(0,be.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,be.useState)(()=>t?lr(t.get("idle")):null);return(0,be.useEffect)(()=>{if(!t){o(null);return}return o(lr(t.get("idle"))),t.on("change",()=>o(lr(t.get("idle"))))},[t]),r}function go(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function An({session:e,onStillHere:t,className:r}){let o=dr(e),n=o?.deadlineEpochS??null,[s,a]=(0,be.useState)(null);if((0,be.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||!e)return null;let i=()=>{e.touch?.(),t?.()};return(0,we.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,we.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,we.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,we.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${go(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,we.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:i,children:"I'm still here"})]})})}var Be=require("react"),Un=require("@urun-sh/core");function Mn(e){let t=(0,Be.useContext)(_e),[r,o]=(0,Be.useState)(null),n=e.app??t?.appId,s=e.function,a=e.intervalS??60,i=t?.baseUrl,c=t?.orgId,u=t?.jwt,g=t?.getAccessToken,p=t?.authProvider;return(0,Be.useEffect)(()=>{if(!i||!c||!n||!s)return;let d=!1,k=()=>{(0,Un.prewake)({baseUrl:i,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:g,authProvider:p}).then(b=>{d||o(b)}).catch(()=>{})};k();let x=setInterval(k,Math.max(1,a)*1e3);return()=>{d=!0,clearInterval(x)}},[n,s,a,i,c,u,g,p]),r}var qt=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,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,Session,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,readOperatorToken,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
2
+ "use strict";var Bt=Object.defineProperty;var Dn=Object.getOwnPropertyDescriptor;var Vn=Object.getOwnPropertyNames;var qn=Object.prototype.hasOwnProperty;var Fn=(e,t)=>{for(var r in t)Bt(e,r,{get:t[r],enumerable:!0})},Hn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vn(t))!qn.call(e,n)&&n!==r&&Bt(e,n,{get:()=>t[n],enumerable:!(o=Dn(t,n))||o.enumerable});return e};var Wn=e=>Hn(Bt({},"__esModule",{value:!0}),e);var So={};Fn(So,{Audio:()=>rt,Camera:()=>ur,ComponentRenderer:()=>Fr,DEFAULT_CAMERA_CONSTRAINTS:()=>ar,DEFAULT_LOG_CAP:()=>ve,DEFAULT_VOICE_CONSTRAINTS:()=>or,DocPatchForm:()=>st,Image:()=>tn,ImageFrame:()=>zr,ImageFrameSchema:()=>Jr,MetricsPanel:()=>Gr,MetricsPanelSchema:()=>Xr,Mic:()=>ln,OPERATOR_CHORD_LABEL:()=>Tr,OPERATOR_TOKEN_STORAGE_KEY:()=>Cr,ProgressCard:()=>Wr,ProgressCardSchema:()=>Hr,Session:()=>Yr,StatusBadge:()=>$r,StatusBadgeSchema:()=>Br,TextStream:()=>jr,TextStreamSchema:()=>Kr,UrunActivationOverlay:()=>Lt,UrunAudio:()=>sn,UrunAuthProvider:()=>$t,UrunCamera:()=>dn,UrunControlSender:()=>kn,UrunDocPanel:()=>vn,UrunErrorBoundary:()=>Me,UrunEventSpine:()=>bn,UrunIdleWarning:()=>An,UrunJwtProvider:()=>kr,UrunProvider:()=>Er,UrunSessionClock:()=>wn,UrunSessionEnded:()=>Rn,UrunSessionGate:()=>Tn,UrunSessionStatus:()=>xn,UrunSessionWaking:()=>Nt,UrunStreamTail:()=>hn,UrunVoice:()=>un,Video:()=>St,Voice:()=>nt,authMode:()=>Je,createDocStore:()=>xt,describeSessionPhase:()=>qt.describeSessionPhase,formatPayload:()=>Fe,getUrunAudioContext:()=>et,isWakingPhase:()=>qt.isWakingPhase,parseJsonObject:()=>wt,pushCapped:()=>fe,readOperatorToken:()=>Kt,registerComponent:()=>Vr,resumeUrunAudioContext:()=>tt,urunPublicEnv:()=>de,useActivation:()=>It,useApp:()=>Ar,useChat:()=>Or,useCompletion:()=>_r,useDocStore:()=>qe,useImageFrame:()=>er,useInputPresence:()=>Lr,useMetricsPanel:()=>tr,useOperatorOverride:()=>mt,useProgressCard:()=>Yt,useRequest:()=>Ur,useSession:()=>Zr,useSessionDoc:()=>Sn,useSessionEndsAt:()=>cr,useSessionIdle:()=>dr,useSessionPhase:()=>oe,useSessionTrack:()=>pn,useSessionWake:()=>_t,useStatusBadge:()=>Zt,useStreamMessages:()=>Rt,useTextStream:()=>Qt,useUrunAudioLevel:()=>bt,useUrunAuth:()=>dt,useUrunPrewake:()=>Mn,usesWorkOSAuth:()=>vr});module.exports=Wn(So);var ue=require("react");var Sr=require("react"),je=require("react/jsx-runtime"),Me=class extends Sr.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,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 hr=require("react"),_e=(0,hr.createContext)(null);function Pe(e){return e&&e.trim()?e.trim():void 0}function de(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Pe(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return Pe(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Pe(typeof process<"u"?process.env?.[e]:void 0)}}function Je(){let e=de("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||de("VERCEL_ENV")==="production"?"workos":de("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function vr(){return Je()==="workos"}var Ne=require("react"),br=require("react/jsx-runtime"),yr=(0,Ne.createContext)(null);function $t({getAccessToken:e,children:t}){let r=(0,Ne.useMemo)(()=>({getAccessToken:e}),[e]);return(0,br.jsx)(yr.Provider,{value:r,children:t})}var kr=$t;function dt(){return(0,Ne.useContext)(yr)}var pt=require("react"),Cr="urun.operator_token",xr=null,Pr="op",Tr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function wr(){return typeof window<"u"}function Kt(){return xr}function Bn(){if(!wr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Pr);if(!r)return null;xr=r,t.delete(Pr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function $n(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function mt(e){let t=(0,pt.useRef)(e);t.current=e,(0,pt.useEffect)(()=>{if(!wr())return;Bn();let r=o=>{if(!$n(o))return;let n=Kt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var he=require("react/jsx-runtime"),Kn="/api/urun-token";function jn(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,he.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,he.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,he.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Er({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,fallback:c,errorFallback:g,children:d}){let S=n===void 0&&t===void 0;if(!S&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!S&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let y=r??o;if(S&&(typeof y!="string"||y.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);let[b,m]=(0,ue.useState)(),[P,h]=(0,ue.useState)(),[w,x]=(0,ue.useState)(null),[E,v]=(0,ue.useState)(null);mt(K=>v({jwt:K}));let R=dt(),D=de("NEXT_PUBLIC_SESSION_TOKEN")??de("NEXT_PUBLIC_URUN_JWT"),M=Je(),U=E!==null,l=M==="workos"&&!n&&!U&&!S,p=n??(M==="jwt"?D:void 0)??b??P?.token,f=U?E.jwt:p,C=s??de("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),I=l&&!f,J=t??P?.orgId,A=e??P?.gatewayUrl,k=S&&P===void 0,L=S&&P!==void 0&&!A?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,$=w??L,G=(0,ue.useMemo)(()=>({appId:y,baseUrl:A??"",orgId:J??"",jwt:f,getAccessToken:l?R?.getAccessToken:void 0,authProvider:C,eventsUrl:i,sessionKey:a,priority:U?"preempt":void 0}),[y,R,A,C,f,i,J,a,l,U]),V=u??Kn;return(0,ue.useEffect)(()=>{if(!S)return;let K=new AbortController;return x(null),(async()=>{try{let j=await fetch(V,{method:"POST",signal:K.signal});if(!j.ok)throw new Error(`[urun] token endpoint ${V} answered ${j.status}`);let W=await j.json(),q=typeof W.token=="string"?W.token:"",Q=typeof W.orgId=="string"?W.orgId:"";if(!q||!Q)throw new Error(`[urun] token endpoint ${V} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);h({token:q,orgId:Q,gatewayUrl:typeof W.gatewayUrl=="string"?W.gatewayUrl:void 0})}catch(j){if(K.signal.aborted)return;x(j instanceof Error?j:new Error(String(j)))}})(),()=>K.abort()},[S,V]),(0,ue.useEffect)(()=>{if(!l||!R)return;let K=!1,j=R;async function W(){try{let Q=await j.getAccessToken();K||m(Q??void 0)}catch{K||m(void 0)}}W();let q=window.setInterval(()=>{W()},6e4);return()=>{K=!0,window.clearInterval(q)}},[R,l]),(0,he.jsx)(Me,{fallback:c,children:$?jn(g,$):I||k?(0,he.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,he.jsx)(_e.Provider,{value:G,children:d})})}var ee=require("react"),Rr=require("@urun-sh/core");function Jn(e,t){return`${e}:${JSON.stringify(t??{})}`}function zn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var Ce=new Map;var jt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Jt=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},zt=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new jt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Jt(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Ar(){let e=(0,ee.useContext)(_e);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,ee.useReducer)(i=>i+1,0),r=(0,ee.useRef)(new Map),o=(0,ee.useRef)(new Map),n=(0,ee.useRef)(null),s=(0,ee.useMemo)(()=>(0,Rr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.priority]);return(0,ee.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=Ce.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=Ce.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let d=Ce.get(u);!d||d.refCount!==0||(Ce.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),(0,ee.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=d=>{let S=Jn(u,d),y=r.current.get(S);if(y&&!y.disposed)return y;let b=zn(e,u,d),m=Ce.get(b);return m?.handle.disposed&&(m.disposeTimer&&clearTimeout(m.disposeTimer),Ce.delete(b),o.current.get(b)===m&&o.current.delete(b),m=void 0),m?m.disposeTimer&&(clearTimeout(m.disposeTimer),m.disposeTimer=null):(m={handle:new zt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},Ce.set(b,m)),o.current.get(b)!==m&&(o.current.set(b,m),m.handle.addNotifier(t),m.refCount+=1),r.current.set(S,m.handle),m.handle};return i.set(u,g),g}})},[e,s])}var z=require("react");function Ie(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Xn(e){return e instanceof Error?e:new Error(String(e))}function Ur(e,t){let r=(0,z.useMemo)(()=>Ie(e),[e]),[o,n]=(0,z.useState)(void 0),[s,i]=(0,z.useState)(null),[a,u]=(0,z.useState)(!1),c=(0,z.useRef)(t);c.current=t;let g=(0,z.useRef)(0),d=(0,z.useRef)(null),S=(0,z.useRef)(!0);(0,z.useEffect)(()=>(S.current=!0,()=>{S.current=!1,d.current?.abort()}),[]);let y=(0,z.useCallback)(async P=>{d.current?.abort();let h=new AbortController;d.current=h;let w=++g.current,x=()=>S.current&&g.current===w;x()&&(u(!0),i(null));try{let E=await r.request(P,{...c.current,signal:h.signal});return x()&&(n(E),u(!1),c.current?.onSuccess?.(E)),E}catch(E){let v=Xn(E);throw x()&&(i(v),u(!1),c.current?.onError?.(v)),v}},[r]),b=(0,z.useCallback)(P=>{y(P).catch(()=>{})},[y]),m=(0,z.useCallback)(()=>{g.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:b,mutateAsync:y,data:o,error:s,isPending:a,reset:m}}var Y=require("react");function Mr(e){return e instanceof Error?e:new Error(String(e))}var Gn=e=>typeof e=="string"?e:String(e);function _r(e,t){let r=(0,Y.useMemo)(()=>Ie(e),[e]),[o,n]=(0,Y.useState)(""),[s,i]=(0,Y.useState)(!1),[a,u]=(0,Y.useState)(null),c=(0,Y.useRef)(t);c.current=t;let g=(0,Y.useRef)(0),d=(0,Y.useRef)(null),S=(0,Y.useRef)(!0);(0,Y.useEffect)(()=>(S.current=!0,()=>{S.current=!1,d.current?.cancel(),d.current=null}),[]);let y=(0,Y.useCallback)(()=>{g.current++,d.current?.cancel(),d.current=null,S.current&&i(!1)},[]),b=(0,Y.useCallback)(async m=>{d.current?.cancel();let P=++g.current,h=()=>S.current&&g.current===P,w=c.current,x=w?.parseChunk??Gn,E=w?.buildPayload??(f=>({prompt:f}));h()&&(n(""),u(null),i(!0));let{parseChunk:v,buildPayload:R,onFinish:D,onError:M,...U}=w??{},l="",p;try{p=r.requestStream(E(m),U),d.current=p}catch(f){let C=Mr(f);h()&&(u(C),i(!1),w?.onError?.(C));return}try{for await(let f of p){if(g.current!==P)break;l+=x(f),h()&&n(l)}h()&&(i(!1),w?.onFinish?.(l))}catch(f){let C=Mr(f);h()&&(u(C),i(!1),w?.onError?.(C))}finally{d.current===p&&(d.current=null)}},[r]);return{completion:o,complete:b,stop:y,isStreaming:s,error:a}}var B=require("react");function Nr(e){return e instanceof Error?e:new Error(String(e))}var Yn=e=>typeof e=="string"?e:String(e),Ir=0;function Xt(e){return Ir+=1,`${e}-${Ir}`}function Or(e,t){let r=(0,B.useMemo)(()=>Ie(e),[e]),[o,n]=(0,B.useState)(()=>(t?.initialMessages??[]).map(x=>({id:x.id??Xt("msg"),role:x.role,content:x.content}))),[s,i]=(0,B.useState)(""),[a,u]=(0,B.useState)(!1),[c,g]=(0,B.useState)(null),d=(0,B.useRef)(t);d.current=t;let S=(0,B.useRef)(o);S.current=o;let y=(0,B.useRef)(s);y.current=s;let b=(0,B.useRef)(0),m=(0,B.useRef)(null),P=(0,B.useRef)(!0);(0,B.useEffect)(()=>(P.current=!0,()=>{P.current=!1,m.current?.cancel(),m.current=null}),[]);let h=(0,B.useCallback)(()=>{b.current++,m.current?.cancel(),m.current=null,P.current&&u(!1)},[]),w=(0,B.useCallback)(async x=>{let E=x===void 0,v=(E?y.current:x)??"";if(!v.trim())return;m.current?.cancel();let D=++b.current,M=()=>P.current&&b.current===D,U=d.current,l=U?.parseChunk??Yn,p={id:Xt("msg"),role:"user",content:v},f={id:Xt("msg"),role:"assistant",content:""},C=[...S.current,p].map(q=>({role:q.role,content:q.content})),I=[...S.current,p,f];S.current=I,n(I),E&&i(""),g(null),u(!0);let J=U?.buildPayload??(q=>({messages:q})),{initialMessages:A,parseChunk:k,buildPayload:L,onFinish:$,onError:G,...V}=U??{},K=q=>{n(Q=>Q.map(Re=>Re.id===f.id?{...Re,content:q}:Re))},j="",W;try{W=r.requestStream(J(C),V),m.current=W}catch(q){let Q=Nr(q);M()&&(g(Q),u(!1),U?.onError?.(Q));return}try{for await(let q of W){if(b.current!==D)break;j+=l(q),M()&&K(j)}M()&&(u(!1),U?.onFinish?.({...f,content:j}))}catch(q){let Q=Nr(q);M()&&(g(Q),u(!1),U?.onError?.(Q))}finally{m.current===W&&(m.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:w,stop:h,isStreaming:a,error:c}}var H=require("react"),Oe=require("@urun-sh/core"),Gt=[];function Lr(e,t={}){let{field:r=Oe.INPUT_PRESENCE_FIELD,hz:o=Oe.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,H.useMemo)(()=>s?(0,Oe.createInputPresencePublisher)({awareness:{setLocalStateField:(v,R)=>s.setField(v,R)},field:r,hz:o}):null,[s,r,o]),a=(0,H.useRef)(null);a.current=i;let[u,c]=(0,H.useState)(!1),[g,d]=(0,H.useState)(Gt),S=(0,H.useRef)(!1);(0,H.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let y=(0,H.useCallback)(()=>{let v=a.current;d(v?v.heldKeys():Gt)},[]),b=(0,H.useCallback)(()=>{a.current?.clear(),d(Gt)},[]);(0,H.useEffect)(()=>{if(!n)return;let v=()=>!!n.pointerLockElement,R=()=>{if(v()){S.current=!1,c(!0);return}S.current||(c(!1),b())},D=f=>{v()&&(a.current?.keyDown(f.key),y())},M=f=>{a.current?.keyUp(f.key),y()},U=f=>{v()&&a.current?.movePointer(f.movementX,f.movementY)},l=f=>{v()&&a.current?.setButtons(f.buttons)},p=()=>{b()};return n.addEventListener("pointerlockchange",R),n.addEventListener("keydown",D),n.addEventListener("keyup",M),n.addEventListener("mousemove",U),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",p),()=>{n.removeEventListener("pointerlockchange",R),n.removeEventListener("keydown",D),n.removeEventListener("keyup",M),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",p)}},[n,b,y]);let m=(0,H.useCallback)(v=>{v.requestPointerLock?.()},[]),P=(0,H.useCallback)(()=>{S.current=!0,c(!0)},[]),h=(0,H.useCallback)(()=>{S.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),b()},[n,b]),w=(0,H.useCallback)(v=>{a.current?.keyDown(v),y()},[y]),x=(0,H.useCallback)(v=>{a.current?.keyUp(v),y()},[y]),E=(0,H.useCallback)((v,R)=>{a.current?.movePointer(v,R)},[]);return{engage:m,engageTouch:P,release:h,engaged:u,heldKeys:g,pressKey:w,releaseKey:x,movePointer:E}}var Dr=new Map;function Vr(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Dr.set(e,{component:t,schema:r})}function qr(e,t){let r=Dr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var xe=require("react/jsx-runtime");function Fr({name:e,props:t,fallback:r}){let o=qr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,xe.jsx)(xe.Fragment,{children:r}):(0,xe.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,xe.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,xe.jsx)(n,{...o.validatedProps})}var Le=require("zod"),Te=require("react/jsx-runtime"),Hr=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 Yt(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Wr(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Yt(e);return(0,Te.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Te.jsx)("div",{className:"urun-progress-label",children:o}),(0,Te.jsx)("div",{className:"urun-progress-bar",children:(0,Te.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Te.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var ft=require("zod"),ze=require("react/jsx-runtime"),Br=ft.z.object({state:ft.z.enum(["thinking","generating","idle","error"]),message:ft.z.string().optional()}),Zn={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Zt(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Zn[t]??t;return{state:t,message:n,isActive:o}}function $r(e){let{state:t,message:r,isActive:o}=Zt(e);return(0,ze.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,ze.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,ze.jsx)("span",{className:"urun-status-message",children:r})]})}var Xe=require("react"),gt=require("zod"),Ge=require("react/jsx-runtime"),Kr=gt.z.object({text:gt.z.string(),streaming:gt.z.boolean().default(!1)});function Qt(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function jr(e){let{text:t,streaming:r}=Qt(e),o=(0,Xe.useRef)(null),n=(0,Xe.useRef)(0);return(0,Xe.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Ge.jsxs)("div",{className:"urun-text-stream",children:[(0,Ge.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Ge.jsx)("span",{className:"urun-text-cursor"})]})}var Ye=require("zod"),Ze=require("react/jsx-runtime"),Jr=Ye.z.object({src:Ye.z.string().url(),alt:Ye.z.string().optional(),caption:Ye.z.string().optional()});function er(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function zr(e){let{src:t,alt:r,caption:o}=er(e);return(0,Ze.jsxs)("figure",{className:"urun-image-frame",children:[(0,Ze.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,Ze.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var pe=require("zod"),De=require("react/jsx-runtime"),Xr=pe.z.object({metrics:pe.z.array(pe.z.object({label:pe.z.string(),value:pe.z.union([pe.z.string(),pe.z.number()]),unit:pe.z.string().optional()}))});function tr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Gr(e){let{metrics:t}=tr(e);return(0,De.jsx)("div",{className:"urun-metrics-panel",children:t.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 Qe=require("react"),Qr=require("react/jsx-runtime"),rr=(0,Qe.createContext)(null);function Yr({session:e,children:t}){return(0,Qr.jsx)(rr.Provider,{value:e,children:t})}function ce(){return(0,Qe.useContext)(rr)}function Zr(){let e=(0,Qe.useContext)(rr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var X=require("react");var ht=require("react/jsx-runtime"),Qn=1e3;function eo(...e){console.debug("[video]",...e)}var St=(0,X.forwardRef)(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:g,videoClassName:d,placeholder:S,children:y,onTrack:b}=t,m=ce(),P=o??m,h=(0,X.useRef)(null),w=(0,X.useRef)(null),[x,E]=(0,X.useState)(!1),v=(0,X.useRef)(b);v.current=b;let R=(0,X.useCallback)(()=>{if(typeof MediaStream>"u")return null;w.current||(w.current=new MediaStream);let p=h.current;return p&&p.srcObject!==w.current&&(p.srcObject=w.current),w.current},[]),D=(0,X.useCallback)(p=>{let f=h.current;if(!f)return;let C=f.play();!C||typeof C.catch!="function"||C.catch(I=>eo(`play() failed (${p})`,I))},[]),M=(0,X.useCallback)(p=>{let f=R();if(f){for(let C of f.getVideoTracks())C!==p&&f.removeTrack(C);if(p&&!f.getVideoTracks().includes(p)){f.addTrack(p);let C=h.current;C&&(C.srcObject=f)}p&&D("track-attach"),E(p!==null),v.current?.(p)}},[R,D]),U=(0,X.useCallback)(p=>{h.current=p,p&&(i&&(p.muted=!0,p.defaultMuted=!0,p.setAttribute("muted","")),p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),R())},[R,i]);(0,X.useImperativeHandle)(r,()=>({get element(){return h.current},get live(){return w.current?w.current.getVideoTracks().length>0:!1}}),[]);let l=s!==void 0;return(0,X.useEffect)(()=>{if(l){M(s??null);return}if(!P)return;let p=P.stream(n),f=()=>{let k=w.current;return k?k.getVideoTracks()[0]??null:null},C=k=>{if(k!==f()&&(M(k),k)){let L=()=>{f()===k&&M(null)};k.addEventListener("ended",L)}},I=p.track;I&&I.readyState==="live"&&C(I);let J=p.on("track",k=>{k&&k.readyState!=="live"||C(k)}),A=setInterval(()=>{let k=p.track;k&&k.readyState==="live"&&C(k)},Qn);return()=>{J(),clearInterval(A)}},[P,n,l,s,M]),(0,ht.jsxs)("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...g},"data-urun-video":"","data-urun-video-live":x?"true":"false",children:[(0,ht.jsx)("video",{ref:U,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),x?null:S,y]})});var en=require("react");var rn=require("react/jsx-runtime"),tn=(0,en.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,rn.jsx)(St,{ref:r,stream:o,...n})});var O=require("react"),on=require("@urun-sh/core");var vt=null;function to(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function et(){if(vt)return vt;let e=to();return e?(vt=new e,vt):null}function tt(){let e=et();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var an=require("react/jsx-runtime"),ro=1e3,nn=200;function nr(...e){console.debug("[audio]",...e)}var rt=(0,O.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,d=ce(),S=o??d,y=(0,O.useRef)(null),b=(0,O.useRef)(null),m=(0,O.useRef)(null),P=(0,O.useRef)(null),h=(0,O.useRef)(u);h.current=u;let w=(0,O.useRef)(c);w.current=c;let x=(0,O.useCallback)(l=>{m.current!==l&&(m.current=l,w.current?.(l))},[]),E=(0,O.useCallback)(()=>{if(typeof MediaStream>"u")return null;b.current||(b.current=new MediaStream);let l=y.current;return l&&l.srcObject!==b.current&&(l.srcObject=b.current),b.current},[]),v=(0,O.useCallback)(l=>{let p=y.current;if(!p)return;let f=p.play();!f||typeof f.then!="function"||f.then(()=>{p.muted||x(!0)}).catch(C=>{let I=C instanceof Error?C.name:String(C);if(I==="AbortError"){nr(`play() aborted (${l}); retrying in ${nn}ms`),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{P.current=null,v(`${l}:retry`)},nn);return}if(I==="NotAllowedError"){nr(`play() blocked pending a user gesture (${l})`),x(!1);return}nr(`play() failed (${l})`,C)})},[x]),R=(0,O.useCallback)(l=>{let p=E();if(p){for(let f of p.getAudioTracks())f!==l&&p.removeTrack(f);l&&!p.getAudioTracks().includes(l)&&p.addTrack(l),l&&v("track-attach"),h.current?.(l)}},[E,v]),D=(0,O.useCallback)(()=>{let l=y.current;l&&(E(),l.muted=!1,v("gesture"),tt(),x(!0))},[E,v,x]);(0,O.useImperativeHandle)(r,()=>({unlock:D,get unlocked(){return m.current===!0},get element(){return y.current}}),[D]);let M=(0,O.useCallback)(l=>{y.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),E()),g?.(l)},[E,g]),U=s!==void 0;return(0,O.useEffect)(()=>{if(U){R(s??null);return}if(!S)return;let l=S.stream(n),p=()=>{let A=b.current;return A?A.getAudioTracks()[0]??null:null},f=A=>{if(A!==p()&&(R(A),A)){let k=()=>{p()===A&&R(null)};A.addEventListener("ended",k)}},C=l.track;C&&C.readyState==="live"&&f(C);let I=l.on("track",A=>{A&&A.readyState!=="live"||f(A)}),J=setInterval(()=>{let A=l.track;A&&A.readyState==="live"&&f(A)},ro);return()=>{I(),clearInterval(J)}},[S,n,U,s,R]),(0,O.useEffect)(()=>(0,on.observePageLifecycle)(()=>{tt(),m.current===!0&&v("foreground")}),[v]),(0,O.useEffect)(()=>()=>{P.current&&clearTimeout(P.current)},[]),(0,an.jsx)("audio",{ref:M,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),sn=rt;var N=require("react"),Ve=require("@urun-sh/core");var cn=require("react/jsx-runtime"),or={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function yt(...e){console.debug("[voice]",...e)}var nt=(0,N.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=or,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:d,onMicStream:S,onTrack:y,onUnlockChange:b,capture:m}=t,P=ce(),h=o??P,w=(0,N.useRef)(null),x=(0,N.useRef)(null),E=(0,N.useRef)(null),v=(0,N.useRef)([]),R=(0,N.useRef)(!1),D=(0,N.useRef)(g);D.current=g;let M=(0,N.useRef)(d);M.current=d;let U=(0,N.useRef)(S);U.current=S;let l=(0,N.useCallback)(k=>{R.current!==k&&(R.current=k,D.current?.(k))},[]),p=(0,N.useCallback)(()=>{for(let k of v.current)k();v.current=[],E.current?.release(),E.current=null,x.current&&(x.current=null,U.current?.(null))},[]),f=(0,N.useCallback)(async()=>{let k=E.current;if(k){let V=await k.update(i);return x.current=k.stream,U.current?.(k.stream),V}let $=await(m??(0,Ve.sharedCaptureController)()).claim("audio",i);E.current=$,v.current=[$.onTrack((V,K)=>{x.current=K,U.current?.(K),R.current&&h?.stream(n).attach(V).catch(j=>yt("mic re-attach after one-capture re-acquire failed",j))}),$.onLost(V=>{E.current=null,v.current=[],x.current=null,U.current?.(null),l(!1),M.current?.(V)})],x.current=$.stream,U.current?.($.stream);let G=$.track;if(!G)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return G},[m,i,h,n,l]),C=(0,N.useCallback)(async()=>{p(),l(!1),await h?.stream(n).detach().catch(()=>{})},[h,n,p,l]),I=(0,N.useCallback)(async()=>{if(!h)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");w.current?.unlock();let k;try{k=await f()}catch(G){p();let V=(0,Ve.sessionFailureFromMediaError)(G,h.status);throw M.current?.(V),V}h.connect?.();let L;for(let G=1;G<=u;G++)try{await h.whenLive(a!==void 0?{timeout:a}:void 0),await h.stream(n).attach(k),l(!0);return}catch(V){L=V,yt(`start attempt ${G}/${u} failed`,V),G<u&&await new Promise(K=>setTimeout(K,c))}p(),l(!1);let $=L instanceof Error?L:new Error(String(L??"voice start failed"));throw M.current?.($),$},[h,n,a,u,c,f,p,l]);(0,N.useImperativeHandle)(r,()=>({start:I,stop:C,unlock:()=>w.current?.unlock(),get active(){return R.current},get micStream(){return x.current},get audio(){return w.current}}),[I,C]);let J=(0,N.useRef)(!1),A=(0,N.useCallback)(async()=>{if(!h||!R.current||J.current)return;let k=x.current?.getAudioTracks()[0]??null;if(k&&k.readyState==="live"){try{await h.stream(n).attach(k)}catch(L){yt("foreground mic re-assert failed (will retry on next pass)",L)}return}J.current=!0;try{let L=await f();await h.stream(n).attach(L)}catch(L){let $=L instanceof Error?L:new Error(String(L));yt("foreground mic re-acquire failed",$),M.current?.($)}finally{J.current=!1}},[h,n,f]);return(0,N.useEffect)(()=>{let k=()=>{A()};return h&&typeof h.onRecovery=="function"?h.onRecovery(k):(0,Ve.observePageLifecycle)(k)},[h,A]),(0,N.useEffect)(()=>p,[p]),s?(0,cn.jsx)(rt,{ref:w,session:h,stream:n,onTrack:y,onUnlockChange:b}):null}),un=nt;var ie=require("react");var kt=require("react");var sr={level:0,speaking:!1};function bt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,kt.useState)(sr);return(0,kt.useEffect)(()=>{if(!e){i(sr);return}let a=et();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let d=new Uint8Array(g.fftSize),y=setInterval(()=>{g.getByteTimeDomainData(d);let b=0;for(let P=0;P<d.length;P++){let h=(d[P]-128)/128;b+=h*h}let m=Math.sqrt(b/d.length);i(P=>{let h=m>n;return Math.abs(P.level-m)<.005&&P.speaking===h?P:{level:m,speaking:h}})},o);return()=>{clearInterval(y),c.disconnect(),i(sr)}},[e,r,o,n]),s}var me=require("react/jsx-runtime"),no={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},oo={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},ln=(0,ie.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:d,capture:S}=t,y=ce(),b=o??y,m=(0,ie.useRef)(null),[P,h]=(0,ie.useState)(null),w=(0,ie.useRef)(d);w.current=d;let{level:x,speaking:E}=bt(a?P:null);return(0,ie.useImperativeHandle)(r,()=>({start:()=>{let v=m.current;return v?v.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>m.current?.stop()??Promise.resolve(),get active(){return m.current?.active??!1},get micStream(){return m.current?.micStream??null}}),[]),(0,ie.useEffect)(()=>{!i||!b||m.current?.start().catch(()=>{})},[i,b]),(0,me.jsxs)(me.Fragment,{children:[(0,me.jsx)(nt,{ref:m,session:b,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...S!==void 0?{capture:S}:{},onActiveChange:c,onError:g,onMicStream:v=>{h(v),w.current?.(v)}}),a?(0,me.jsx)("span",{className:u,style:no,"data-urun-mic":"","data-urun-mic-active":P?"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(x*100)/100,children:(0,me.jsx)("span",{style:oo,children:(0,me.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(x*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var Pt=require("@urun-sh/core"),T=require("react");var ne=require("react/jsx-runtime"),ar={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function ir(...e){console.debug("[camera]",...e)}function so(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function io(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var ur=(0,T.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:d,visible:S=!1,className:y,videoClassName:b,onActiveChange:m,onError:P,onStream:h,onTrack:w,children:x,capture:E,flipControl:v="auto",flipControlClassName:R,onDevices:D}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let M=i?"user":a?"environment":u??"environment",U=ce(),l=o??U,p=(0,T.useRef)(null),f=(0,T.useRef)(null),C=(0,T.useRef)(null),I=(0,T.useRef)([]),J=(0,T.useRef)(null),A=(0,T.useRef)(!1),k=(0,T.useRef)(M),[L,$]=(0,T.useState)(M),[G,V]=(0,T.useState)(!1),[K,j]=(0,T.useState)(null),[W,q]=(0,T.useState)(!1),[Q]=(0,T.useState)(so),Re=(0,T.useRef)(m);Re.current=m;let at=(0,T.useRef)(P);at.current=P;let Ft=(0,T.useRef)(h);Ft.current=h;let ut=(0,T.useRef)(w);ut.current=w;let pr=(0,T.useRef)(D);pr.current=D;let Se=(0,T.useCallback)(_=>{A.current!==_&&(A.current=_,V(_),Re.current?.(_))},[]);(0,T.useEffect)(()=>{if(!G){j(null);return}let _=!1,F=()=>{io().then(re=>{_||(j(re),re&&pr.current?.(re))})};F();let Z=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof Z?.addEventListener=="function"?(Z.addEventListener("devicechange",F),()=>{_=!0,Z.removeEventListener?.("devicechange",F)}):()=>{_=!0}},[G]);let ct=(0,T.useCallback)(_=>{let F=p.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=_,_&&F.play()?.catch?.(Z=>ir("preview play() failed",Z)))},[]),le=(0,T.useCallback)(()=>{J.current?.(),J.current=null;for(let _ of I.current)_();I.current=[],C.current?.release(),C.current=null,f.current&&(f.current=null,Ft.current?.(null),ut.current?.(null)),ct(null)},[ct]),Ht=(0,T.useCallback)((_,F)=>{J.current?.(),f.current=F,ct(F),Ft.current?.(F);let Z=()=>{f.current===F&&(ir("camera track ended (device removed or permission revoked)"),le(),Se(!1))};_.addEventListener("ended",Z),J.current=()=>_.removeEventListener("ended",Z)},[ct,le,Se]),Ae=(0,T.useCallback)(async _=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let F={...ar,...s,facingMode:_},Z;try{let re=C.current;if(re)Z=await re.update(F);else{let $e=await(E??(0,Pt.sharedCaptureController)()).claim("video",F);if(C.current=$e,I.current=[$e.onTrack((Ke,On)=>{Ht(Ke,On),A.current&&l.stream(n).attachVideo(Ke).then(()=>ut.current?.(Ke)).catch(Ln=>ir("camera re-publish after one-capture re-acquire failed",Ln))}),$e.onLost(Ke=>{C.current=null,I.current=[],le(),Se(!1),at.current?.(Ke)})],!$e.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});Z=$e.track}}catch(re){let Ue=(0,Pt.sessionFailureFromMediaError)(re,l.status);throw at.current?.(Ue),Ue}k.current=_,$(_),Ht(Z,C.current?.stream??new MediaStream([Z]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(Z)}catch(re){le(),Se(!1);let Ue=re instanceof Error?re:new Error(String(re));throw at.current?.(Ue),Ue}ut.current?.(Z),Se(!0)},[l,n,s,d,E,Ht,le,Se]),mr=(0,T.useCallback)(_=>Ae(_?.facingMode??k.current),[Ae]),lt=(0,T.useCallback)(async _=>{A.current&&k.current===_||await Ae(_)},[Ae]),Wt=(0,T.useCallback)(()=>Ae(k.current==="environment"?"user":"environment"),[Ae]),fr=(0,T.useCallback)(async()=>{le(),Se(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,le,Se]);(0,T.useImperativeHandle)(r,()=>({start:mr,stop:fr,flip:Wt,setFacingMode:lt,get active(){return A.current},get facingMode(){return k.current},get stream(){return f.current},get element(){return p.current}}),[mr,fr,Wt,lt]);let gr=(0,T.useRef)(lt);if(gr.current=lt,(0,T.useEffect)(()=>{!c||!l||gr.current(M).catch(()=>{})},[c,l,M]),(0,T.useEffect)(()=>le,[le]),!S)return null;let _n=g==="auto"?L==="user":g,Nn=G&&(v===!0||v==="auto"&&Q&&(K?.length??0)>1),In=()=>{W||(q(!0),Wt().catch(()=>{}).finally(()=>q(!1)))};return(0,ne.jsxs)("div",{className:y,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":L,children:[(0,ne.jsx)("video",{ref:p,className:b,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",..._n?{transform:"scaleX(-1)"}:{}}}),Nn?(0,ne.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:In,disabled:W,className:R,style:R?{opacity:W?.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:W?.6:1},children:(0,ne.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,ne.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ne.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ne.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ne.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ne.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,x]})}),dn=(0,T.forwardRef)(function({preview:t=!0,...r},o){return(0,ne.jsx)(ur,{ref:o,...r,visible:t,autoStart:!1})});var Ct=require("react");function pn(e,t){let[r,o]=(0,Ct.useState)(null);return(0,Ct.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var gn=require("react");var Tt=require("react");var mn=require("zustand/vanilla"),fn=require("zustand"),ao=()=>{};function xt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,mn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):ao,u=(c=>(0,fn.useStore)(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function qe(e,t){let r=(0,Tt.useMemo)(()=>xt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Tt.useEffect)(()=>r.bind(),[r]),r}function Sn(e,t,r){let n=qe(e,t)(r??(a=>a)),s=(0,gn.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var Et=require("react");var ve=200;function fe(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Fe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function wt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Rt(e,t,r={}){let o=r.cap??200,[n,s]=(0,Et.useState)([]);return(0,Et.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>fe(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var ae=require("react/jsx-runtime");function hn({session:e,name:t,cap:r,className:o}){let n=Rt(e,t,{cap:r});return(0,ae.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,ae.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,ae.jsx)("code",{children:t}),(0,ae.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,ae.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,ae.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,ae.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,ae.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,ae.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Fe(s.payload)]},`${s.at}-${i}`))})]})}var ot=require("react");var te=require("react/jsx-runtime");function st({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,ot.useState)(""),[i,a]=(0,ot.useState)(null),u=(0,ot.useCallback)(()=>{let c=wt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,te.jsxs)("div",{className:"urun-doc-patch",children:[(0,te.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,te.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,te.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,te.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function vn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=qe(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,te.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,te.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,te.jsx)("code",{children:t}),(0,te.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,te.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,te.jsx)(st,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var At=require("react");var ge=require("react/jsx-runtime");function yn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function kn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,At.useState)([]);return(0,At.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>fe(u,{at:Date.now(),direction:"in",text:yn(Fe(a))},r))}):void 0),[e,t,r]),(0,ge.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,ge.jsx)(st,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>fe(u,{at:Date.now(),direction:"out",text:yn(a)},r))}}),(0,ge.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,ge.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,ge.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,ge.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,ge.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Ut=require("react");var we=require("react/jsx-runtime");function bn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Ut.useState)([]),a=t.join(","),u=r.join(",");return(0,Ut.useEffect)(()=>{if(i([]),!e)return;let c=(d,S)=>i(y=>fe(y,{at:Date.now(),kind:d,text:S},o)),g=[];g.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let S=e.stream(d);g.push(S.on("track",y=>c("track",`${d}: ${y?"track arrived":"track ended"}`)))}for(let d of r){let S=e.doc(d);g.push(S.on("change",()=>c("doc",`${d} changed`)))}return()=>g.forEach(d=>d())},[e,a,u,o]),(0,we.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,we.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,g)=>(0,we.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,we.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,we.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}var Dt=require("@urun-sh/core");var Mt=require("react");function oe(e){let[t,r]=(0,Mt.useState)(e?.phase??null);return(0,Mt.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var Cn=require("@urun-sh/core");var He=require("react"),Pn=require("@urun-sh/core");function _t(e){let t=oe(e),r=(0,Pn.isWakingPhase)(t?.name),o=(0,He.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,He.useState)(s);return(0,He.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var ye=require("react/jsx-runtime");function Nt({session:e,render:t,className:r}){let o=_t(e);return!o.waking||!o.phase?null:(0,ye.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,ye.jsxs)(ye.Fragment,{children:[(0,ye.jsx)("span",{className:"urun-session-waking-label",children:(0,Cn.describeSessionPhase)(o.phase)})," ",(0,ye.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Ot=require("react");var ke=require("react"),uo={event:null,elapsedMs:0};function It(e,t){let[r,o]=(0,ke.useState)(null),n=(0,ke.useRef)(0);(0,ke.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,ke.useState)(0);return(0,ke.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:uo}var We=require("react/jsx-runtime"),co={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 lo(e){let[t,r]=(0,Ot.useState)(!1);return(0,Ot.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function Lt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=It(e,t),i=lo(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,We.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,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:a.hint??co[u]})," ",(0,We.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var se=require("react/jsx-runtime"),po={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function xn({session:e,className:t}){let r=oe(e),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,se.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,se.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,se.jsx)("span",{className:"urun-session-status-label",children:po[o]}),n?(0,se.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function Tn({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=oe(e);if(s?.name==="live")return(0,se.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,se.jsx)(Lt,{session:e})]});let i=r?r(s):(0,se.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,Dt.isWakingPhase)(s.name)?(0,se.jsx)(Nt,{session:e}):s&&s.name!=="idle"?(0,Dt.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,se.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,se.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var Vt=require("react");var En=require("react/jsx-runtime");function cr(e){return oe(e)?.endsAt??null}function mo(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function wn({session:e,urgentMs:t=6e4,className:r}){let n=cr(e)?.getTime()??null,[s,i]=(0,Vt.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,Vt.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=mo(s);return(0,En.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var it=require("react/jsx-runtime"),fo=new Set(["expired","ended","error"]);function Rn({session:e,onNewSession:t,children:r,className:o}){let n=oe(e);if(!n||!fo.has(n.name))return null;let s=r?r(n):(0,it.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,it.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,it.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var be=require("react"),Ee=require("react/jsx-runtime");function lr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function dr(e){let t=(0,be.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,be.useState)(()=>t?lr(t.get("idle")):null);return(0,be.useEffect)(()=>{if(!t){o(null);return}return o(lr(t.get("idle"))),t.on("change",()=>o(lr(t.get("idle"))))},[t]),r}function go(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function An({session:e,onStillHere:t,className:r}){let o=dr(e),n=o?.deadlineEpochS??null,[s,i]=(0,be.useState)(null);if((0,be.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,Ee.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,Ee.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Ee.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Ee.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${go(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Ee.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var Be=require("react"),Un=require("@urun-sh/core");function Mn(e){let t=(0,Be.useContext)(_e),[r,o]=(0,Be.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,d=t?.authProvider;return(0,Be.useEffect)(()=>{if(!a||!u||!n||!s)return;let S=!1,y=()=>{(0,Un.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:d}).then(m=>{S||o(m)}).catch(()=>{})};y();let b=setInterval(y,Math.max(1,i)*1e3);return()=>{S=!0,clearInterval(b)}},[n,s,i,a,u,c,g,d]),r}var qt=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,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,Session,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,readOperatorToken,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client"
2
- import{a as Fr,b as Hr,c as rt}from"./chunk-WF2OBDSX.mjs";import{useEffect as $t,useMemo as Zr,useState as Ie}from"react";import{Component as Wr}from"react";import{jsx as qt,jsxs as Br}from"react/jsx-runtime";var be=class extends Wr{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Br("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:[qt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),qt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as $r}from"react";var me=$r(null);function se(e){return e&&e.trim()?e.trim():void 0}function ee(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return se(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return se(typeof process<"u"?process.env?.[e]:void 0)}}function Ne(){let e=ee("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ee("VERCEL_ENV")==="production"?"workos":ee("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function jr(){return Ne()==="workos"}import{useEffect as Kr,useRef as Jr}from"react";var zr="urun.operator_token",Ht=null,Ft="op",Xr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Wt(){return typeof window<"u"}function Bt(){return Ht}function Gr(){if(!Wt())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Ft);if(!r)return null;Ht=r,t.delete(Ft);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Yr(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function nt(e){let t=Jr(e);t.current=e,Kr(()=>{if(!Wt())return;Gr();let r=o=>{if(!Yr(o))return;let n=Bt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{jsx as Pe,jsxs as rn}from"react/jsx-runtime";var Qr="/api/urun-token";function en(e,t){return typeof e=="function"?e(t):e!==void 0?e:rn("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:[Pe("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Pe("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function tn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:a,sessionKey:i,tokenEndpoint:c,fallback:u,errorFallback:g,children:p}){let d=n===void 0&&t===void 0;if(!d&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!d&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let k=r??o;if(d&&(typeof k!="string"||k.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);let[x,b]=Ie(),[y,S]=Ie(),[T,C]=Ie(null),[E,h]=Ie(null);nt(F=>h({jwt:F}));let w=rt(),I=ee("NEXT_PUBLIC_SESSION_TOKEN")??ee("NEXT_PUBLIC_URUN_JWT"),U=Ne(),A=E!==null,l=U==="workos"&&!n&&!A&&!d,m=n??(U==="jwt"?I:void 0)??x??y?.token,f=A?E.jwt:m,P=s??ee("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),_=l&&!f,W=t??y?.orgId,R=e??y?.gatewayUrl,v=d&&y===void 0,N=d&&y!==void 0&&!R?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,q=T??N,B=Zr(()=>({appId:k,baseUrl:R??"",orgId:W??"",jwt:f,getAccessToken:l?w?.getAccessToken:void 0,authProvider:P,eventsUrl:a,sessionKey:i,priority:A?"preempt":void 0}),[k,w,R,P,f,a,W,i,l,A]),L=c??Qr;return $t(()=>{if(!d)return;let F=new AbortController;return C(null),(async()=>{try{let H=await fetch(L,{method:"POST",signal:F.signal});if(!H.ok)throw new Error(`[urun] token endpoint ${L} answered ${H.status}`);let V=await H.json(),O=typeof V.token=="string"?V.token:"",j=typeof V.orgId=="string"?V.orgId:"";if(!O||!j)throw new Error(`[urun] token endpoint ${L} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);S({token:O,orgId:j,gatewayUrl:typeof V.gatewayUrl=="string"?V.gatewayUrl:void 0})}catch(H){if(F.signal.aborted)return;C(H instanceof Error?H:new Error(String(H)))}})(),()=>F.abort()},[d,L]),$t(()=>{if(!l||!w)return;let F=!1,H=w;async function V(){try{let j=await H.getAccessToken();F||b(j??void 0)}catch{F||b(void 0)}}V();let O=window.setInterval(()=>{V()},6e4);return()=>{F=!0,window.clearInterval(O)}},[w,l]),Pe(be,{fallback:u,children:q?en(g,q):_||v?Pe("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Pe(me.Provider,{value:B,children:p})})}import{useContext as nn,useEffect as on,useMemo as jt,useReducer as sn,useRef as ot}from"react";import{App as an}from"@urun-sh/core";function un(e,t){return`${e}:${JSON.stringify(t??{})}`}function cn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var ie=new Map;var st=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,a=>{s(a),o()})}}dispose(){this._unsubscribeChange()}},it=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},at=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=i=>{fetch(t,{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(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new st(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new it(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function ln(){let e=nn(me);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=sn(a=>a+1,0),r=ot(new Map),o=ot(new Map),n=ot(null),s=jt(()=>an(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.priority]);return on(()=>{let a=n.current;if(a){n.current=null;for(let[i,c]of a){let u=ie.get(i);u===c&&o.current.get(i)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let i=new Map;for(let[c,u]of o.current){let g=ie.get(c);g===u&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),i.set(c,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let p=ie.get(c);!p||p.refCount!==0||(ie.delete(c),p.handle.disconnect())},0)))}n.current=i}},[]),jt(()=>new Proxy({},{get(a,i){if(typeof i=="string")return c=>{let u=un(i,c),g=r.current.get(u);if(g&&!g.disposed)return g;let p=cn(e,i,c),d=ie.get(p);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),ie.delete(p),o.current.get(p)===d&&o.current.delete(p),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new at(s[i](c),t,e.eventsUrl),refCount:0,disposeTimer:null},ie.set(p,d)),o.current.get(p)!==d&&(o.current.set(p,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(u,d.handle),d.handle}}}),[e,s])}import{useCallback as ut,useEffect as dn,useMemo as pn,useRef as Le,useState as ct}from"react";function fe(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function mn(e){return e instanceof Error?e:new Error(String(e))}function fn(e,t){let r=pn(()=>fe(e),[e]),[o,n]=ct(void 0),[s,a]=ct(null),[i,c]=ct(!1),u=Le(t);u.current=t;let g=Le(0),p=Le(null),d=Le(!0);dn(()=>(d.current=!0,()=>{d.current=!1,p.current?.abort()}),[]);let k=ut(async y=>{p.current?.abort();let S=new AbortController;p.current=S;let T=++g.current,C=()=>d.current&&g.current===T;C()&&(c(!0),a(null));try{let E=await r.request(y,{...u.current,signal:S.signal});return C()&&(n(E),c(!1),u.current?.onSuccess?.(E)),E}catch(E){let h=mn(E);throw C()&&(a(h),c(!1),u.current?.onError?.(h)),h}},[r]),x=ut(y=>{k(y).catch(()=>{})},[k]),b=ut(()=>{g.current++,p.current?.abort(),p.current=null,n(void 0),a(null),c(!1)},[]);return{mutate:x,mutateAsync:k,data:o,error:s,isPending:i,reset:b}}import{useCallback as Kt,useEffect as gn,useMemo as Sn,useRef as Oe,useState as lt}from"react";function Jt(e){return e instanceof Error?e:new Error(String(e))}var hn=e=>typeof e=="string"?e:String(e);function vn(e,t){let r=Sn(()=>fe(e),[e]),[o,n]=lt(""),[s,a]=lt(!1),[i,c]=lt(null),u=Oe(t);u.current=t;let g=Oe(0),p=Oe(null),d=Oe(!0);gn(()=>(d.current=!0,()=>{d.current=!1,p.current?.cancel(),p.current=null}),[]);let k=Kt(()=>{g.current++,p.current?.cancel(),p.current=null,d.current&&a(!1)},[]),x=Kt(async b=>{p.current?.cancel();let y=++g.current,S=()=>d.current&&g.current===y,T=u.current,C=T?.parseChunk??hn,E=T?.buildPayload??(f=>({prompt:f}));S()&&(n(""),c(null),a(!0));let{parseChunk:h,buildPayload:w,onFinish:I,onError:U,...A}=T??{},l="",m;try{m=r.requestStream(E(b),A),p.current=m}catch(f){let P=Jt(f);S()&&(c(P),a(!1),T?.onError?.(P));return}try{for await(let f of m){if(g.current!==y)break;l+=C(f),S()&&n(l)}S()&&(a(!1),T?.onFinish?.(l))}catch(f){let P=Jt(f);S()&&(c(P),a(!1),T?.onError?.(P))}finally{p.current===m&&(p.current=null)}},[r]);return{completion:o,complete:x,stop:k,isStreaming:s,error:i}}import{useCallback as zt,useEffect as yn,useMemo as kn,useRef as ge,useState as De}from"react";function Xt(e){return e instanceof Error?e:new Error(String(e))}var bn=e=>typeof e=="string"?e:String(e),Gt=0;function dt(e){return Gt+=1,`${e}-${Gt}`}function Pn(e,t){let r=kn(()=>fe(e),[e]),[o,n]=De(()=>(t?.initialMessages??[]).map(C=>({id:C.id??dt("msg"),role:C.role,content:C.content}))),[s,a]=De(""),[i,c]=De(!1),[u,g]=De(null),p=ge(t);p.current=t;let d=ge(o);d.current=o;let k=ge(s);k.current=s;let x=ge(0),b=ge(null),y=ge(!0);yn(()=>(y.current=!0,()=>{y.current=!1,b.current?.cancel(),b.current=null}),[]);let S=zt(()=>{x.current++,b.current?.cancel(),b.current=null,y.current&&c(!1)},[]),T=zt(async C=>{let E=C===void 0,h=(E?k.current:C)??"";if(!h.trim())return;b.current?.cancel();let I=++x.current,U=()=>y.current&&x.current===I,A=p.current,l=A?.parseChunk??bn,m={id:dt("msg"),role:"user",content:h},f={id:dt("msg"),role:"assistant",content:""},P=[...d.current,m].map(O=>({role:O.role,content:O.content})),_=[...d.current,m,f];d.current=_,n(_),E&&a(""),g(null),c(!0);let W=A?.buildPayload??(O=>({messages:O})),{initialMessages:R,parseChunk:v,buildPayload:N,onFinish:q,onError:B,...L}=A??{},F=O=>{n(j=>j.map(le=>le.id===f.id?{...le,content:O}:le))},H="",V;try{V=r.requestStream(W(P),L),b.current=V}catch(O){let j=Xt(O);U()&&(g(j),c(!1),A?.onError?.(j));return}try{for await(let O of V){if(x.current!==I)break;H+=l(O),U()&&F(H)}U()&&(c(!1),A?.onFinish?.({...f,content:H}))}catch(O){let j=Xt(O);U()&&(g(j),c(!1),A?.onError?.(j))}finally{b.current===V&&(b.current=null)}},[r]);return{messages:o,input:s,setInput:a,sendMessage:T,stop:S,isStreaming:i,error:u}}import{useCallback as te,useEffect as Yt,useMemo as Cn,useRef as Zt,useState as Qt}from"react";import{createInputPresencePublisher as xn,INPUT_PRESENCE_DEFAULT_HZ as Tn,INPUT_PRESENCE_FIELD as En}from"@urun-sh/core";var pt=[];function wn(e,t={}){let{field:r=En,hz:o=Tn}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,a=Cn(()=>s?xn({awareness:{setLocalStateField:(h,w)=>s.setField(h,w)},field:r,hz:o}):null,[s,r,o]),i=Zt(null);i.current=a;let[c,u]=Qt(!1),[g,p]=Qt(pt),d=Zt(!1);Yt(()=>{if(a)return()=>a.dispose()},[a]);let k=te(()=>{let h=i.current;p(h?h.heldKeys():pt)},[]),x=te(()=>{i.current?.clear(),p(pt)},[]);Yt(()=>{if(!n)return;let h=()=>!!n.pointerLockElement,w=()=>{if(h()){d.current=!1,u(!0);return}d.current||(u(!1),x())},I=f=>{h()&&(i.current?.keyDown(f.key),k())},U=f=>{i.current?.keyUp(f.key),k()},A=f=>{h()&&i.current?.movePointer(f.movementX,f.movementY)},l=f=>{h()&&i.current?.setButtons(f.buttons)},m=()=>{x()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",I),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",m),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",I),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",m)}},[n,x,k]);let b=te(h=>{h.requestPointerLock?.()},[]),y=te(()=>{d.current=!0,u(!0)},[]),S=te(()=>{d.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),x()},[n,x]),T=te(h=>{i.current?.keyDown(h),k()},[k]),C=te(h=>{i.current?.keyUp(h),k()},[k]),E=te((h,w)=>{i.current?.movePointer(h,w)},[]);return{engage:b,engageTouch:y,release:S,engaged:c,heldKeys:g,pressKey:T,releaseKey:C,movePointer:E}}var er=new Map;function Rn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);er.set(e,{component:t,schema:r})}function tr(e,t){let r=er.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as Un,jsx as Ve}from"react/jsx-runtime";function An({name:e,props:t,fallback:r}){let o=tr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?Ve(Un,{children:r}):Ve("div",{className:"urun-component-error",role:"alert",children:Ve("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return Ve(n,{...o.validatedProps})}import{z as Ce}from"zod";import{jsx as mt,jsxs as rr}from"react/jsx-runtime";var Mn=Ce.object({step:Ce.number().min(0),total:Ce.number().min(1),label:Ce.string().optional(),variant:Ce.enum(["default","success","error"]).default("default")});function nr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),a=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:a}}function _n(e){let{step:t,total:r,label:o,variant:n,percentage:s}=nr(e);return rr("div",{className:"urun-progress-card","data-variant":n,children:[o&&mt("div",{className:"urun-progress-label",children:o}),mt("div",{className:"urun-progress-bar",children:mt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),rr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as ft}from"zod";import{jsx as or,jsxs as On}from"react/jsx-runtime";var Nn=ft.object({state:ft.enum(["thinking","generating","idle","error"]),message:ft.string().optional()}),In={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function sr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??In[t]??t;return{state:t,message:n,isActive:o}}function Ln(e){let{state:t,message:r,isActive:o}=sr(e);return On("span",{className:"urun-status-badge","data-state":t,children:[or("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),or("span",{className:"urun-status-message",children:r})]})}import{useRef as ir,useEffect as Dn}from"react";import{z as gt}from"zod";import{jsx as ar,jsxs as Fn}from"react/jsx-runtime";var Vn=gt.object({text:gt.string(),streaming:gt.boolean().default(!1)});function ur(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function qn(e){let{text:t,streaming:r}=ur(e),o=ir(null),n=ir(0);return Dn(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Fn("div",{className:"urun-text-stream",children:[ar("span",{ref:o,className:"urun-text-content"}),r&&ar("span",{className:"urun-text-cursor"})]})}import{z as qe}from"zod";import{jsx as cr,jsxs as Bn}from"react/jsx-runtime";var Hn=qe.object({src:qe.string().url(),alt:qe.string().optional(),caption:qe.string().optional()});function lr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Wn(e){let{src:t,alt:r,caption:o}=lr(e);return Bn("figure",{className:"urun-image-frame",children:[cr("img",{className:"urun-image",src:t,alt:r}),o&&cr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as re}from"zod";import{jsx as St,jsxs as Kn}from"react/jsx-runtime";var $n=re.object({metrics:re.array(re.object({label:re.string(),value:re.union([re.string(),re.number()]),unit:re.string().optional()}))});function dr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function jn(e){let{metrics:t}=dr(e);return St("div",{className:"urun-metrics-panel",children:t.map((r,o)=>Kn("div",{className:"urun-metric-card",children:[St("div",{className:"urun-metric-label",children:r.label}),St("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{createContext as Jn,useContext as pr}from"react";import{jsx as Gn}from"react/jsx-runtime";var ht=Jn(null);function zn({session:e,children:t}){return Gn(ht.Provider,{value:e,children:t})}function X(){return pr(ht)}function Xn(){let e=pr(ht);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{forwardRef as Yn,useCallback as Fe,useEffect as Zn,useImperativeHandle as Qn,useRef as vt,useState as eo}from"react";import{jsx as no,jsxs as oo}from"react/jsx-runtime";var to=1e3;function ro(...e){console.debug("[video]",...e)}var yt=Yn(function(t,r){let{session:o,stream:n="video",track:s,muted:a=!0,mirror:i=!1,objectFit:c="contain",className:u,style:g,videoClassName:p,placeholder:d,children:k,onTrack:x}=t,b=X(),y=o??b,S=vt(null),T=vt(null),[C,E]=eo(!1),h=vt(x);h.current=x;let w=Fe(()=>{if(typeof MediaStream>"u")return null;T.current||(T.current=new MediaStream);let m=S.current;return m&&m.srcObject!==T.current&&(m.srcObject=T.current),T.current},[]),I=Fe(m=>{let f=S.current;if(!f)return;let P=f.play();!P||typeof P.catch!="function"||P.catch(_=>ro(`play() failed (${m})`,_))},[]),U=Fe(m=>{let f=w();if(f){for(let P of f.getVideoTracks())P!==m&&f.removeTrack(P);if(m&&!f.getVideoTracks().includes(m)){f.addTrack(m);let P=S.current;P&&(P.srcObject=f)}m&&I("track-attach"),E(m!==null),h.current?.(m)}},[w,I]),A=Fe(m=>{S.current=m,m&&(a&&(m.muted=!0,m.defaultMuted=!0,m.setAttribute("muted","")),m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),w())},[w,a]);Qn(r,()=>({get element(){return S.current},get live(){return T.current?T.current.getVideoTracks().length>0:!1}}),[]);let l=s!==void 0;return Zn(()=>{if(l){U(s??null);return}if(!y)return;let m=y.stream(n),f=()=>{let v=T.current;return v?v.getVideoTracks()[0]??null:null},P=v=>{if(v!==f()&&(U(v),v)){let N=()=>{f()===v&&U(null)};v.addEventListener("ended",N)}},_=m.track;_&&_.readyState==="live"&&P(_);let W=m.on("track",v=>{v&&v.readyState!=="live"||P(v)}),R=setInterval(()=>{let v=m.track;v&&v.readyState==="live"&&P(v)},to);return()=>{W(),clearInterval(R)}},[y,n,l,s,U]),oo("div",{className:u,style:{position:"relative",width:"100%",height:"100%",...g},"data-urun-video":"","data-urun-video-live":C?"true":"false",children:[no("video",{ref:A,className:p,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...i?{transform:"scaleX(-1)"}:{}}}),C?null:d,k]})});import{forwardRef as so}from"react";import{jsx as ao}from"react/jsx-runtime";var io=so(function(t,r){let{stream:o="image",...n}=t;return ao(yt,{ref:r,stream:o,...n})});import{forwardRef as co,useCallback as Se,useEffect as kt,useImperativeHandle as lo,useRef as he}from"react";import{observePageLifecycle as po}from"@urun-sh/core";var He=null;function uo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function We(){if(He)return He;let e=uo();return e?(He=new e,He):null}function Be(){let e=We();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as go}from"react/jsx-runtime";var mo=1e3,mr=200;function bt(...e){console.debug("[audio]",...e)}var $e=co(function(t,r){let{session:o,stream:n="audio",track:s,controls:a=!1,className:i,onTrack:c,onUnlockChange:u,onAudioElement:g}=t,p=X(),d=o??p,k=he(null),x=he(null),b=he(null),y=he(null),S=he(c);S.current=c;let T=he(u);T.current=u;let C=Se(l=>{b.current!==l&&(b.current=l,T.current?.(l))},[]),E=Se(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let l=k.current;return l&&l.srcObject!==x.current&&(l.srcObject=x.current),x.current},[]),h=Se(l=>{let m=k.current;if(!m)return;let f=m.play();!f||typeof f.then!="function"||f.then(()=>{m.muted||C(!0)}).catch(P=>{let _=P instanceof Error?P.name:String(P);if(_==="AbortError"){bt(`play() aborted (${l}); retrying in ${mr}ms`),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,h(`${l}:retry`)},mr);return}if(_==="NotAllowedError"){bt(`play() blocked pending a user gesture (${l})`),C(!1);return}bt(`play() failed (${l})`,P)})},[C]),w=Se(l=>{let m=E();if(m){for(let f of m.getAudioTracks())f!==l&&m.removeTrack(f);l&&!m.getAudioTracks().includes(l)&&m.addTrack(l),l&&h("track-attach"),S.current?.(l)}},[E,h]),I=Se(()=>{let l=k.current;l&&(E(),l.muted=!1,h("gesture"),Be(),C(!0))},[E,h,C]);lo(r,()=>({unlock:I,get unlocked(){return b.current===!0},get element(){return k.current}}),[I]);let U=Se(l=>{k.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),E()),g?.(l)},[E,g]),A=s!==void 0;return kt(()=>{if(A){w(s??null);return}if(!d)return;let l=d.stream(n),m=()=>{let R=x.current;return R?R.getAudioTracks()[0]??null:null},f=R=>{if(R!==m()&&(w(R),R)){let v=()=>{m()===R&&w(null)};R.addEventListener("ended",v)}},P=l.track;P&&P.readyState==="live"&&f(P);let _=l.on("track",R=>{R&&R.readyState!=="live"||f(R)}),W=setInterval(()=>{let R=l.track;R&&R.readyState==="live"&&f(R)},mo);return()=>{_(),clearInterval(W)}},[d,n,A,s,w]),kt(()=>po(()=>{Be(),b.current===!0&&h("foreground")}),[h]),kt(()=>()=>{y.current&&clearTimeout(y.current)},[]),go("audio",{ref:U,className:i,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})}),fo=$e;import{forwardRef as So,useCallback as ve,useEffect as fr,useImperativeHandle as ho,useRef as Y}from"react";import{observePageLifecycle as vo,sessionFailureFromMediaError as yo,sharedCaptureController as ko}from"@urun-sh/core";import{jsx as Po}from"react/jsx-runtime";var gr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function je(...e){console.debug("[voice]",...e)}var Ke=So(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:a=gr,connectTimeoutMs:i,attempts:c=3,retryDelayMs:u=1500,onActiveChange:g,onError:p,onMicStream:d,onTrack:k,onUnlockChange:x,capture:b}=t,y=X(),S=o??y,T=Y(null),C=Y(null),E=Y(null),h=Y([]),w=Y(!1),I=Y(g);I.current=g;let U=Y(p);U.current=p;let A=Y(d);A.current=d;let l=ve(v=>{w.current!==v&&(w.current=v,I.current?.(v))},[]),m=ve(()=>{for(let v of h.current)v();h.current=[],E.current?.release(),E.current=null,C.current&&(C.current=null,A.current?.(null))},[]),f=ve(async()=>{let v=E.current;if(v){let L=await v.update(a);return C.current=v.stream,A.current?.(v.stream),L}let q=await(b??ko()).claim("audio",a);E.current=q,h.current=[q.onTrack((L,F)=>{C.current=F,A.current?.(F),w.current&&S?.stream(n).attach(L).catch(H=>je("mic re-attach after one-capture re-acquire failed",H))}),q.onLost(L=>{E.current=null,h.current=[],C.current=null,A.current?.(null),l(!1),U.current?.(L)})],C.current=q.stream,A.current?.(q.stream);let B=q.track;if(!B)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return B},[b,a,S,n,l]),P=ve(async()=>{m(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,m,l]),_=ve(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");T.current?.unlock();let v;try{v=await f()}catch(B){m();let L=yo(B,S.status);throw U.current?.(L),L}S.connect?.();let N;for(let B=1;B<=c;B++)try{await S.whenLive(i!==void 0?{timeout:i}:void 0),await S.stream(n).attach(v),l(!0);return}catch(L){N=L,je(`start attempt ${B}/${c} failed`,L),B<c&&await new Promise(F=>setTimeout(F,u))}m(),l(!1);let q=N instanceof Error?N:new Error(String(N??"voice start failed"));throw U.current?.(q),q},[S,n,i,c,u,f,m,l]);ho(r,()=>({start:_,stop:P,unlock:()=>T.current?.unlock(),get active(){return w.current},get micStream(){return C.current},get audio(){return T.current}}),[_,P]);let W=Y(!1),R=ve(async()=>{if(!S||!w.current||W.current)return;let v=C.current?.getAudioTracks()[0]??null;if(v&&v.readyState==="live"){try{await S.stream(n).attach(v)}catch(N){je("foreground mic re-assert failed (will retry on next pass)",N)}return}W.current=!0;try{let N=await f();await S.stream(n).attach(N)}catch(N){let q=N instanceof Error?N:new Error(String(N));je("foreground mic re-acquire failed",q),U.current?.(q)}finally{W.current=!1}},[S,n,f]);return fr(()=>{let v=()=>{R()};return S&&typeof S.onRecovery=="function"?S.onRecovery(v):vo(v)},[S,R]),fr(()=>m,[m]),s?Po($e,{ref:T,session:S,stream:n,onTrack:k,onUnlockChange:x}):null}),bo=Ke;import{forwardRef as To,useEffect as Eo,useImperativeHandle as wo,useRef as Sr,useState as Ro}from"react";import{useEffect as Co,useState as xo}from"react";var Pt={level:0,speaking:!1};function Ct(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,a]=xo(Pt);return Co(()=>{if(!e){a(Pt);return}let i=We();if(!i||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,g;try{u=i.createMediaStreamSource(c),g=i.createAnalyser(),g.fftSize=r,u.connect(g)}catch{return}let p=new Uint8Array(g.fftSize),k=setInterval(()=>{g.getByteTimeDomainData(p);let x=0;for(let y=0;y<p.length;y++){let S=(p[y]-128)/128;x+=S*S}let b=Math.sqrt(x/p.length);a(y=>{let S=b>n;return Math.abs(y.level-b)<.005&&y.speaking===S?y:{level:b,speaking:S}})},o);return()=>{clearInterval(k),u.disconnect(),a(Pt)}},[e,r,o,n]),s}import{Fragment as _o,jsx as Je,jsxs as No}from"react/jsx-runtime";var Ao={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Uo={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Mo=To(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:a=!0,visible:i=!1,className:c,onActiveChange:u,onError:g,onMicStream:p,capture:d}=t,k=X(),x=o??k,b=Sr(null),[y,S]=Ro(null),T=Sr(p);T.current=p;let{level:C,speaking:E}=Ct(i?y:null);return wo(r,()=>({start:()=>{let h=b.current;return h?h.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>b.current?.stop()??Promise.resolve(),get active(){return b.current?.active??!1},get micStream(){return b.current?.micStream??null}}),[]),Eo(()=>{!a||!x||b.current?.start().catch(()=>{})},[a,x]),No(_o,{children:[Je(Ke,{ref:b,session:x,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...d!==void 0?{capture:d}:{},onActiveChange:u,onError:g,onMicStream:h=>{S(h),T.current?.(h)}}),i?Je("span",{className:c,style:Ao,"data-urun-mic":"","data-urun-mic-active":y?"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(C*100)/100,children:Je("span",{style:Uo,children:Je("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(C*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{sessionFailureFromMediaError as Io,sharedCaptureController as Lo}from"@urun-sh/core";import{forwardRef as vr,useCallback as Z,useEffect as xt,useImperativeHandle as Oo,useRef as K,useState as xe}from"react";import{jsx as ne,jsxs as hr}from"react/jsx-runtime";var yr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Tt(...e){console.debug("[camera]",...e)}function Do(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Vo(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var kr=vr(function(t,r){let{session:o,stream:n="video",constraints:s,front:a=!1,back:i=!1,facingMode:c,autoStart:u=!0,mirror:g="auto",connectTimeoutMs:p,visible:d=!1,className:k,videoClassName:x,onActiveChange:b,onError:y,onStream:S,onTrack:T,children:C,capture:E,flipControl:h="auto",flipControlClassName:w,onDevices:I}=t;if(a&&i)throw new Error("<Camera> takes `front` OR `back`, not both");let U=a?"user":i?"environment":c??"environment",A=X(),l=o??A,m=K(null),f=K(null),P=K(null),_=K([]),W=K(null),R=K(!1),v=K(U),[N,q]=xe(U),[B,L]=xe(!1),[F,H]=xe(null),[V,O]=xe(!1),[j]=xe(Do),le=K(b);le.current=b;let Ae=K(y);Ae.current=y;let Qe=K(S);Qe.current=S;let Ue=K(T);Ue.current=T;let Lt=K(I);Lt.current=I;let Q=Z(M=>{R.current!==M&&(R.current=M,L(M),le.current?.(M))},[]);xt(()=>{if(!B){H(null);return}let M=!1,D=()=>{Vo().then(J=>{M||(H(J),J&&Lt.current?.(J))})};D();let $=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof $?.addEventListener=="function"?($.addEventListener("devicechange",D),()=>{M=!0,$.removeEventListener?.("devicechange",D)}):()=>{M=!0}},[B]);let Me=Z(M=>{let D=m.current;D&&(D.muted=!0,D.defaultMuted=!0,D.setAttribute("muted",""),D.setAttribute("playsinline",""),D.setAttribute("webkit-playsinline",""),D.srcObject=M,M&&D.play()?.catch?.($=>Tt("preview play() failed",$)))},[]),G=Z(()=>{W.current?.(),W.current=null;for(let M of _.current)M();_.current=[],P.current?.release(),P.current=null,f.current&&(f.current=null,Qe.current?.(null),Ue.current?.(null)),Me(null)},[Me]),et=Z((M,D)=>{W.current?.(),f.current=D,Me(D),Qe.current?.(D);let $=()=>{f.current===D&&(Tt("camera track ended (device removed or permission revoked)"),G(),Q(!1))};M.addEventListener("ended",$),W.current=()=>M.removeEventListener("ended",$)},[Me,G,Q]),de=Z(async M=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let D={...yr,...s,facingMode:M},$;try{let J=P.current;if(J)$=await J.update(D);else{let ye=await(E??Lo()).claim("video",D);if(P.current=ye,_.current=[ye.onTrack((ke,Vr)=>{et(ke,Vr),R.current&&l.stream(n).attachVideo(ke).then(()=>Ue.current?.(ke)).catch(qr=>Tt("camera re-publish after one-capture re-acquire failed",qr))}),ye.onLost(ke=>{P.current=null,_.current=[],G(),Q(!1),Ae.current?.(ke)})],!ye.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});$=ye.track}}catch(J){let pe=Io(J,l.status);throw Ae.current?.(pe),pe}v.current=M,q(M),et($,P.current?.stream??new MediaStream([$]));try{l.connect?.(),await l.whenLive(p!==void 0?{timeout:p}:void 0),await l.stream(n).attachVideo($)}catch(J){G(),Q(!1);let pe=J instanceof Error?J:new Error(String(J));throw Ae.current?.(pe),pe}Ue.current?.($),Q(!0)},[l,n,s,p,E,et,G,Q]),Ot=Z(M=>de(M?.facingMode??v.current),[de]),_e=Z(async M=>{R.current&&v.current===M||await de(M)},[de]),tt=Z(()=>de(v.current==="environment"?"user":"environment"),[de]),Dt=Z(async()=>{G(),Q(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,G,Q]);Oo(r,()=>({start:Ot,stop:Dt,flip:tt,setFacingMode:_e,get active(){return R.current},get facingMode(){return v.current},get stream(){return f.current},get element(){return m.current}}),[Ot,Dt,tt,_e]);let Vt=K(_e);if(Vt.current=_e,xt(()=>{!u||!l||Vt.current(U).catch(()=>{})},[u,l,U]),xt(()=>G,[G]),!d)return null;let Lr=g==="auto"?N==="user":g,Or=B&&(h===!0||h==="auto"&&j&&(F?.length??0)>1),Dr=()=>{V||(O(!0),tt().catch(()=>{}).finally(()=>O(!1)))};return hr("div",{className:k,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":N,children:[ne("video",{ref:m,className:x,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Lr?{transform:"scaleX(-1)"}:{}}}),Or?ne("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Dr,disabled:V,className:w,style:w?{opacity:V?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:V?.6:1},children:hr("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:[ne("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ne("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ne("path",{d:"M14.5 10.5v1.6h-1.6"}),ne("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ne("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,C]})}),qo=vr(function({preview:t=!0,...r},o){return ne(kr,{ref:o,...r,visible:t,autoStart:!1})});import{useEffect as Fo,useState as Ho}from"react";function Wo(e,t){let[r,o]=Ho(null);return Fo(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as zo}from"react";import{useEffect as Ko,useMemo as Jo}from"react";import{createStore as Bo}from"zustand/vanilla";import{useStore as $o}from"zustand";var jo=()=>{};function Et(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=Bo(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,a=()=>{if(s){for(let u of s)u();s=null}},i=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),a):jo,c=(u=>$o(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:i,unbind:a}),t.bind!==!1&&i(),c}function Te(e,t){let r=Jo(()=>Et(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Ko(()=>r.bind(),[r]),r}function Xo(e,t,r){let n=Te(e,t)(r??(i=>i)),s=zo(i=>{e&&t&&e.doc(t).set(i)},[e,t]);if(r)return n;let a=n;return{snapshot:e&&t?a.doc:null,synced:a.synced,set:s}}import{useEffect as Go,useState as Yo}from"react";var ae=200;function oe(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Ee(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function wt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Rt(e,t,r={}){let o=r.cap??200,[n,s]=Yo([]);return Go(()=>{if(s([]),!e||!t)return;let a=!0,i=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await i.next();if(!a||c.done)break;s(u=>oe(u,{at:Date.now(),payload:c.value},o))}})(),()=>{a=!1,i.return?.()}},[e,t,o]),n}import{jsx as ze,jsxs as we}from"react/jsx-runtime";function Zo({session:e,name:t,cap:r,className:o}){let n=Rt(e,t,{cap:r});return we("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[we("div",{className:"urun-stream-tail-meta",children:[ze("code",{children:t}),we("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),ze("div",{className:"urun-stream-tail-log",children:n.length===0?we("span",{className:"urun-stream-tail-empty",children:["Waiting for ",ze("code",{children:t})," messages\u2026"]}):n.map((s,a)=>we("div",{className:"urun-stream-tail-line",children:[ze("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Ee(s.payload)]},`${s.at}-${a}`))})]})}import{useCallback as Qo,useState as br}from"react";import{jsx as ue,jsxs as Xe}from"react/jsx-runtime";function Ge({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=br(""),[a,i]=br(null),c=Qo(()=>{let u=wt(n);if(!u.ok){i(u.error);return}i(null),o(u.value,n.trim()),s("")},[n,o]);return Xe("div",{className:"urun-doc-patch",children:[ue("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),Xe("div",{className:"urun-doc-patch-actions",children:[ue("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),a?ue("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function es({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Te(e,t),a=s(u=>u.doc),i=s(u=>u.synced),c=s(u=>u.set);return Xe("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[Xe("div",{className:"urun-doc-panel-meta",children:[ue("code",{children:t}),ue("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),ue("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),r?ue(Ge,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}import{useEffect as ts,useState as rs}from"react";import{jsx as Re,jsxs as Cr}from"react/jsx-runtime";function Pr(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ns({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=rs([]);return ts(()=>(s([]),e?e.doc(t).on("change",i=>{s(c=>oe(c,{at:Date.now(),direction:"in",text:Pr(Ee(i))},r))}):void 0),[e,t,r]),Cr("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Re(Ge,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(a,i)=>{e?.doc(t).set(a),s(c=>oe(c,{at:Date.now(),direction:"out",text:Pr(i)},r))}}),Re("div",{className:"urun-control-sender-log",children:n.length===0?Re("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((a,i)=>Cr("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[Re("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",Re("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${i}`))})]})}import{useEffect as os,useState as ss}from"react";import{jsx as Ye,jsxs as as}from"react/jsx-runtime";function is({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,a]=ss([]),i=t.join(","),c=r.join(",");return os(()=>{if(a([]),!e)return;let u=(p,d)=>a(k=>oe(k,{at:Date.now(),kind:p,text:d},o)),g=[];g.push(e.onPhase(p=>u("phase",`phase \u2192 ${p.name}`)));for(let p of t){let d=e.stream(p);g.push(d.on("track",k=>u("track",`${p}: ${k?"track arrived":"track ended"}`)))}for(let p of r){let d=e.doc(p);g.push(d.on("change",()=>u("doc",`${p} changed`)))}return()=>g.forEach(p=>p())},[e,i,c,o]),Ye("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?Ye("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,g)=>as("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[Ye("span",{className:"urun-event-spine-kind",children:u.kind})," ",Ye("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${g}`))})}import{describeSessionPhase as Ps,isWakingPhase as Cs}from"@urun-sh/core";import{useEffect as us,useState as cs}from"react";function z(e){let[t,r]=cs(e?.phase??null);return us(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as fs}from"@urun-sh/core";import{useEffect as ls,useRef as ds,useState as ps}from"react";import{isWakingPhase as ms}from"@urun-sh/core";function At(e){let t=z(e),r=ms(t?.name),o=ds(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[a,i]=ps(s);return ls(()=>{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:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?a:0}}import{Fragment as gs,jsx as xr,jsxs as Tr}from"react/jsx-runtime";function Ut({session:e,render:t,className:r}){let o=At(e);return!o.waking||!o.phase?null:xr("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Tr(gs,{children:[xr("span",{className:"urun-session-waking-label",children:fs(o.phase)})," ",Tr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as vs,useState as ys}from"react";import{useEffect as Er,useRef as Ss,useState as wr}from"react";var hs={event:null,elapsedMs:0};function Mt(e,t){let[r,o]=wr(null),n=Ss(0);Er(()=>{if(o(null),!!e?.onActivation)return e.onActivation(i=>{t!==void 0&&i.stream!==t||(n.current=Date.now(),o(i))})},[e,t]);let[s,a]=wr(0);return Er(()=>{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}:hs}import{jsx as Rr,jsxs as Ar}from"react/jsx-runtime";var ks={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 bs(e){let[t,r]=ys(!1);return vs(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function _t({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Mt(e,t),a=bs(r),i=s.event;if(!i||i.state==="first-media"||a)return null;let c=i.state;return Rr("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):Ar("div",{className:"urun-activation-overlay-card",children:[Rr("span",{className:"urun-activation-overlay-copy",children:i.hint??ks[c]})," ",Ar("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as ce,jsxs as Nt}from"react/jsx-runtime";var xs={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Ts({session:e,className:t}){let r=z(e),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 Nt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[ce("span",{className:"urun-session-status-dot","data-phase":o}),ce("span",{className:"urun-session-status-label",children:xs[o]}),n?ce("span",{className:"urun-session-status-detail",children:n}):null]})}function Es({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=z(e);if(s?.name==="live")return Nt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,ce(_t,{session:e})]});let a=r?r(s):ce("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&Cs(s.name)?ce(Ut,{session:e}):s&&s.name!=="idle"?Ps(s):"Waiting for a live session\u2026"}),i=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Nt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[a,i?ce("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as ws,useState as Rs}from"react";import{jsx as Ms}from"react/jsx-runtime";function Ur(e){return z(e)?.endsAt??null}function As(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Us({session:e,urgentMs:t=6e4,className:r}){let n=Ur(e)?.getTime()??null,[s,a]=Rs(()=>n===null?null:Math.max(0,n-Date.now()));if(ws(()=>{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=As(s);return Ms("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${i}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:i})}import{jsx as Mr,jsxs as Is}from"react/jsx-runtime";var _s=new Set(["expired","ended","error"]);function Ns({session:e,onNewSession:t,children:r,className:o}){let n=z(e);if(!n||!_s.has(n.name))return null;let s=r?r(n):Mr("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 Is("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?Mr("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as _r,useMemo as Ls,useState as Nr}from"react";import{jsx as Ze,jsxs as Vs}from"react/jsx-runtime";function It(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Ir(e){let t=Ls(()=>e?e.doc("control"):null,[e]),[r,o]=Nr(()=>t?It(t.get("idle")):null);return _r(()=>{if(!t){o(null);return}return o(It(t.get("idle"))),t.on("change",()=>o(It(t.get("idle"))))},[t]),r}function Os(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Ds({session:e,onStillHere:t,className:r}){let o=Ir(e),n=o?.deadlineEpochS??null,[s,a]=Nr(null);if(_r(()=>{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||!e)return null;let i=()=>{e.touch?.(),t?.()};return Ze("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:Vs("div",{className:"urun-idle-warning-card",children:[Ze("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),Ze("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Os(s)} due to inactivity.`:"This session will end soon due to inactivity."}),Ze("button",{type:"button",className:"urun-idle-warning-confirm",onClick:i,children:"I'm still here"})]})})}import{useContext as qs,useEffect as Fs,useState as Hs}from"react";import{prewake as Ws}from"@urun-sh/core";function Bs(e){let t=qs(me),[r,o]=Hs(null),n=e.app??t?.appId,s=e.function,a=e.intervalS??60,i=t?.baseUrl,c=t?.orgId,u=t?.jwt,g=t?.getAccessToken,p=t?.authProvider;return Fs(()=>{if(!i||!c||!n||!s)return;let d=!1,k=()=>{Ws({baseUrl:i,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:g,authProvider:p}).then(b=>{d||o(b)}).catch(()=>{})};k();let x=setInterval(k,Math.max(1,a)*1e3);return()=>{d=!0,clearInterval(x)}},[n,s,a,i,c,u,g,p]),r}import{describeSessionPhase as qc,isWakingPhase as Fc}from"@urun-sh/core";export{$e as Audio,kr as Camera,An as ComponentRenderer,yr as DEFAULT_CAMERA_CONSTRAINTS,ae as DEFAULT_LOG_CAP,gr as DEFAULT_VOICE_CONSTRAINTS,Ge as DocPatchForm,io as Image,Wn as ImageFrame,Hn as ImageFrameSchema,jn as MetricsPanel,$n as MetricsPanelSchema,Mo as Mic,Xr as OPERATOR_CHORD_LABEL,zr as OPERATOR_TOKEN_STORAGE_KEY,_n as ProgressCard,Mn as ProgressCardSchema,zn as Session,Ln as StatusBadge,Nn as StatusBadgeSchema,qn as TextStream,Vn as TextStreamSchema,_t as UrunActivationOverlay,fo as UrunAudio,Fr as UrunAuthProvider,qo as UrunCamera,ns as UrunControlSender,es as UrunDocPanel,be as UrunErrorBoundary,is as UrunEventSpine,Ds as UrunIdleWarning,Hr as UrunJwtProvider,tn as UrunProvider,Us as UrunSessionClock,Ns as UrunSessionEnded,Es as UrunSessionGate,Ts as UrunSessionStatus,Ut as UrunSessionWaking,Zo as UrunStreamTail,bo as UrunVoice,yt as Video,Ke as Voice,Ne as authMode,Et as createDocStore,qc as describeSessionPhase,Ee as formatPayload,We as getUrunAudioContext,Fc as isWakingPhase,wt as parseJsonObject,oe as pushCapped,Bt as readOperatorToken,Rn as registerComponent,Be as resumeUrunAudioContext,ee as urunPublicEnv,Mt as useActivation,ln as useApp,Pn as useChat,vn as useCompletion,Te as useDocStore,lr as useImageFrame,wn as useInputPresence,dr as useMetricsPanel,nt as useOperatorOverride,nr as useProgressCard,fn as useRequest,Xn as useSession,Xo as useSessionDoc,Ur as useSessionEndsAt,Ir as useSessionIdle,z as useSessionPhase,Wo as useSessionTrack,At as useSessionWake,sr as useStatusBadge,Rt as useStreamMessages,ur as useTextStream,Ct as useUrunAudioLevel,rt as useUrunAuth,Bs as useUrunPrewake,jr as usesWorkOSAuth};
2
+ import{a as Fr,b as Hr,c as rt}from"./chunk-WF2OBDSX.mjs";import{useEffect as $t,useMemo as Zr,useState as Ie}from"react";import{Component as Wr}from"react";import{jsx as qt,jsxs as Br}from"react/jsx-runtime";var be=class extends Wr{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Br("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:[qt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),qt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as $r}from"react";var me=$r(null);function se(e){return e&&e.trim()?e.trim():void 0}function ee(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return se(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return se(typeof process<"u"?process.env?.[e]:void 0)}}function Ne(){let e=ee("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ee("VERCEL_ENV")==="production"?"workos":ee("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function jr(){return Ne()==="workos"}import{useEffect as Kr,useRef as Jr}from"react";var zr="urun.operator_token",Ht=null,Ft="op",Xr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Wt(){return typeof window<"u"}function Bt(){return Ht}function Gr(){if(!Wt())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Ft);if(!r)return null;Ht=r,t.delete(Ft);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Yr(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function nt(e){let t=Jr(e);t.current=e,Kr(()=>{if(!Wt())return;Gr();let r=o=>{if(!Yr(o))return;let n=Bt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{jsx as Pe,jsxs as rn}from"react/jsx-runtime";var Qr="/api/urun-token";function en(e,t){return typeof e=="function"?e(t):e!==void 0?e:rn("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:[Pe("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Pe("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function tn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,fallback:c,errorFallback:g,children:d}){let S=n===void 0&&t===void 0;if(!S&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!S&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let y=r??o;if(S&&(typeof y!="string"||y.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);let[b,m]=Ie(),[P,h]=Ie(),[T,x]=Ie(null),[w,v]=Ie(null);nt(F=>v({jwt:F}));let E=rt(),I=ee("NEXT_PUBLIC_SESSION_TOKEN")??ee("NEXT_PUBLIC_URUN_JWT"),U=Ne(),A=w!==null,l=U==="workos"&&!n&&!A&&!S,p=n??(U==="jwt"?I:void 0)??b??P?.token,f=A?w.jwt:p,C=s??ee("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),_=l&&!f,W=t??P?.orgId,R=e??P?.gatewayUrl,k=S&&P===void 0,N=S&&P!==void 0&&!R?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,q=T??N,B=Zr(()=>({appId:y,baseUrl:R??"",orgId:W??"",jwt:f,getAccessToken:l?E?.getAccessToken:void 0,authProvider:C,eventsUrl:i,sessionKey:a,priority:A?"preempt":void 0}),[y,E,R,C,f,i,W,a,l,A]),L=u??Qr;return $t(()=>{if(!S)return;let F=new AbortController;return x(null),(async()=>{try{let H=await fetch(L,{method:"POST",signal:F.signal});if(!H.ok)throw new Error(`[urun] token endpoint ${L} answered ${H.status}`);let V=await H.json(),O=typeof V.token=="string"?V.token:"",j=typeof V.orgId=="string"?V.orgId:"";if(!O||!j)throw new Error(`[urun] token endpoint ${L} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);h({token:O,orgId:j,gatewayUrl:typeof V.gatewayUrl=="string"?V.gatewayUrl:void 0})}catch(H){if(F.signal.aborted)return;x(H instanceof Error?H:new Error(String(H)))}})(),()=>F.abort()},[S,L]),$t(()=>{if(!l||!E)return;let F=!1,H=E;async function V(){try{let j=await H.getAccessToken();F||m(j??void 0)}catch{F||m(void 0)}}V();let O=window.setInterval(()=>{V()},6e4);return()=>{F=!0,window.clearInterval(O)}},[E,l]),Pe(be,{fallback:c,children:q?en(g,q):_||k?Pe("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Pe(me.Provider,{value:B,children:d})})}import{useContext as nn,useEffect as on,useMemo as jt,useReducer as sn,useRef as ot}from"react";import{App as an}from"@urun-sh/core";function un(e,t){return`${e}:${JSON.stringify(t??{})}`}function cn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var ie=new Map;var st=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},it=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},at=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new st(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new it(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function ln(){let e=nn(me);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=sn(i=>i+1,0),r=ot(new Map),o=ot(new Map),n=ot(null),s=jt(()=>an(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.priority]);return on(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=ie.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=ie.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let d=ie.get(u);!d||d.refCount!==0||(ie.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),jt(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=d=>{let S=un(u,d),y=r.current.get(S);if(y&&!y.disposed)return y;let b=cn(e,u,d),m=ie.get(b);return m?.handle.disposed&&(m.disposeTimer&&clearTimeout(m.disposeTimer),ie.delete(b),o.current.get(b)===m&&o.current.delete(b),m=void 0),m?m.disposeTimer&&(clearTimeout(m.disposeTimer),m.disposeTimer=null):(m={handle:new at(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},ie.set(b,m)),o.current.get(b)!==m&&(o.current.set(b,m),m.handle.addNotifier(t),m.refCount+=1),r.current.set(S,m.handle),m.handle};return i.set(u,g),g}})},[e,s])}import{useCallback as ut,useEffect as dn,useMemo as pn,useRef as Le,useState as ct}from"react";function fe(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function mn(e){return e instanceof Error?e:new Error(String(e))}function fn(e,t){let r=pn(()=>fe(e),[e]),[o,n]=ct(void 0),[s,i]=ct(null),[a,u]=ct(!1),c=Le(t);c.current=t;let g=Le(0),d=Le(null),S=Le(!0);dn(()=>(S.current=!0,()=>{S.current=!1,d.current?.abort()}),[]);let y=ut(async P=>{d.current?.abort();let h=new AbortController;d.current=h;let T=++g.current,x=()=>S.current&&g.current===T;x()&&(u(!0),i(null));try{let w=await r.request(P,{...c.current,signal:h.signal});return x()&&(n(w),u(!1),c.current?.onSuccess?.(w)),w}catch(w){let v=mn(w);throw x()&&(i(v),u(!1),c.current?.onError?.(v)),v}},[r]),b=ut(P=>{y(P).catch(()=>{})},[y]),m=ut(()=>{g.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:b,mutateAsync:y,data:o,error:s,isPending:a,reset:m}}import{useCallback as Kt,useEffect as gn,useMemo as Sn,useRef as Oe,useState as lt}from"react";function Jt(e){return e instanceof Error?e:new Error(String(e))}var hn=e=>typeof e=="string"?e:String(e);function vn(e,t){let r=Sn(()=>fe(e),[e]),[o,n]=lt(""),[s,i]=lt(!1),[a,u]=lt(null),c=Oe(t);c.current=t;let g=Oe(0),d=Oe(null),S=Oe(!0);gn(()=>(S.current=!0,()=>{S.current=!1,d.current?.cancel(),d.current=null}),[]);let y=Kt(()=>{g.current++,d.current?.cancel(),d.current=null,S.current&&i(!1)},[]),b=Kt(async m=>{d.current?.cancel();let P=++g.current,h=()=>S.current&&g.current===P,T=c.current,x=T?.parseChunk??hn,w=T?.buildPayload??(f=>({prompt:f}));h()&&(n(""),u(null),i(!0));let{parseChunk:v,buildPayload:E,onFinish:I,onError:U,...A}=T??{},l="",p;try{p=r.requestStream(w(m),A),d.current=p}catch(f){let C=Jt(f);h()&&(u(C),i(!1),T?.onError?.(C));return}try{for await(let f of p){if(g.current!==P)break;l+=x(f),h()&&n(l)}h()&&(i(!1),T?.onFinish?.(l))}catch(f){let C=Jt(f);h()&&(u(C),i(!1),T?.onError?.(C))}finally{d.current===p&&(d.current=null)}},[r]);return{completion:o,complete:b,stop:y,isStreaming:s,error:a}}import{useCallback as zt,useEffect as yn,useMemo as kn,useRef as ge,useState as De}from"react";function Xt(e){return e instanceof Error?e:new Error(String(e))}var bn=e=>typeof e=="string"?e:String(e),Gt=0;function dt(e){return Gt+=1,`${e}-${Gt}`}function Pn(e,t){let r=kn(()=>fe(e),[e]),[o,n]=De(()=>(t?.initialMessages??[]).map(x=>({id:x.id??dt("msg"),role:x.role,content:x.content}))),[s,i]=De(""),[a,u]=De(!1),[c,g]=De(null),d=ge(t);d.current=t;let S=ge(o);S.current=o;let y=ge(s);y.current=s;let b=ge(0),m=ge(null),P=ge(!0);yn(()=>(P.current=!0,()=>{P.current=!1,m.current?.cancel(),m.current=null}),[]);let h=zt(()=>{b.current++,m.current?.cancel(),m.current=null,P.current&&u(!1)},[]),T=zt(async x=>{let w=x===void 0,v=(w?y.current:x)??"";if(!v.trim())return;m.current?.cancel();let I=++b.current,U=()=>P.current&&b.current===I,A=d.current,l=A?.parseChunk??bn,p={id:dt("msg"),role:"user",content:v},f={id:dt("msg"),role:"assistant",content:""},C=[...S.current,p].map(O=>({role:O.role,content:O.content})),_=[...S.current,p,f];S.current=_,n(_),w&&i(""),g(null),u(!0);let W=A?.buildPayload??(O=>({messages:O})),{initialMessages:R,parseChunk:k,buildPayload:N,onFinish:q,onError:B,...L}=A??{},F=O=>{n(j=>j.map(le=>le.id===f.id?{...le,content:O}:le))},H="",V;try{V=r.requestStream(W(C),L),m.current=V}catch(O){let j=Xt(O);U()&&(g(j),u(!1),A?.onError?.(j));return}try{for await(let O of V){if(b.current!==I)break;H+=l(O),U()&&F(H)}U()&&(u(!1),A?.onFinish?.({...f,content:H}))}catch(O){let j=Xt(O);U()&&(g(j),u(!1),A?.onError?.(j))}finally{m.current===V&&(m.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:T,stop:h,isStreaming:a,error:c}}import{useCallback as te,useEffect as Yt,useMemo as Cn,useRef as Zt,useState as Qt}from"react";import{createInputPresencePublisher as xn,INPUT_PRESENCE_DEFAULT_HZ as Tn,INPUT_PRESENCE_FIELD as wn}from"@urun-sh/core";var pt=[];function En(e,t={}){let{field:r=wn,hz:o=Tn}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=Cn(()=>s?xn({awareness:{setLocalStateField:(v,E)=>s.setField(v,E)},field:r,hz:o}):null,[s,r,o]),a=Zt(null);a.current=i;let[u,c]=Qt(!1),[g,d]=Qt(pt),S=Zt(!1);Yt(()=>{if(i)return()=>i.dispose()},[i]);let y=te(()=>{let v=a.current;d(v?v.heldKeys():pt)},[]),b=te(()=>{a.current?.clear(),d(pt)},[]);Yt(()=>{if(!n)return;let v=()=>!!n.pointerLockElement,E=()=>{if(v()){S.current=!1,c(!0);return}S.current||(c(!1),b())},I=f=>{v()&&(a.current?.keyDown(f.key),y())},U=f=>{a.current?.keyUp(f.key),y()},A=f=>{v()&&a.current?.movePointer(f.movementX,f.movementY)},l=f=>{v()&&a.current?.setButtons(f.buttons)},p=()=>{b()};return n.addEventListener("pointerlockchange",E),n.addEventListener("keydown",I),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",p),()=>{n.removeEventListener("pointerlockchange",E),n.removeEventListener("keydown",I),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",p)}},[n,b,y]);let m=te(v=>{v.requestPointerLock?.()},[]),P=te(()=>{S.current=!0,c(!0)},[]),h=te(()=>{S.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),b()},[n,b]),T=te(v=>{a.current?.keyDown(v),y()},[y]),x=te(v=>{a.current?.keyUp(v),y()},[y]),w=te((v,E)=>{a.current?.movePointer(v,E)},[]);return{engage:m,engageTouch:P,release:h,engaged:u,heldKeys:g,pressKey:T,releaseKey:x,movePointer:w}}var er=new Map;function Rn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);er.set(e,{component:t,schema:r})}function tr(e,t){let r=er.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as Un,jsx as Ve}from"react/jsx-runtime";function An({name:e,props:t,fallback:r}){let o=tr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?Ve(Un,{children:r}):Ve("div",{className:"urun-component-error",role:"alert",children:Ve("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return Ve(n,{...o.validatedProps})}import{z as Ce}from"zod";import{jsx as mt,jsxs as rr}from"react/jsx-runtime";var Mn=Ce.object({step:Ce.number().min(0),total:Ce.number().min(1),label:Ce.string().optional(),variant:Ce.enum(["default","success","error"]).default("default")});function nr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function _n(e){let{step:t,total:r,label:o,variant:n,percentage:s}=nr(e);return rr("div",{className:"urun-progress-card","data-variant":n,children:[o&&mt("div",{className:"urun-progress-label",children:o}),mt("div",{className:"urun-progress-bar",children:mt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),rr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as ft}from"zod";import{jsx as or,jsxs as On}from"react/jsx-runtime";var Nn=ft.object({state:ft.enum(["thinking","generating","idle","error"]),message:ft.string().optional()}),In={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function sr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??In[t]??t;return{state:t,message:n,isActive:o}}function Ln(e){let{state:t,message:r,isActive:o}=sr(e);return On("span",{className:"urun-status-badge","data-state":t,children:[or("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),or("span",{className:"urun-status-message",children:r})]})}import{useRef as ir,useEffect as Dn}from"react";import{z as gt}from"zod";import{jsx as ar,jsxs as Fn}from"react/jsx-runtime";var Vn=gt.object({text:gt.string(),streaming:gt.boolean().default(!1)});function ur(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function qn(e){let{text:t,streaming:r}=ur(e),o=ir(null),n=ir(0);return Dn(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Fn("div",{className:"urun-text-stream",children:[ar("span",{ref:o,className:"urun-text-content"}),r&&ar("span",{className:"urun-text-cursor"})]})}import{z as qe}from"zod";import{jsx as cr,jsxs as Bn}from"react/jsx-runtime";var Hn=qe.object({src:qe.string().url(),alt:qe.string().optional(),caption:qe.string().optional()});function lr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Wn(e){let{src:t,alt:r,caption:o}=lr(e);return Bn("figure",{className:"urun-image-frame",children:[cr("img",{className:"urun-image",src:t,alt:r}),o&&cr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as re}from"zod";import{jsx as St,jsxs as Kn}from"react/jsx-runtime";var $n=re.object({metrics:re.array(re.object({label:re.string(),value:re.union([re.string(),re.number()]),unit:re.string().optional()}))});function dr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function jn(e){let{metrics:t}=dr(e);return St("div",{className:"urun-metrics-panel",children:t.map((r,o)=>Kn("div",{className:"urun-metric-card",children:[St("div",{className:"urun-metric-label",children:r.label}),St("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{createContext as Jn,useContext as pr}from"react";import{jsx as Gn}from"react/jsx-runtime";var ht=Jn(null);function zn({session:e,children:t}){return Gn(ht.Provider,{value:e,children:t})}function X(){return pr(ht)}function Xn(){let e=pr(ht);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{forwardRef as Yn,useCallback as Fe,useEffect as Zn,useImperativeHandle as Qn,useRef as vt,useState as eo}from"react";import{jsx as no,jsxs as oo}from"react/jsx-runtime";var to=1e3;function ro(...e){console.debug("[video]",...e)}var yt=Yn(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:g,videoClassName:d,placeholder:S,children:y,onTrack:b}=t,m=X(),P=o??m,h=vt(null),T=vt(null),[x,w]=eo(!1),v=vt(b);v.current=b;let E=Fe(()=>{if(typeof MediaStream>"u")return null;T.current||(T.current=new MediaStream);let p=h.current;return p&&p.srcObject!==T.current&&(p.srcObject=T.current),T.current},[]),I=Fe(p=>{let f=h.current;if(!f)return;let C=f.play();!C||typeof C.catch!="function"||C.catch(_=>ro(`play() failed (${p})`,_))},[]),U=Fe(p=>{let f=E();if(f){for(let C of f.getVideoTracks())C!==p&&f.removeTrack(C);if(p&&!f.getVideoTracks().includes(p)){f.addTrack(p);let C=h.current;C&&(C.srcObject=f)}p&&I("track-attach"),w(p!==null),v.current?.(p)}},[E,I]),A=Fe(p=>{h.current=p,p&&(i&&(p.muted=!0,p.defaultMuted=!0,p.setAttribute("muted","")),p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),E())},[E,i]);Qn(r,()=>({get element(){return h.current},get live(){return T.current?T.current.getVideoTracks().length>0:!1}}),[]);let l=s!==void 0;return Zn(()=>{if(l){U(s??null);return}if(!P)return;let p=P.stream(n),f=()=>{let k=T.current;return k?k.getVideoTracks()[0]??null:null},C=k=>{if(k!==f()&&(U(k),k)){let N=()=>{f()===k&&U(null)};k.addEventListener("ended",N)}},_=p.track;_&&_.readyState==="live"&&C(_);let W=p.on("track",k=>{k&&k.readyState!=="live"||C(k)}),R=setInterval(()=>{let k=p.track;k&&k.readyState==="live"&&C(k)},to);return()=>{W(),clearInterval(R)}},[P,n,l,s,U]),oo("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...g},"data-urun-video":"","data-urun-video-live":x?"true":"false",children:[no("video",{ref:A,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),x?null:S,y]})});import{forwardRef as so}from"react";import{jsx as ao}from"react/jsx-runtime";var io=so(function(t,r){let{stream:o="image",...n}=t;return ao(yt,{ref:r,stream:o,...n})});import{forwardRef as co,useCallback as Se,useEffect as kt,useImperativeHandle as lo,useRef as he}from"react";import{observePageLifecycle as po}from"@urun-sh/core";var He=null;function uo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function We(){if(He)return He;let e=uo();return e?(He=new e,He):null}function Be(){let e=We();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as go}from"react/jsx-runtime";var mo=1e3,mr=200;function bt(...e){console.debug("[audio]",...e)}var $e=co(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,d=X(),S=o??d,y=he(null),b=he(null),m=he(null),P=he(null),h=he(u);h.current=u;let T=he(c);T.current=c;let x=Se(l=>{m.current!==l&&(m.current=l,T.current?.(l))},[]),w=Se(()=>{if(typeof MediaStream>"u")return null;b.current||(b.current=new MediaStream);let l=y.current;return l&&l.srcObject!==b.current&&(l.srcObject=b.current),b.current},[]),v=Se(l=>{let p=y.current;if(!p)return;let f=p.play();!f||typeof f.then!="function"||f.then(()=>{p.muted||x(!0)}).catch(C=>{let _=C instanceof Error?C.name:String(C);if(_==="AbortError"){bt(`play() aborted (${l}); retrying in ${mr}ms`),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{P.current=null,v(`${l}:retry`)},mr);return}if(_==="NotAllowedError"){bt(`play() blocked pending a user gesture (${l})`),x(!1);return}bt(`play() failed (${l})`,C)})},[x]),E=Se(l=>{let p=w();if(p){for(let f of p.getAudioTracks())f!==l&&p.removeTrack(f);l&&!p.getAudioTracks().includes(l)&&p.addTrack(l),l&&v("track-attach"),h.current?.(l)}},[w,v]),I=Se(()=>{let l=y.current;l&&(w(),l.muted=!1,v("gesture"),Be(),x(!0))},[w,v,x]);lo(r,()=>({unlock:I,get unlocked(){return m.current===!0},get element(){return y.current}}),[I]);let U=Se(l=>{y.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),w()),g?.(l)},[w,g]),A=s!==void 0;return kt(()=>{if(A){E(s??null);return}if(!S)return;let l=S.stream(n),p=()=>{let R=b.current;return R?R.getAudioTracks()[0]??null:null},f=R=>{if(R!==p()&&(E(R),R)){let k=()=>{p()===R&&E(null)};R.addEventListener("ended",k)}},C=l.track;C&&C.readyState==="live"&&f(C);let _=l.on("track",R=>{R&&R.readyState!=="live"||f(R)}),W=setInterval(()=>{let R=l.track;R&&R.readyState==="live"&&f(R)},mo);return()=>{_(),clearInterval(W)}},[S,n,A,s,E]),kt(()=>po(()=>{Be(),m.current===!0&&v("foreground")}),[v]),kt(()=>()=>{P.current&&clearTimeout(P.current)},[]),go("audio",{ref:U,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),fo=$e;import{forwardRef as So,useCallback as ve,useEffect as fr,useImperativeHandle as ho,useRef as Y}from"react";import{observePageLifecycle as vo,sessionFailureFromMediaError as yo,sharedCaptureController as ko}from"@urun-sh/core";import{jsx as Po}from"react/jsx-runtime";var gr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function je(...e){console.debug("[voice]",...e)}var Ke=So(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=gr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:d,onMicStream:S,onTrack:y,onUnlockChange:b,capture:m}=t,P=X(),h=o??P,T=Y(null),x=Y(null),w=Y(null),v=Y([]),E=Y(!1),I=Y(g);I.current=g;let U=Y(d);U.current=d;let A=Y(S);A.current=S;let l=ve(k=>{E.current!==k&&(E.current=k,I.current?.(k))},[]),p=ve(()=>{for(let k of v.current)k();v.current=[],w.current?.release(),w.current=null,x.current&&(x.current=null,A.current?.(null))},[]),f=ve(async()=>{let k=w.current;if(k){let L=await k.update(i);return x.current=k.stream,A.current?.(k.stream),L}let q=await(m??ko()).claim("audio",i);w.current=q,v.current=[q.onTrack((L,F)=>{x.current=F,A.current?.(F),E.current&&h?.stream(n).attach(L).catch(H=>je("mic re-attach after one-capture re-acquire failed",H))}),q.onLost(L=>{w.current=null,v.current=[],x.current=null,A.current?.(null),l(!1),U.current?.(L)})],x.current=q.stream,A.current?.(q.stream);let B=q.track;if(!B)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return B},[m,i,h,n,l]),C=ve(async()=>{p(),l(!1),await h?.stream(n).detach().catch(()=>{})},[h,n,p,l]),_=ve(async()=>{if(!h)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");T.current?.unlock();let k;try{k=await f()}catch(B){p();let L=yo(B,h.status);throw U.current?.(L),L}h.connect?.();let N;for(let B=1;B<=u;B++)try{await h.whenLive(a!==void 0?{timeout:a}:void 0),await h.stream(n).attach(k),l(!0);return}catch(L){N=L,je(`start attempt ${B}/${u} failed`,L),B<u&&await new Promise(F=>setTimeout(F,c))}p(),l(!1);let q=N instanceof Error?N:new Error(String(N??"voice start failed"));throw U.current?.(q),q},[h,n,a,u,c,f,p,l]);ho(r,()=>({start:_,stop:C,unlock:()=>T.current?.unlock(),get active(){return E.current},get micStream(){return x.current},get audio(){return T.current}}),[_,C]);let W=Y(!1),R=ve(async()=>{if(!h||!E.current||W.current)return;let k=x.current?.getAudioTracks()[0]??null;if(k&&k.readyState==="live"){try{await h.stream(n).attach(k)}catch(N){je("foreground mic re-assert failed (will retry on next pass)",N)}return}W.current=!0;try{let N=await f();await h.stream(n).attach(N)}catch(N){let q=N instanceof Error?N:new Error(String(N));je("foreground mic re-acquire failed",q),U.current?.(q)}finally{W.current=!1}},[h,n,f]);return fr(()=>{let k=()=>{R()};return h&&typeof h.onRecovery=="function"?h.onRecovery(k):vo(k)},[h,R]),fr(()=>p,[p]),s?Po($e,{ref:T,session:h,stream:n,onTrack:y,onUnlockChange:b}):null}),bo=Ke;import{forwardRef as To,useEffect as wo,useImperativeHandle as Eo,useRef as Sr,useState as Ro}from"react";import{useEffect as Co,useState as xo}from"react";var Pt={level:0,speaking:!1};function Ct(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=xo(Pt);return Co(()=>{if(!e){i(Pt);return}let a=We();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let d=new Uint8Array(g.fftSize),y=setInterval(()=>{g.getByteTimeDomainData(d);let b=0;for(let P=0;P<d.length;P++){let h=(d[P]-128)/128;b+=h*h}let m=Math.sqrt(b/d.length);i(P=>{let h=m>n;return Math.abs(P.level-m)<.005&&P.speaking===h?P:{level:m,speaking:h}})},o);return()=>{clearInterval(y),c.disconnect(),i(Pt)}},[e,r,o,n]),s}import{Fragment as _o,jsx as Je,jsxs as No}from"react/jsx-runtime";var Ao={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Uo={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Mo=To(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:d,capture:S}=t,y=X(),b=o??y,m=Sr(null),[P,h]=Ro(null),T=Sr(d);T.current=d;let{level:x,speaking:w}=Ct(a?P:null);return Eo(r,()=>({start:()=>{let v=m.current;return v?v.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>m.current?.stop()??Promise.resolve(),get active(){return m.current?.active??!1},get micStream(){return m.current?.micStream??null}}),[]),wo(()=>{!i||!b||m.current?.start().catch(()=>{})},[i,b]),No(_o,{children:[Je(Ke,{ref:m,session:b,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...S!==void 0?{capture:S}:{},onActiveChange:c,onError:g,onMicStream:v=>{h(v),T.current?.(v)}}),a?Je("span",{className:u,style:Ao,"data-urun-mic":"","data-urun-mic-active":P?"true":"false","data-urun-mic-speaking":w?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(x*100)/100,children:Je("span",{style:Uo,children:Je("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(x*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{sessionFailureFromMediaError as Io,sharedCaptureController as Lo}from"@urun-sh/core";import{forwardRef as vr,useCallback as Z,useEffect as xt,useImperativeHandle as Oo,useRef as K,useState as xe}from"react";import{jsx as ne,jsxs as hr}from"react/jsx-runtime";var yr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Tt(...e){console.debug("[camera]",...e)}function Do(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Vo(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var kr=vr(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:d,visible:S=!1,className:y,videoClassName:b,onActiveChange:m,onError:P,onStream:h,onTrack:T,children:x,capture:w,flipControl:v="auto",flipControlClassName:E,onDevices:I}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":u??"environment",A=X(),l=o??A,p=K(null),f=K(null),C=K(null),_=K([]),W=K(null),R=K(!1),k=K(U),[N,q]=xe(U),[B,L]=xe(!1),[F,H]=xe(null),[V,O]=xe(!1),[j]=xe(Do),le=K(m);le.current=m;let Ae=K(P);Ae.current=P;let Qe=K(h);Qe.current=h;let Ue=K(T);Ue.current=T;let Lt=K(I);Lt.current=I;let Q=Z(M=>{R.current!==M&&(R.current=M,L(M),le.current?.(M))},[]);xt(()=>{if(!B){H(null);return}let M=!1,D=()=>{Vo().then(J=>{M||(H(J),J&&Lt.current?.(J))})};D();let $=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof $?.addEventListener=="function"?($.addEventListener("devicechange",D),()=>{M=!0,$.removeEventListener?.("devicechange",D)}):()=>{M=!0}},[B]);let Me=Z(M=>{let D=p.current;D&&(D.muted=!0,D.defaultMuted=!0,D.setAttribute("muted",""),D.setAttribute("playsinline",""),D.setAttribute("webkit-playsinline",""),D.srcObject=M,M&&D.play()?.catch?.($=>Tt("preview play() failed",$)))},[]),G=Z(()=>{W.current?.(),W.current=null;for(let M of _.current)M();_.current=[],C.current?.release(),C.current=null,f.current&&(f.current=null,Qe.current?.(null),Ue.current?.(null)),Me(null)},[Me]),et=Z((M,D)=>{W.current?.(),f.current=D,Me(D),Qe.current?.(D);let $=()=>{f.current===D&&(Tt("camera track ended (device removed or permission revoked)"),G(),Q(!1))};M.addEventListener("ended",$),W.current=()=>M.removeEventListener("ended",$)},[Me,G,Q]),de=Z(async M=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let D={...yr,...s,facingMode:M},$;try{let J=C.current;if(J)$=await J.update(D);else{let ye=await(w??Lo()).claim("video",D);if(C.current=ye,_.current=[ye.onTrack((ke,Vr)=>{et(ke,Vr),R.current&&l.stream(n).attachVideo(ke).then(()=>Ue.current?.(ke)).catch(qr=>Tt("camera re-publish after one-capture re-acquire failed",qr))}),ye.onLost(ke=>{C.current=null,_.current=[],G(),Q(!1),Ae.current?.(ke)})],!ye.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});$=ye.track}}catch(J){let pe=Io(J,l.status);throw Ae.current?.(pe),pe}k.current=M,q(M),et($,C.current?.stream??new MediaStream([$]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo($)}catch(J){G(),Q(!1);let pe=J instanceof Error?J:new Error(String(J));throw Ae.current?.(pe),pe}Ue.current?.($),Q(!0)},[l,n,s,d,w,et,G,Q]),Ot=Z(M=>de(M?.facingMode??k.current),[de]),_e=Z(async M=>{R.current&&k.current===M||await de(M)},[de]),tt=Z(()=>de(k.current==="environment"?"user":"environment"),[de]),Dt=Z(async()=>{G(),Q(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,G,Q]);Oo(r,()=>({start:Ot,stop:Dt,flip:tt,setFacingMode:_e,get active(){return R.current},get facingMode(){return k.current},get stream(){return f.current},get element(){return p.current}}),[Ot,Dt,tt,_e]);let Vt=K(_e);if(Vt.current=_e,xt(()=>{!c||!l||Vt.current(U).catch(()=>{})},[c,l,U]),xt(()=>G,[G]),!S)return null;let Lr=g==="auto"?N==="user":g,Or=B&&(v===!0||v==="auto"&&j&&(F?.length??0)>1),Dr=()=>{V||(O(!0),tt().catch(()=>{}).finally(()=>O(!1)))};return hr("div",{className:y,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":N,children:[ne("video",{ref:p,className:b,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Lr?{transform:"scaleX(-1)"}:{}}}),Or?ne("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Dr,disabled:V,className:E,style:E?{opacity:V?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:V?.6:1},children:hr("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:[ne("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ne("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ne("path",{d:"M14.5 10.5v1.6h-1.6"}),ne("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ne("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,x]})}),qo=vr(function({preview:t=!0,...r},o){return ne(kr,{ref:o,...r,visible:t,autoStart:!1})});import{useEffect as Fo,useState as Ho}from"react";function Wo(e,t){let[r,o]=Ho(null);return Fo(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as zo}from"react";import{useEffect as Ko,useMemo as Jo}from"react";import{createStore as Bo}from"zustand/vanilla";import{useStore as $o}from"zustand";var jo=()=>{};function wt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Bo(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):jo,u=(c=>$o(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function Te(e,t){let r=Jo(()=>wt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Ko(()=>r.bind(),[r]),r}function Xo(e,t,r){let n=Te(e,t)(r??(a=>a)),s=zo(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as Go,useState as Yo}from"react";var ae=200;function oe(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function we(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Et(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Rt(e,t,r={}){let o=r.cap??200,[n,s]=Yo([]);return Go(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>oe(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as ze,jsxs as Ee}from"react/jsx-runtime";function Zo({session:e,name:t,cap:r,className:o}){let n=Rt(e,t,{cap:r});return Ee("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[Ee("div",{className:"urun-stream-tail-meta",children:[ze("code",{children:t}),Ee("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),ze("div",{className:"urun-stream-tail-log",children:n.length===0?Ee("span",{className:"urun-stream-tail-empty",children:["Waiting for ",ze("code",{children:t})," messages\u2026"]}):n.map((s,i)=>Ee("div",{className:"urun-stream-tail-line",children:[ze("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",we(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as Qo,useState as br}from"react";import{jsx as ue,jsxs as Xe}from"react/jsx-runtime";function Ge({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=br(""),[i,a]=br(null),u=Qo(()=>{let c=Et(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return Xe("div",{className:"urun-doc-patch",children:[ue("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),Xe("div",{className:"urun-doc-patch-actions",children:[ue("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?ue("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function es({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Te(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return Xe("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[Xe("div",{className:"urun-doc-panel-meta",children:[ue("code",{children:t}),ue("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),ue("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?ue(Ge,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as ts,useState as rs}from"react";import{jsx as Re,jsxs as Cr}from"react/jsx-runtime";function Pr(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ns({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=rs([]);return ts(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>oe(u,{at:Date.now(),direction:"in",text:Pr(we(a))},r))}):void 0),[e,t,r]),Cr("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Re(Ge,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>oe(u,{at:Date.now(),direction:"out",text:Pr(a)},r))}}),Re("div",{className:"urun-control-sender-log",children:n.length===0?Re("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>Cr("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[Re("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",Re("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as os,useState as ss}from"react";import{jsx as Ye,jsxs as as}from"react/jsx-runtime";function is({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=ss([]),a=t.join(","),u=r.join(",");return os(()=>{if(i([]),!e)return;let c=(d,S)=>i(y=>oe(y,{at:Date.now(),kind:d,text:S},o)),g=[];g.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let S=e.stream(d);g.push(S.on("track",y=>c("track",`${d}: ${y?"track arrived":"track ended"}`)))}for(let d of r){let S=e.doc(d);g.push(S.on("change",()=>c("doc",`${d} changed`)))}return()=>g.forEach(d=>d())},[e,a,u,o]),Ye("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?Ye("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,g)=>as("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[Ye("span",{className:"urun-event-spine-kind",children:c.kind})," ",Ye("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}import{describeSessionPhase as Ps,isWakingPhase as Cs}from"@urun-sh/core";import{useEffect as us,useState as cs}from"react";function z(e){let[t,r]=cs(e?.phase??null);return us(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as fs}from"@urun-sh/core";import{useEffect as ls,useRef as ds,useState as ps}from"react";import{isWakingPhase as ms}from"@urun-sh/core";function At(e){let t=z(e),r=ms(t?.name),o=ds(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=ps(s);return ls(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as gs,jsx as xr,jsxs as Tr}from"react/jsx-runtime";function Ut({session:e,render:t,className:r}){let o=At(e);return!o.waking||!o.phase?null:xr("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Tr(gs,{children:[xr("span",{className:"urun-session-waking-label",children:fs(o.phase)})," ",Tr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as vs,useState as ys}from"react";import{useEffect as wr,useRef as Ss,useState as Er}from"react";var hs={event:null,elapsedMs:0};function Mt(e,t){let[r,o]=Er(null),n=Ss(0);wr(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=Er(0);return wr(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:hs}import{jsx as Rr,jsxs as Ar}from"react/jsx-runtime";var ks={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 bs(e){let[t,r]=ys(!1);return vs(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function _t({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Mt(e,t),i=bs(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return Rr("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):Ar("div",{className:"urun-activation-overlay-card",children:[Rr("span",{className:"urun-activation-overlay-copy",children:a.hint??ks[u]})," ",Ar("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as ce,jsxs as Nt}from"react/jsx-runtime";var xs={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Ts({session:e,className:t}){let r=z(e),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 Nt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[ce("span",{className:"urun-session-status-dot","data-phase":o}),ce("span",{className:"urun-session-status-label",children:xs[o]}),n?ce("span",{className:"urun-session-status-detail",children:n}):null]})}function ws({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=z(e);if(s?.name==="live")return Nt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,ce(_t,{session:e})]});let i=r?r(s):ce("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&Cs(s.name)?ce(Ut,{session:e}):s&&s.name!=="idle"?Ps(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Nt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?ce("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Es,useState as Rs}from"react";import{jsx as Ms}from"react/jsx-runtime";function Ur(e){return z(e)?.endsAt??null}function As(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Us({session:e,urgentMs:t=6e4,className:r}){let n=Ur(e)?.getTime()??null,[s,i]=Rs(()=>n===null?null:Math.max(0,n-Date.now()));if(Es(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=As(s);return Ms("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{jsx as Mr,jsxs as Is}from"react/jsx-runtime";var _s=new Set(["expired","ended","error"]);function Ns({session:e,onNewSession:t,children:r,className:o}){let n=z(e);if(!n||!_s.has(n.name))return null;let s=r?r(n):Mr("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 Is("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?Mr("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as _r,useMemo as Ls,useState as Nr}from"react";import{jsx as Ze,jsxs as Vs}from"react/jsx-runtime";function It(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Ir(e){let t=Ls(()=>e?e.doc("control"):null,[e]),[r,o]=Nr(()=>t?It(t.get("idle")):null);return _r(()=>{if(!t){o(null);return}return o(It(t.get("idle"))),t.on("change",()=>o(It(t.get("idle"))))},[t]),r}function Os(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Ds({session:e,onStillHere:t,className:r}){let o=Ir(e),n=o?.deadlineEpochS??null,[s,i]=Nr(null);if(_r(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return Ze("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:Vs("div",{className:"urun-idle-warning-card",children:[Ze("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),Ze("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Os(s)} due to inactivity.`:"This session will end soon due to inactivity."}),Ze("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as qs,useEffect as Fs,useState as Hs}from"react";import{prewake as Ws}from"@urun-sh/core";function Bs(e){let t=qs(me),[r,o]=Hs(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,d=t?.authProvider;return Fs(()=>{if(!a||!u||!n||!s)return;let S=!1,y=()=>{Ws({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:d}).then(m=>{S||o(m)}).catch(()=>{})};y();let b=setInterval(y,Math.max(1,i)*1e3);return()=>{S=!0,clearInterval(b)}},[n,s,i,a,u,c,g,d]),r}import{describeSessionPhase as qc,isWakingPhase as Fc}from"@urun-sh/core";export{$e as Audio,kr as Camera,An as ComponentRenderer,yr as DEFAULT_CAMERA_CONSTRAINTS,ae as DEFAULT_LOG_CAP,gr as DEFAULT_VOICE_CONSTRAINTS,Ge as DocPatchForm,io as Image,Wn as ImageFrame,Hn as ImageFrameSchema,jn as MetricsPanel,$n as MetricsPanelSchema,Mo as Mic,Xr as OPERATOR_CHORD_LABEL,zr as OPERATOR_TOKEN_STORAGE_KEY,_n as ProgressCard,Mn as ProgressCardSchema,zn as Session,Ln as StatusBadge,Nn as StatusBadgeSchema,qn as TextStream,Vn as TextStreamSchema,_t as UrunActivationOverlay,fo as UrunAudio,Fr as UrunAuthProvider,qo as UrunCamera,ns as UrunControlSender,es as UrunDocPanel,be as UrunErrorBoundary,is as UrunEventSpine,Ds as UrunIdleWarning,Hr as UrunJwtProvider,tn as UrunProvider,Us as UrunSessionClock,Ns as UrunSessionEnded,ws as UrunSessionGate,Ts as UrunSessionStatus,Ut as UrunSessionWaking,Zo as UrunStreamTail,bo as UrunVoice,yt as Video,Ke as Voice,Ne as authMode,wt as createDocStore,qc as describeSessionPhase,we as formatPayload,We as getUrunAudioContext,Fc as isWakingPhase,Et as parseJsonObject,oe as pushCapped,Bt as readOperatorToken,Rn as registerComponent,Be as resumeUrunAudioContext,ee as urunPublicEnv,Mt as useActivation,ln as useApp,Pn as useChat,vn as useCompletion,Te as useDocStore,lr as useImageFrame,En as useInputPresence,dr as useMetricsPanel,nt as useOperatorOverride,nr as useProgressCard,fn as useRequest,Xn as useSession,Xo as useSessionDoc,Ur as useSessionEndsAt,Ir as useSessionIdle,z as useSessionPhase,Wo as useSessionTrack,At as useSessionWake,sr as useStatusBadge,Rt as useStreamMessages,ur as useTextStream,Ct as useUrunAudioLevel,rt as useUrunAuth,Bs as useUrunPrewake,jr as usesWorkOSAuth};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/react",
3
- "version": "0.2.28",
3
+ "version": "0.2.29",
4
4
  "description": "React bindings for the urun TypeScript SDK",
5
5
  "repository": {
6
6
  "type": "git",
@@ -53,7 +53,7 @@
53
53
  "dev": "tsup --watch"
54
54
  },
55
55
  "peerDependencies": {
56
- "@urun-sh/core": "^0.2.28",
56
+ "@urun-sh/core": "^0.2.29",
57
57
  "@workos-inc/authkit-nextjs": "^3.0.0",
58
58
  "@workos-inc/authkit-react": "^0.15.0 || ^0.16.0",
59
59
  "next": "^15.0.0 || ^16.0.0",
@@ -75,6 +75,8 @@
75
75
  "@workos-inc/authkit-nextjs": "^3.0.0",
76
76
  "@workos-inc/authkit-react": "^0.16.1",
77
77
  "esbuild": "0.28.1",
78
+ "eslint": "^9.39.5",
79
+ "eslint-config-next": "16.2.7",
78
80
  "happy-dom": "^20.9.0",
79
81
  "next": "16.2.6",
80
82
  "pngjs": "^7.0.0",