@urun-sh/openai 0.6.50 → 0.6.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-Q3AIBMET.js → chunk-526ZJAOW.js} +1 -1
- package/dist/{chunk-OZVX4WPP.js → chunk-5L7LOBL7.js} +1 -1
- package/dist/{chunk-XKKQ2NEZ.js → chunk-7OUSAG7O.js} +1 -1
- package/dist/{chunk-V6WQRPUO.js → chunk-AW5X2PRN.js} +2 -2
- package/dist/chunk-AWCC5WRB.js +1 -0
- package/dist/{chunk-6WTMEJZS.js → chunk-H4KFMIEV.js} +1 -1
- package/dist/{chunk-PL4MNBET.js → chunk-USE56WRQ.js} +1 -1
- package/dist/gemini-live.cjs +1 -1
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +2 -2
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +1 -1
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +3 -3
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +1 -1
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-PXV7QBSD.js +0 -1
|
@@ -175,7 +175,7 @@ self.onrtctransform = (event) => {
|
|
|
175
175
|
`)}var aoe=class Rd{constructor(e,r){this.sink=e,this.seqState=r??{seq:0}}sink;stopped=!1;deadCb=null;seqState;static FLOW_WINDOW_MS=5e3;static FLOW_MIN_SENT_PER_WINDOW=25;sentCount=0;flowTimer=null;flowLastSent=0;flowLastDelivered=0;zeroSendWindows=0;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}sentDatagrams(){return this.sentCount}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let r=null;if(!(e!==null&&(r=coe(e)?this.bridgedTrack(e):e,!r))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(r)}catch(s){this.die(`replaceTrack: ${s instanceof Error?s.message:String(s)}`);return}this.currentTrack=r,r&&this.wireTrackLiveness(r);return}r!==null&&(this.engage(r),this.startFlowWatch())}}startFlowWatch(){this.flowTimer||this.stopped||(this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),this.flowTimer=setInterval(()=>{if(this.stopped)return;let e=this.sentCount-this.flowLastSent,r=this.sink.delivered()-this.flowLastDelivered;if(this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),e>0&&S.log(`[urun] WT mic uplink flow: wrote=${(e/(Rd.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s accepted=${(r/(Rd.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s`),this.sentCount===0&&this.currentTrack&&this.currentTrack.readyState==="live"&&e===0){if(this.zeroSendWindows++,this.zeroSendWindows>=2){this.die(`loopback wrote no datagrams for ${2*Rd.FLOW_WINDOW_MS/1e3}s with a live source (ICE stuck in checking, DTLS hung, or the encode transform never wired) \u2014 the recovery ladder must re-engage the lane`);return}}else this.zeroSendWindows=0;e<Rd.FLOW_MIN_SENT_PER_WINDOW||r*2>=e||S.error(`[urun] WT mic uplink flow STARVED: wrote ${e} datagrams in ${Rd.FLOW_WINDOW_MS/1e3}s but QUIC accepted only ${r}`)},Rd.FLOW_WINDOW_MS))}stop(){if(!this.stopped){this.stopped=!0,this.flowTimer!==null&&(clearInterval(this.flowTimer),this.flowTimer=null),this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let r=globalThis;if(typeof r.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof r.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let s;try{s=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let n=this.sendPc.addTrack(e);this.sender=n,this.currentTrack=e,this.wireTrackLiveness(e);let i=r.RTCRtpScriptTransform;if(n.transform=new i(s,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let r=e.RTCPeerConnection;this.sendPc=new r({iceServers:[]}),this.recvPc=new r({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=s=>{if(!s.candidate)return;let n=this.candQueue;n!==null&&(n.toRecv.push(s.candidate),this.flushCandidates())},this.recvPc.onicecandidate=s=>{if(!s.candidate)return;let n=this.candQueue;n!==null&&(n.toSend.push(s.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(s=>this.die(`loopback renegotiate: ${s instanceof Error?s.message:String(s)}`))},this.recvPc.ontrack=s=>{let n=s.transceiver?.mid??null;n!==null&&n===this.renderMidOf()&&this.renderRemoteCb?.(s.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(r){this.die(`render replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(r=>this.die(`loopback negotiate: ${r instanceof Error?r.message:String(r)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(r=>r.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,r=this.recvPc;if(!(!e||!r||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let s=await e.createOffer();s.sdp=Uq(s.sdp??""),await e.setLocalDescription(s),await r.setRemoteDescription(e.localDescription??{type:"offer",sdp:s.sdp});let n=await r.createAnswer();n.sdp=Uq(n.sdp??""),await r.setLocalDescription(n),await e.setRemoteDescription(r.localDescription??{type:"answer",sdp:n.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let r=e;try{let s=r.context.createMediaStreamDestination();r.connect(s);let n=s.stream.getAudioTracks()[0]??null;return n?(this.nodeBridge={node:r,dest:s},n):(this.die("AudioNode bridge produced no audio track"),null)}catch(s){return this.die(`AudioNode bridge: ${s instanceof Error?s.message:String(s)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([ooe],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=r=>{let s=r.data;s?.type==="enc"&&s.payload instanceof ArrayBuffer?this.onEncodedFrame(s.rtpTimestamp??0,new Uint8Array(s.payload)):s?.type==="err"&&this.die(`transform: ${s.detail??"unknown"}`)},e.onerror=r=>this.die(`transform worker: ${r.message||"error"}`),this.worker=e,e}onEncodedFrame(e,r){if(this.stopped)return;let s=dH(this.seqState.seq,e,r,this.sink.maxDatagramSize()||bR);if(s===null){S.warn(`[urun] WT mic uplink: frame of ${r.byteLength}B exceeds the fragment budget \u2014 dropped`),this.seqState.seq=this.seqState.seq+1>>>0;return}for(let n of s)this.sink.send(n),this.sentCount++;this.seqState.seq=this.seqState.seq+1>>>0}die(e){this.stopped||(S.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function coe(t){let e=t;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var loe=9e4,doe="avc1.42E01F",uoe=60,hoe=3,foe=1e4;function poe(t){return Math.round(t*(loe/1e6))%2**32>>>0}var moe=class{constructor(t){this.sink=t}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(t){this.deadCb=t}requestKeyframe(){this.keyframeWanted=!0}setSource(t){if(this.stopped||(this.teardownCapture(),t===null))return;let e=globalThis.MediaStreamTrackProcessor;if(typeof e!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let r=++this.generation,s=new e({track:t}).readable.getReader(),n=!1;this.cancelCapture=()=>{n=!0,s.cancel().catch(()=>{})},(async()=>{for(;!n&&!this.stopped&&r===this.generation;){let{value:i,done:o}=await s.read();if(o)break;if(i){if(n||this.stopped||r!==this.generation){i.close();break}this.encodeFrame(i)}}})().catch(i=>{!n&&!this.stopped&&r===this.generation&&this.die(`capture: ${i instanceof Error?i.message:String(i)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(t){let e={width:t.codedWidth,height:t.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==e.width||this.encoderDims.height!==e.height){let s=globalThis.VideoEncoder;if(typeof s!="function"){t.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)})),this.encoderDims=e,this.encoder.configure({codec:doe,avc:{format:"annexb"},width:e.width,height:e.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(n){t.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let r=this.keyframeWanted||this.framesSinceKeyframe>=uoe;this.keyframeWanted=!1,this.framesSinceKeyframe=r?0:this.framesSinceKeyframe+1;try{this.encoder.encode(t,{keyFrame:r})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}t.close()}sendFrame(t){if(this.stopped)return;let e=new Uint8Array(t.byteLength);t.copyTo(e);let r=dH(this.frameSeq,poe(t.timestamp),e,this.sink.maxDatagramSize()||bR,{lane:Kie,keyframe:t.type==="key"});if(r===null){S.warn(`[urun] WT video uplink: AU of ${e.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(t){if(this.stopped)return;let e=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>e-r<foe),this.encoderErrorsAt.push(e),this.encoderErrorsAt.length>=hoe){this.die(`video encoder: ${t.message}`);return}S.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",t.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(t){this.stopped||(S.warn(`[urun] WT video uplink lane dead (${t}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(t))}};function goe(t){return t.byteLength>=2&&t[0]===1&&t[1]===3}var yoe=class{constructor(t){this.transport=t}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(t){this.deadCb=t}send(t,e){let r=new TextEncoder().encode(t);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let n=this.streams.get(t);if(!n){let o=await this.transport.openUniStream(),a=new Uint8Array(2+r.byteLength);a[0]=1,a[1]=r.byteLength,a.set(r,2),await o.write(a),n={writer:o},this.streams.set(t,n)}let i=new Uint8Array(4+e.byteLength);new DataView(i.buffer).setUint32(0,e.byteLength,!0),i.set(e,4),await n.writer.write(i),goe(e)&&(this.streams.delete(t),await n.writer.close().catch(()=>{}))}catch(n){throw this.die(n instanceof Error?n.message:String(n)),n}});return this.chain=s.catch(()=>{}),s}stop(t="stopped"){if(this.dead===null){this.dead=t;for(let e of this.streams.values())e.writer.close().catch(()=>{});this.streams.clear()}}die(t){this.dead===null&&(S.warn(`[urun] WT data uplink lane dead (${t})`),this.stop(t),this.deadCb?.(t))}},Mq=250,boe=25,xoe=2e3,woe=15e3,voe=1e3,_oe=45e3,Soe=5e3,Eoe={llm:!0},Coe=500,jq=10,koe=2,Toe=2,BI=2,xR=class Pd{constructor(e,r,s,n,i,o,a){this.offer=e,this.sessionId=r,this.canvas=s,this.audioLane=n,this.audioUplink=i,this.videoUplink=o,this.dataUplink=a,this.firstMedia=new Promise((c,l)=>{this.firstFrameResolve=c,this.firstFrameReject=l}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new pR({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let r=this.offer.codec,s=r!==void 0&&r!=="";this.hasVideoLane=s,s&&Oq(r,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(u=>({algorithm:"sha-256",value:Uint8Array.from(atob(u),d=>d.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let n=await this.wt.createBidirectionalStream();this.writer=n.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=n.readable.getReader(),o=new hR,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let l=c;if(this.lastInboundControlAt=performance.now(),typeof l.pingIntervalMs=="number"&&l.pingIntervalMs>0?this.advertisedPingIntervalMs=l.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,S.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),s&&(Oq(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let u={setSource:h=>{this.renderSource=h,this.audioUplinkLane?.setRenderSource?.(h)},onRemote:h=>{this.renderRemoteCb=h}},d=new ioe(this.offer.audio,{...this.audioLane,renderHop:u});try{d.start(),this.audioPlayout=d}catch(h){S.warn(`[urun] WT audio lane failed to start (${h instanceof Error?h.message:String(h)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),d.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let u=this.wt.createUnidirectionalStream?.bind(this.wt);if(!u)throw new Error("WebTransport uni streams are not creatable in this environment");let d=new yoe({openUniStream:async()=>(await u()).getWriter()});d.onDead(h=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(h,d)}),this.dataUplinkSender=d,this.dataUplink.onUplink(d)}catch(u){let d=u instanceof Error?u.message:String(u);S.warn(`[urun] WT data uplink failed to engage (${d}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(d)}this.controlLoop(i,o,a).catch(u=>this.die(`control loop: ${u}`)),this.datagramLoop().catch(u=>this.die(`datagram loop: ${u}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Coe)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(u=>{this.closedReason=`connection error: ${u}`,this.die(`connection error: ${u}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${Mq}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??woe},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),voe))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let r=typeof e.ds=="number"?e.ds:null,s=typeof e.ur=="number"?e.ur:null;if(r===null&&s===null)return;this.gatewayExposesCounters=!0;let n=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:r,ur:s,recvDownlink:n,sentUplink:i},!o)return;let a=r!==null&&o.ds!==null?r-o.ds:null,c=s!==null&&o.ur!==null?s-o.ur:null,l=n-o.recvDownlink,u=i-o.sentUplink,d="none";if(a!==null&&a>=jq&&l<=0?d="downlink":c!==null&&u>=jq&&c<=0&&(d="uplink"),d==="none"){this.severedStreak="none",this.observePlayoutProgress(l,r);return}if(this.severedStreak!==d){this.severedStreak=d;return}this.severedStreak="none";let h=d==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${u} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+h+` (gateway flow counters ds=${r} ur=${s}, client received=${n} accepted=${i}, confirmed on ${koe} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,r){let s=this.audioPlayout;if(!s){this.playoutScheduledSeen=null;return}let n=s.playoutProgress(),i=n.surfaced;if(this.playoutScheduledSeen!==null&&n.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=n.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=n.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Toe)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,S.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${r}, client received=${this.audioDgramsReceived}, scheduled=${n.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{s.rebuildSurface()}catch(o){S.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=BI}return}this.playoutStallStreak<BI||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${r}, client received=${this.audioDgramsReceived}, scheduled=${n.scheduled} on ${BI} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let r=this.pathLiveness();if(!r.alive)return;let s=performance.now(),n=this.audioLaneLastArrivalAt===null?null:s-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:s-this.lastInboundControlAt,o=n===null&&i===null?!0:(n===null||n>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(i/1e3)}s while the path reports alive (${r.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),l=this.lastInboundDataAt===null?null:s-this.lastInboundDataAt,u=n!==null?n:this.firstInboundDataAt===null?null:s-this.firstInboundDataAt,d=u!==null&&u>=e.stallMs;if(c&&d&&l!==null&&l<=Soe&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((u??0)/1e3)}s while the data lane delivered a frame ${Math.round((l??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${r.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&i!==null&&i>=_oe&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(i/1e3)}s while the path reports alive (${r.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let r=this.dataUplinkSender;r&&(this.dataUplinkSender=null,r.stop(e),this.dataUplink?.onUplinkLost(e,r))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let r=this.audioUplinkLane;r?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,r??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let r=this.videoUplinkLane;r?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,r??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let r={onData:(s,n)=>{if(Eoe[s]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(s,n)},onLaneError:s=>e.onLaneError(s)};this.dataLaneSink=r,yR(this.wt.incomingUnidirectionalStreams,r).catch(s=>{this.die(`data lane: ${s instanceof Error?s.message:String(s)}`)})}initDecoder(e,r,s){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:r,height:s};let o=new n({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...r>0&&s>0?{codedWidth:r,codedHeight:s}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;S.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,S.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(r.codec,r.width,r.height),this.decoderErrorLogged=!1}catch(s){this.decoderErrorLogged||(this.decoderErrorLogged=!0,S.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${s instanceof Error?s.message:String(s)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,r){this.stopped||this.deadFired||this.datagramWriter().write(e).then(r,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let r=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,S.error(`[urun] WT uplink datagram send FAILED (${r}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let s=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(n=>s-n<xoe),this.uplinkSendErrorsAt.push(s),!(this.uplinkSendErrorsAt.length<boe)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${r}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSeqState={seq:0};uplinkSink(e){this.datagramWriter();let r=0;return{send:s=>this.uplinkSend(s,()=>{r++}),delivered:()=>r,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??bR}}engageAudioUplink(){let e=new aoe(this.uplinkSink("audio"),this.uplinkSeqState);e.onDead(r=>this.onUplinkLaneDead("audio",r,e)),e.onRenderTrack?.(r=>this.renderRemoteCb?.(r)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new moe(this.uplinkSink("video"));e.onDead(r=>this.onUplinkLaneDead("video",r,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let r=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(s){let n=s instanceof Error?s.message:String(s);S.warn(`[urun] WT ${r} uplink failed to engage (${n}) \u2014 keeping the WT session; the ${r} stays on the WebRTC produce path`),this.seamUplinkLost(e,n)}}freshLaneBuilt(e){let r={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),r}onUplinkLaneDead(e,r,s){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let n=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=i?.builtAt!=null&&Date.now()-i.builtAt>=Pd.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(o>Pd.UPLINK_LANE_RETRY_MAX){S.error(`[urun] WT ${n} uplink lane dead (${r}) \u2014 ${Pd.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${Pd.UPLINK_LANE_RETRY_MAX} recovery attempts: ${r}`,s);return}S.warn(`[urun] WT ${n} uplink lane dead (${r}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${Pd.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let a={count:o,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=a:this.videoUplinkRetry=a,a.timer=setTimeout(()=>{a.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},Pd.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,r,s){e==="audio"?this.audioUplink.onUplinkLost(r,s):this.videoUplink.onUplinkLost(r,s)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:r,done:s}=await e.read();if(s)break;if(!r)continue;if(r.byteLength>=ei&&r[11]===cH){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(r);continue}if(!this.hasVideoLane)continue;let n=performance.now();if(this.lastArrivalTs>0){let i=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(r)}}decodeFrame(e,r,s){let n=globalThis.EncodedVideoChunk;if(typeof n=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new n({type:r?"key":"delta",timestamp:e*(1e6/24),data:s})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(uR(e)),this.controlWritesAccepted++}catch(r){let s=r instanceof Error?r.message:String(r);throw this.controlWriteError||(this.controlWriteError=s),this.die(`control stream write refused: ${s}`),r}}async sendControlRaw(e){try{let r=new Uint8Array(4+e.byteLength);new DataView(r.buffer).setUint32(0,e.byteLength,!0),r.set(e,4),await this.writer.write(r),this.controlWritesAccepted++}catch(r){let s=r instanceof Error?r.message:String(r);throw this.controlWriteError||(this.controlWriteError=s),this.die(`control stream write refused: ${s}`),r}}async readControl(e,r,s=[]){for(;;){let n=s.shift();if(n)return n;let{value:i,done:o}=await e.read();if(o)return null;i&&s.push(...r.push(i))}}async controlLoop(e,r,s){for(;!this.stopped;){let n=await this.readControl(e,r,s);if(!n){this.die("control stream ended");break}let i=n;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Vie(n.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let r=performance.now(),s=(r-e)/1e3;e=r;let n=this.reassembler.drainWindow(),i=n.delivered+n.abandoned;this.lastStats={recvBps:s>0?n.bytes*8/s:0,lossPct:i>0?100*n.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Mq)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}},$q=2500,Fq=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Aoe=1e4,wR=class Ec{constructor(e,r,s){this.signaling=e,this.sessionId=r,this.opts=s}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;wtLegEstablished=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let r=this.session;if(!(!r||r.kind!=="webtransport")){if(r.pathLiveness?.()?.alive===!1&&this.wtLegEstablished){this.opts.onWtLegDeath?.(e),this.wtOnlyLeg=!1,this.wtLegEstablished=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(e)),this.session=null,this.redialWtAfterDeath(e,!0);return}r.fail?.(e)}}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let r=typeof e.WebTransport=="function",s=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,i={webtransport:r&&s&&n,webcodecs:s,codecs:Fq,wtData:r&&s&&n&&this.opts.dataLane!==void 0,wtAudio:r&&s&&n&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:r&&n&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:r&&s&&n&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:r&&s&&n&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&S.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let l=null;try{return l=this.createWebTransportSession(),await OI(l.start(),this.opts.quicDeadlineMs??$q,"quic connect deadline"),this.wtDialedHost=LI(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(l,i.wtData===!0),this.session=l,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.wtLegEstablished=!0,this.opts.onTransportChange?.("webtransport"),this.session}catch(u){if(S.warn(`[urun] WT dial failed (${xv(u)}) \u2014 dialed ${qq(this.offer.webtransport?.url)}`),l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let d=String(u instanceof Error?u.message:u);throw S.error(`[urun] WT-REQUIRED leg failed to establish (${d}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(d),u}S.warn("[urun] webtransport failed, falling back to webrtc:",u),this.proceedWebRtcDial(`wt failed: ${String(u instanceof Error?u.message:u)}`),this.notifyEstablished("webrtc",String(u instanceof Error?u.message:u))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw S.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,this.wtLegEstablished=!1,await e?.stop()}noteOfferedWtHost(){let e=LI(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,S.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(Ioe(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,s=this.opts.dataLane!==void 0,n=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",i=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",o=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Fq,wtData:s,wtAudio:n,wtAudioUp:i,wtVideoUp:o,wtDataUp:a}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let c=this.createWebTransportSession();try{await OI(c.start(),this.opts.quicDeadlineMs??$q,"quic connect deadline")}catch(l){throw S.warn(`[urun] WT dial failed (${xv(l)}) \u2014 dialed ${qq(this.offer.webtransport?.url)}`),c.stop().catch(()=>{}),l}if(this.wtDialedHost=LI(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return c.stop().catch(()=>{}),null;try{this.engageQuicDataLane(c,s)}catch(l){throw c.stop().catch(()=>{}),l}if(this.disconnected)return c.stop().catch(()=>{}),null;this.session=c;{let l=this.offer.webtransport;l&&(this.opts.audioLane===void 0||l.audio!==void 0)&&(this.opts.audioUplink===void 0||l.audioUp===!0)&&(this.opts.videoUplink===void 0||l.videoUp===!0)&&(this.opts.dataLane===void 0||l.data===!0)&&(this.opts.dataUplink===void 0||l.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.wtLegEstablished=!0,this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),c}engageQuicDataLane(e,r){if(!r||this.offer?.webtransport?.data!==!0)return;let s=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,i)=>s.onData(n,i),onLaneError:n=>s.onLaneError(n)}),s.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new xR(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(r=>{S.error("[urun] webrtc path died:",r)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(r=>{if(this.wtLegEstablished=!1,this.opts.onWtLegDeath?.(r),this.opts.allowWebRtcFallback===!1){S.error(`[urun] WT-REQUIRED leg died mid-session (${r}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(r)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(r,!0);return}let s=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(r)),e.stop().catch(()=>{}),s){this.session=null,this.wtOnlyLeg=!1,S.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",r),this.redialWtAfterDeath(r,!0);return}S.warn("[urun] quic died mid-session, failing over to webrtc:",r),this.lateWebRtcFailover(e,r,s)})}redialWtAfterDeath(e,r=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=Ec.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){S.error(`[urun] WT re-dial failed ${Ec.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}S.error(`[urun] WT re-dial failed ${Ec.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let s=this.wtRedialFailures+1,n=uH(Ec.WT_REDIAL_BASE_MS,s,Ec.WT_REDIAL_CAP_MS,s===1&&r?0:void 0);S.warn(`[urun] WT re-dial attempt ${s} scheduled in ${Math.round(n)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},n)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){S.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${Ec.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(r){let s=xv(r);S.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${Ec.WT_REDIAL_MAX} failed (${s}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${s}`)}}}lateWebRtcFailover(e,r,s){this.disconnected||(async()=>{let n=this.createWebRtc();try{let i=await OI(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Aoe,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${r}`),this.opts.onTransportChange?.("webrtc",r)}catch(i){if(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=s?`media transport lost \u2014 the WebTransport connection dropped (${r}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${r}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;S.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,r){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:r})}};function xv(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t&&typeof t=="object"){try{let e=JSON.stringify(t);if(e!==void 0&&e!=="{}")return e}catch{}return t.constructor?.name??Object.prototype.toString.call(t).slice(8,-1)}return String(t)}function LI(t){if(t)try{return new URL(t).host}catch{return}}function qq(t){if(!t)return"(no offer url)";try{let e=new URL(t);return e.searchParams.delete("token"),e.toString()}catch{return t.replace(/[?&]token=[^&\s]*/g,"")}}function Ioe(t){if(!t)return!1;let e=t.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function uH(t,e,r,s){if(s!==void 0)return s;let n=Math.min(t*2**Math.max(0,e-2),r);return Math.round(n*(.75+Math.random()*.5))}function OI(t,e,r){return new Promise((s,n)=>{let i=setTimeout(()=>n(new Error(r)),e);t.then(o=>{clearTimeout(i),s(o)},o=>{clearTimeout(i),n(o)})})}var Roe=1e4,vR=class{constructor(t,e=Roe){this.carrier=t,this.requestTimeoutMs=e}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(t,e){let r=dv();return new Promise((s,n)=>{let i=setTimeout(()=>{o(),n(new Error(`[urun] signaling request timed out: ${t}`))},this.requestTimeoutMs),o=this.carrier.onSignal(a=>{if(a.type!==`${t}.response`||a.requestId!==r)return;if(clearTimeout(i),o(),a.error){n(new Error(`[urun] ${t} failed: ${String(a.error)}`));return}let{type:c,requestId:l,...u}=a;s(u)});this.carrier.sendSignal({type:t,requestId:r,...e})||(clearTimeout(i),o(),n(new Error(`[urun] signaling request not sent: ${t} \u2014 the signaling socket is not open`)))})}notify(t,e){this.carrier.sendSignal({type:t,...e})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${t} \u2014 the signaling socket is not open`,detail:{method:t}})}on(t,e){return this.carrier.onSignal(r=>{r.type===t&&e(r)})}},Poe="video",_R=class{constructor(t,e=Poe){this.transport=t,this.streamName=e,this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let e=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(e(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(e)})}async stop(){for(let t of this.unsubscribers.splice(0))t()}onDead(t){this.deadCb=t}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(t){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(t)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(t))}};function Doe(t){let e=t;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Boe="video",Loe=45e3;async function Ooe(t,e,r){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let n=e,i=r.runtimeWaitCapMs??Loe;return new Promise(o=>{let a=!1,c,l=null,u=null,d=!1,h=w=>{a||(a=!0,m(),u!==null&&(clearTimeout(u),u=null),c?.(),o(w))};u=setTimeout(()=>{if(d||a||r.isDisposed())return;d=!0;let w=n.current();t.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${r.sessionId} (server status: ${w?.reason??w?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let f=()=>{l===null&&!a&&(l=setTimeout(()=>h("unconfirmed"),i))},m=()=>{l!==null&&(clearTimeout(l),l=null)};c=e.subscribe(w=>{let p=w?.name;if(p==="live")return h("live");if(p==="error")return h("gone");m(),vc(p)||f()}),vc(s)||f()})}function Noe(t,e,r){let s=globalThis,n=s.document;if(!(typeof n?.createElement=="function"&&typeof s.WebTransport=="function"&&typeof s.VideoDecoder=="function")||r.allowWebTransport===!1)return null;let i=t.holdWebRtcDial?.(),o=n.createElement("canvas"),a=!1,c=null,l=!1,u=()=>{if(c){for(let A of c.getVideoTracks())try{A.stop()}catch{}c=null}l&&(l=!1,r.onOverrideTrack(null))},d=new wR(new vR(t),e,{canvas:o,createWebRtcSession:r.createWebRtcSession??(()=>new _R(t,r.streamName??Boe)),createWebTransportSession:r.createWebTransportSession,dataLane:{onData:(A,C)=>t.dispatchQuicStreamData(A,C),onQuicLane:()=>t.markStreamDataLaneQuic(),onQuicLaneLost:A=>t.quicStreamDataLaneLost(A),onLaneError:A=>t.raiseQuicStreamDataError(A)},audioLane:r.onOverrideAudioTrack?{jitterBufferTargetMs:r.audioPlayout?.jitterBufferTargetMs,ctx:r.audioPlayout?.audioContext,onTrack:A=>{a||(A&&t.noteQuicMediaFlowing?.(),r.onOverrideAudioTrack(A))}}:void 0,audioUplink:r.audioUplink,videoUplink:r.videoUplink,dataUplink:r.dataUplink,webRtcDial:i,allowWebRtcFallback:r.allowWebRtcFallback,onWtRequiredOutage:()=>E(),onMediaTransportLost:A=>{a||(u(),r.onOverrideAudioTrack?.(null),r.onMediaTransportLost?.(A),E())},onWtLegDeath:()=>{t.noteMediaLegDeath?.()},onTransportChange:(A,C)=>{a||(A==="webrtc"&&(u(),E()),r.onTransportChange?.(A,C))}}),h=t.onWtOnlyLegDeath?.(A=>d.failCurrentWtLeg(A)),f=null,m=()=>{f!==null&&(clearInterval(f),f=null)},w=r.wtRetryBaseMs??2e3,p=r.wtRetryCapMs??3e4,b=null,v=0,E=()=>{if(a||b!==null||d.activeTransport==="webtransport")return;let A=uH(w,v+2,p);b=setTimeout(()=>{b=null,v+=1,d.retryWebTransport().then(C=>{if(a){C&&d.disconnect().catch(()=>{});return}if(C)return S.debug(`[urun] webtransport upgraded in background (retry ${v})`),v=0,W(C);E()}).catch(C=>{a||(S.debug(`[urun] webtransport background retry ${v} failed: `+xv(C)),E())})},A)},O=()=>{b!==null&&(clearTimeout(b),b=null)},W=async A=>{if(a||A.kind!=="webtransport")return;let C=r.pathHealthProbeMs??1e4;m();let R=!1;f=setInterval(()=>{if(a||d.activeTransport!=="webtransport")return;let X=Doe(A);if(!X){S.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),m();return}let J=X.pathLiveness();if(!J.alive){let V=d.isWtOnlyLeg;S.error(`[urun] webtransport path is DEAD: ${J.evidence}`+(V?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),m(),X.fail(`path health: ${J.evidence}`);return}if(!R){if(R=!0,d.isWtOnlyLeg){S.warn(`[urun] webtransport established, no application media yet after ${C}ms \u2014 the QUIC PATH IS HEALTHY (${J.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}S.warn(`[urun] webtransport established but no QUIC media after ${C}ms \u2014 no media datagrams reached this client (path healthy: ${J.evidence}); webrtc track remains authoritative`)}},C);try{await A.firstMedia}catch(X){m(),S.debug("[urun] webtransport ended before any media flowed:",X);return}if(m(),a||d.activeTransport!=="webtransport"||typeof o.captureStream!="function")return;c=o.captureStream();let j=c.getVideoTracks()[0];j&&(l=!0,r.onOverrideTrack(j))},P=!1;return(async()=>{let A=await Ooe(t,r.runtimePhase,{sessionId:e,runtimeWaitCapMs:r.runtimeWaitCapMs,isDisposed:()=>a});if(a)return;if(A==="gone"){S.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),i?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}P=!0;let C=await d.connect();if(a){d.disconnect().catch(()=>{});return}await W(C)})().catch(A=>{if(m(),a){S.debug("[urun] transport negotiation aborted: session disposed mid-dial:",A);return}if(r.allowWebRtcFallback===!1){S.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",A),E();return}i?.proceed(`negotiation unavailable: ${A instanceof Error?A.message:String(A)}`),S.warn("[urun] transport negotiation unavailable, staying on webrtc:",A),E()}),{activeTransport:()=>d.activeTransport,mediaTransportAttempted:()=>P,watchDownlinkStall(A){d.watchDownlinkStall(A)},dispose(){a=!0;try{h?.(),m(),O(),u(),r.onOverrideAudioTrack?.(null)}catch(A){S.error("[urun] dial negotiation dispose: a teardown step failed:",A)}finally{d.disconnect().catch(()=>{})}}}}var Uoe=new Set;function hH(t){if(t.functionsUrl)return{functionsUrl:t.functionsUrl,orgId:t.orgId,apiKey:t.apiKey,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}}var Moe="rpc",NI="$presence",Hq=6e4,joe=5e3,UI=["control",_v],vv=2e4,SR=3e4,Vq=3e4,$oe="rpc-resp";function Foe(t){return`${$oe}:${t}`}function MI(){return dv()}function qoe(t){if(t&&typeof t=="object"){let e=t.error;if(e&&typeof e=="object"){let{message:r,code:s}=e;return{message:typeof r=="string"?r:JSON.stringify(e),code:typeof s=="string"?s:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof t=="string"?t:JSON.stringify(t)}}function Hoe(t,e,r,s,n,i,o,a,c,l){let u=[],d=null,h=!1,f=null,m=!1,w,p,b=new Promise((q,ne)=>{w=q,p=ne});b.catch(()=>{});let v=o(),E=null,O=null,W=null,P=null,A=null,C=null,R=!0,j=()=>{W&&(clearTimeout(W),W=null),P&&(P(),P=null)},X=()=>{A&&(clearTimeout(A),A=null),C&&(C(),C=null)},J=!1,V=()=>{J||!m||(J=!0,t.delete(["rpc",e]))},H=()=>{R=!1,j(),X(),E?.(),E=null,O?.(),O=null,a?.removeEventListener("abort",I),v.dispose(),V()},Y=()=>{if(d){if(u.length>0){let q=d;d=null,q.resolve({value:u.shift(),done:!1})}else if(f!==null){let q=d;d=null,q.reject(f)}else if(h){let q=d;d=null,q.resolve({value:void 0,done:!0})}}},D=q=>{h||(u.push(q),Y())},Q=q=>{h||(f=q,h=!0,p(q),H(),Y())},re=q=>{h||(h=!0,w(q),H(),Y())},I=()=>{let q=a?.reason;Q(q instanceof sa?q:new Eg(e))},U=q=>{if(!(h||!q||typeof q!="object"))switch(X(),V(),q.t){case"delta":typeof q.delta=="string"&&D(q.delta);break;case"response":re(q.body);break;case"error":{let{message:ne,code:le}=qoe(q.body);Q(new sa(ne,{requestId:e,code:q.code??le}));break}}},G=()=>{let q=v.messages()[Symbol.asyncIterator]();E=()=>{q.return?.(void 0)};let ne=()=>{R&&q.next().then(le=>{if(R){if(le.done){h||re(void 0);return}U(le.value),ne()}},le=>{R&&Q(le)})};ne()},$=()=>{if(!m){if(m=!0,a){if(a.aborted){Q(new Eg(e));return}a.addEventListener("abort",I,{once:!0})}O=c?.(q=>Q(q))??null,G(),t.set({rpc:{[e]:{args:r,respond_on:s,consumer_id:n,stream:i}}}),l&&l>0&&!t.synced&&(W=setTimeout(()=>{W=null,!h&&!t.synced&&Q(new Q1(l,e))},l),P=t.onSynced(()=>j())),C=t.onSynced(()=>{C=null,!(h||J||A)&&(A=setTimeout(()=>{A=null,!(h||J)&&S.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Vq/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},Vq))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if($(),u.length>0)return Promise.resolve({value:u.shift(),done:!1});if(f!==null){let q=f;return f=null,Promise.reject(q)}return h?Promise.resolve({value:void 0,done:!0}):new Promise((q,ne)=>{d={resolve:q,reject:ne}})},return(){return h||(h=!0,w(void 0),H()),Promise.resolve({value:void 0,done:!0})},throw(q){return h||(h=!0,p(q),H()),Promise.reject(q)}}}},body:b,start:$}}function Wq(t){if(t&&typeof t=="object"){let{epoch:e,by:r}=t,s={epoch:typeof e=="number"?e:0};return(r==="runtime"||r==="browser")&&(s.by=r),s}}function Voe(t,e){let r=t.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:n,br:i}=r,o={};(s==="audio"||s==="video"||s==="data")&&(o.kind=s);let a=Wq(n);a&&(o.rt=a);let c=Wq(i);return c&&(o.br=c),o}var Woe=class{constructor(t,e,r,s,n){this._name=t,this._transport=e,this._streamData=r,this._controlDoc=s,this._onActivity=n,this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_directOut=!1;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let t=this;return{[Symbol.asyncIterator](){let e=[...t._replay],r=null,s=!1,n=null,i={push(a){if(!s)if(r){let c=r;r=null,c.resolve({value:a,done:!1})}else e.push(a)},end(){if(s=!0,r){let a=r;r=null,a.resolve({value:void 0,done:!0})}}};t._messageConsumers.add(i);let o=()=>{s=!0,t._messageConsumers.delete(i)};return t._transport.mediaAvailability().then(a=>{if(!(a===null||s)&&(n=t._streamConsumeUnavailableError(a),o(),r)){let c=r;r=null,c.reject(n)}}),{next(){return e.length>0?Promise.resolve({value:e.shift(),done:!1}):n?Promise.reject(n):s?Promise.resolve({value:void 0,done:!0}):new Promise((a,c)=>{r={resolve:a,reject:c}})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let t=this._transport.mediaUnavailableReason();if(t)throw this._streamConsumeUnavailableError(t)}_streamConsumeUnavailableError(t){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${t}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,t=>this._deliver(t))))}_deliver(t){this._replay.push(t);for(let e of this._messageConsumers)e.push(t)}get track(){let t=this._transport.getTrackByName(this._name)??this._track;return t!==this._track&&this._setTrack(t),this._overrideTrack??this._track}get directOut(){return this._directOut}_setOverrideTrack(t,e){if(this._overrideTrack===t&&this._directOut===(e?.directOut??!1))return;this._overrideTrack=t,this._directOut=t?e?.directOut??!1:!1,t&&t.addEventListener?.("ended",()=>{this._overrideTrack===t&&this._setOverrideTrack(null)},{once:!0});let r=t??this._transport.getTrackByName(this._name)??this._track,s=this._handlers.get("track");if(s)for(let n of s)n(r)}_claimBrowserProducer(t){if(!this._controlDoc)return;let e=this._controlDoc(),r=Voe(e,this._name),s=r?.br;if(s?.by==="runtime")throw new Z1(this._name,"runtime","browser");if(s)return;let n={br:{epoch:1}};r?.rt&&(n.rt=r.rt);let i=r?.kind??t;i&&(n.kind=i),e.set({streams:{[this._name]:n}})}async attach(t){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(t,this._name)}async attachVideo(t){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(t,this._name)}async emit(t,e={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,t,e)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(t){if(t!=="live"&&(!Number.isFinite(t)||t<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,t)}chunks(t={}){let e=t.source??lR;return Hie(e,{track:()=>this.track,onTrack:r=>this.on("track",r)})}onSeeked(t){return this._transport.on("seeked",(e,r)=>{e===this._name&&t(r)})}on(t,e){let r=this._handlers.get(t);return r||(r=new Set,this._handlers.set(t,r)),r.add(e),()=>{r?.delete(e),r?.size===0&&this._handlers.delete(t)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let t of this._messageConsumers)t.end();this._messageConsumers.clear()}_setTrack(t){if(this._track=t,t&&t.addEventListener("ended",()=>{this._track===t&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let e=this._handlers.get("track");if(e)for(let r of e)r(t)}},ER=class fH{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new SI;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceIdleMs=Hq;_presenceLastActivityAt=Date.now();_presencePresent=!1;_presenceTimer=null;_presenceTracker=null;_gateDocUp={};_gate="open";_gateTimer=null;_gateDocUnsubs=[];_gateOff=!1;_gatedFrom;_gatedWith;_publicPhase;_phaseHandlers=new Set;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_namedSessionIdProbe;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,r,s,n,i,o){this._sessionId=e,this._multiplexer=r,this._transport=s,this._recordingsAuth=n,this._artifactsAuth=i,this._streamData=wI(s),this._wireControlDocIncarnation(),this._lifecycleUnsub=oR(()=>this.recover()),this._activityMode=o?.activity??"auto",this._presenceIdleMs=o?.presenceIdleMs??Hq,this._activity=rR({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new iR({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this._notePresenceActivity(),this._activation=new zI({onPhase:a=>this.onPhase(a),hint:()=>this.doc(_v).get(HI)??this.doc("control").get(VI),onData:(a,c)=>this._streamData.onData(a,c)}),this._transport.on("phase",()=>this._applyLiveGate());for(let a of UI)this._gateDocUnsubs.push(this.doc(a).onConnectionState(c=>{this._gateDocUp[a]=c.connected,this._applyLiveGate()}))}_applyLiveGate(){let e=this._transport.phase;if(!e)return;let r=this._gateOff||!this._docConnector.connected||UI.every(i=>this._gateDocUp[i]);if(e.name!=="live"||r?(clearTimeout(this._gateTimer??void 0),this._gateTimer=null,this._gate="open"):this._gate==="open"&&(this._gate="connecting",this._gateTimer=setTimeout(()=>{this._gateTimer=null,this._gate="failed",this._applyLiveGate()},vv)),e===this._gatedFrom&&this._gate===this._gatedWith)return;this._gatedFrom=e,this._gatedWith=this._gate;let s=UI.filter(i=>!this._gateDocUp[i]).join("/"),n=this._gate==="open"?e:this._gate==="connecting"?{...e,name:"connecting",reason:"docs_connecting"}:{...e,name:"error",reason:"doc_plane_unreachable",error:{kind:"transport-failed",code:"doc_plane_unreachable",reason:`the session's ${s} doc connection did not open within ${vv/1e3}s (still retrying)`}};if(n!==this._publicPhase){this._publicPhase=n;for(let i of[...this._phaseHandlers])i(n)}}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",r=>{this._transport.applyControlDocState(r)})}static async attach(e,r){let s=await uq({baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,sessionId:e,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}),n=r.getAccessToken?await r.getAccessToken()??void 0:r.jwt,i=new Y1,o=new uv({url:s.wsUrl,orgId:r.orgId,jwt:n,authProvider:r.authProvider,sessionId:e,iceServers:s.response.ice_servers}),a=new fH(e,i,o,hH(r),$I({...r,baseUrl:s.baseUrl}),{activity:r.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:s.wsUrl,sessionId:e,iceServers:s.response.ice_servers}),o.setEndsAt(s.endsAt),Ad()&&await Cg();let c=r.getAccessToken,l=c?u=>!u?.redial&&n?n:Promise.resolve(c()).then(d=>d??n):n;return a.setDocTransport({wsUrl:s.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase!==this._gatedFrom&&this._applyLiveGate(),this._publicPhase??this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){let e=this._transport.status,r=this.phase;return!e||!r||r===this._transport.phase?e:{...e,phase:r.name,...r.error?{error:r.error}:{}}}get region(){return this._transport.region}onPhase(e){return e(this.phase),this._phaseHandlers.add(e),()=>{this._phaseHandlers.delete(e)}}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return rv(this,e)}on(e,r){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(r),this._generationTickStop||(this._generationTickStop=ZI(this.doc("control"),s=>{for(let n of Array.from(this._generationTickHandlers))try{n(s)}catch(i){S.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(r),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let r=new Cv(e);return this._recordingsAccessor={list:s=>r.list(s??this._sessionId),get:s=>r.get(s),retain:(s,n)=>r.retain(s,n),pin:s=>r.pin(s),unpin:s=>r.unpin(s),permanent:s=>r.permanent(s),delete:s=>r.delete(s)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Og(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,r)=>new Og(this._requireArtifactsAuth()).getDownloadUrl(e,r??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e!==this._sessionId){this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}setNamedSessionIdProbe(e){this._namedSessionIdProbe=e}namedSessionId(){return this._namedSessionIdProbe?.()}stream(e){let r=this._streams.get(e);return r||(r=new Woe(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,r),this._activation.watch(e,r)),r}doc(e){let r=this._docs.get(e);return r||(r=new EI(e,this._sessionId,Uoe.has(e)?null:this._docConnector.connect),this._docs.set(e,r)),r}get presence(){return this._presence||(this._presence=CI(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch(),this._notePresenceActivity()}keepalive(){this._activity?.touch(),this._notePresenceActivity()}presenceDetach(){this._presenceDetachNow()}_notePresenceActivity(){this._presenceLastActivityAt=Date.now(),this._presencePresent||(this._presencePresent=!0,this.doc(NI).awareness.setLocalState({role:"client"})),this._presenceTimer===null&&(this._presenceTimer=setInterval(()=>this._presenceSweep(),joe),this._presenceTimer.unref?.())}_presenceSweep(){this._presencePresent&&(Date.now()-this._presenceLastActivityAt<this._presenceIdleMs||(this._presencePresent=!1,this.doc(NI).awareness.setLocalState(null)))}_presenceDetachNow(){this._presenceTimer!==null&&(clearInterval(this._presenceTimer),this._presenceTimer=null),this._presencePresent&&(this._presencePresent=!1,this._docs.get(NI)?.awareness.setLocalState(null))}_autoTouch(){this._activityMode!=="explicit"&&(this._activity?.touch(),this._notePresenceActivity())}activity(){this._activity?.touch(),this._notePresenceActivity()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let r=hv(e.wsUrl),s=typeof e.token=="function"?"<token-supplier>":e.token??"",n=e.attach?`${e.attach.gen}:${e.attach.token}`:"",i=`${r}${s}${n}${this._sessionId}`;i!==this._docEndpointKey&&(this._docEndpointKey=i,this.connectDocs(_I({serverUrl:r,sessionId:this._sessionId,token:e.token,attach:e.attach,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,r={}){let s=MI(),n=new AbortController;r.signal&&(r.signal.aborted?n.abort(r.signal.reason):r.signal.addEventListener("abort",()=>n.abort(r.signal.reason),{once:!0}));let i=null;if(typeof r.timeout=="number"&&r.timeout>=0){let c=r.timeout;i=setTimeout(()=>n.abort(new J1(c,s)),c)}let o=this._consumeResponse(s,e,!1,n.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,r,s,n,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(Moe),a=Foe(e);return Hoe(o,e,r,a,this._streamData.consumerId,s,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??SR)}requestStream(e,r={}){let s=MI();return this._consumeResponse(s,e,!0,r.signal,r.docSyncTimeout).deltas}complete(e,r={}){let s=MI(),n=this._consumeResponse(s,e,!1,r.signal,r.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(r){S.warn("[urun] session recovery hook failed:",r)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Noe(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:r=>this._transport.on("phase",r)},onOverrideTrack:r=>this.stream("video")._setOverrideTrack(r),onOverrideAudioTrack:r=>this.stream("audio")._setOverrideTrack(r,{directOut:!0}),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Td)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Td);let e=this._cancelHandler().then(r=>(this.disconnect(),r));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){S.info(`[urun] session detach (${e??"client detach"}) \u2014 caller:
|
|
176
176
|
`+(new Error().stack??"").split(`
|
|
177
177
|
`).slice(1,4).join(`
|
|
178
|
-
`));let r=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of r)try{s()}catch{}try{try{this._lifecycleUnsub?.()}catch{}this._lifecycleUnsub=null;try{this._dialNegotiation?.dispose()}catch(n){S.error("[urun] session detach: dial negotiation dispose failed:",n)}this._dialNegotiation=null;try{this._activity?.dispose()}catch{}this._activity=null;try{this._presenceDetachNow()}catch{}try{this._presenceTracker?.dispose()}catch{}this._presenceTracker=null;try{this._activation.dispose()}catch{}try{this._generationTickStop?.()}catch{}this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let s=Array.from(this._activeRequests);this._activeRequests.clear();for(let n of s)try{n(new ev)}catch{}this._gateOff=!0,clearTimeout(this._gateTimer??void 0),this._gateTimer=null;for(let n of this._gateDocUnsubs.splice(0))n();for(let[n,i]of this._docs)try{i.dispose()}catch(o){S.error(`[urun] session detach: doc '${n}' dispose failed:`,o)}this._docs.clear();for(let[n,i]of this._streams)try{i.dispose()}catch(o){S.error(`[urun] session detach: stream '${n}' dispose failed:`,o)}this._streams.clear()}finally{this._transport.disconnect(e)}}},zoe={failed:!0,rejected:!0,expired:!0,cancelled:!0,canceled:!0,closed:!0},Koe={idle:!0,queued:!0,provisioning:!0,waiting_for_capacity:!0,unavailable:!0,connecting:!0};function Goe(t){return Koe[t]===!0}function Xoe(t){let e=t.fetchImpl??globalThis.fetch,r=t.baseUrl.replace(/\/+$/,""),s=null,n=!1,i=!1,o=0,a=t.transport.on("phase",h);function c(){i||(i=!0,a(),d())}function l(){o+=1,o>=15&&c()}async function u(){if(!n){n=!0;try{let f=await t.jwt?.(),m=await e(`${r}/api/session-requests/${encodeURIComponent(t.requestId)}?wait_s=15`,{...f?{headers:{authorization:`Bearer ${f}`}}:{},signal:Yoe(20*1e3)});if(m.status===404||m.status===410){c();return}if(m.ok){let w=await m.json().catch(()=>{}),p=typeof w?.status=="string"?w.status:void 0;if(p!==void 0&&zoe[p]===!0){c();return}o=0;return}l()}catch{l()}finally{n=!1}}}function d(){s!==null&&(clearInterval(s),s=null)}function h(){if(Goe(t.transport.phase.name)){s===null&&(s=setInterval(()=>{u()},2e4),s.unref?.());return}d()}return h(),c}function Yoe(t){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(t):void 0}function Joe(t){return`urun:session:v2:${t.orgId}:${t.app}:${t.functionName}`}function CR(){try{return globalThis.sessionStorage??null}catch{return null}}var kR=new Map;function qI(t){if(!t)return;let e=t.split(".");if(!(e.length<2))try{let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=JSON.parse(atob(r+"=".repeat((4-r.length%4)%4)));return typeof s?.sub=="string"&&s.sub.length>0?s.sub:void 0}catch{return}}function Qoe(t,e){return t!==void 0&&e!==void 0&&t!==e}function zq(t,e){let r=CR(),s=null;if(r)try{let i=r.getItem(t);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(s={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{s=null}let n=kR.get(t)??s??null;return!n||Qoe(n.actor,e)?null:n}function Zoe(t,e){let r={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};kR.set(t,r);let s=CR();if(s)try{s.setItem(t,JSON.stringify(r))}catch{}}function jI(t){kR.delete(t);let e=CR();if(e)try{e.removeItem(t)}catch{}}var Kq=new Set(["paused","acquiring","live"]),eae=new Set(["24h","keep"]);function Gq(t){if(typeof t!="string"||t.length===0)return null;let e=new Date(t);return Number.isFinite(e.getTime())?e:null}function tae(t){if(typeof t?.id!="string"||t.id.length===0)throw new Gi("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof t.state!="string"||!Kq.has(t.state))throw new Gi(`[urun] session ${t.id} reported an unrecognized state ${JSON.stringify(t.state)} \u2014 this @urun-sh/core build knows only ${[...Kq].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof t.recordings_expired=="boolean"?e=t.recordings_expired:S.warn(`[urun] session ${t.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:t.id,label:typeof t.label=="string"&&t.label.length>0?t.label:null,state:t.state,app:typeof t.app=="string"?t.app:"",functionName:typeof t.function=="string"?t.function:"",createdAt:Gq(t.created_at),lastActiveAt:Gq(t.last_active_at),archived:t.archived===!0,preview:typeof t.preview=="string"&&t.preview.length>0?t.preview:null,recordingsExpired:e,retention:eae.has(t.retention)?t.retention:(t.retention!==void 0&&S.warn(`[urun] session ${t.id} reported an unrecognized retention ${JSON.stringify(t.retention)} \u2014 defaulting to '24h'`),"24h")}}var TR=class{_request;_app;constructor(t,e){this._app=t,this._request=e}async list(t={}){let{rows:e,nextCursor:r}=await cq({...this._request,app:t.app??this._app,functionName:t.functionName,includeArchived:t.includeArchived,limit:t.limit,cursor:t.cursor});return{sessions:e.map(tae),nextCursor:r}}async end(t){await lq({...this._request,sessionId:t})}async archive(t){await pI({...this._request,sessionId:t,archived:!0})}async unarchive(t){await pI({...this._request,sessionId:t,archived:!1})}async setName(t,e,r={}){await dq({...this._request,sessionId:t,name:e,source:r.source})}};function Xq(t,e,r){let s=qI(r);Zoe(t,s!==void 0?{sessionId:e,actor:s}:{sessionId:e})}var rae=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function pH(t,e){return new TR(t,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function mH(t,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(r,s){if(!(rae.has(s)||typeof s!="string"))return(n,i)=>{let o=n??{},a=Joe({orgId:e.orgId,app:t,functionName:s}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,l,u=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,d=u(),h=e.jwt,f=e.getAccessToken?async I=>{let U=await e.getAccessToken(I);return U&&(h=U),U}:void 0,m={...e,getAccessToken:f},w=new Y1,p=new uv({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:d,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new ER(d,w,p,hH(m),$I(m),{activity:i?.activity,presenceIdleMs:i?.presenceIdleMs}),v,E=!1,O,W=!1,P,A,C=new Promise(I=>{A=I}),R,j=I=>{I.sessionId||P||(P="teardown",R="ticket",Ag({baseUrl:I.baseUrl,requestId:I.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider}))},X=I=>{P||I.sessionId||(P="abandon",Ag({baseUrl:I.baseUrl,requestId:I.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider,reason:"client_abandoned"}))},J=I=>{let U=I.sessionId||!l?I:{...I,sessionId:l};v=U,A({status:"ready",handle:U}),(W||P==="teardown")&&j(U)};b.setNamedSessionIdProbe(()=>v?.sessionId),b.setEndHandler(async()=>{let I=v?{status:"ready",handle:v}:await C;if(I.status==="unavailable")throw new Td("[urun] session allocation failed before a releasable request was created",{cause:I.cause});let U=v??I.handle;return jI(a),P==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(P="end",U.sessionId?hI({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):uI({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let I=v?{status:"ready",handle:v}:await C;if(I.status==="unavailable")throw new Td("[urun] session allocation failed before a cancellable request was created",{cause:I.cause});let U=v??I.handle;if(U.sessionId)throw new Sn(`[urun] cancel() is for a queued admission request, but this call already has session ${U.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:U.sessionId,code:"cancel_on_live_session"});P="end";try{let G=await uI({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return jI(a),G}catch(G){throw P==="end"&&(P=void 0),G}});let V=async I=>{let U,G=i?.sessionId??e.sessionKey??l,$,q;if(G===void 0&&!c){let ot=zq(a);if(ot?.sessionId){if(q=qI(h),ot.actor!==void 0&&q===void 0&&f){let ht=await Promise.resolve(f()).catch(()=>{});q=qI(ht??e.jwt)}$=ot.actor!==void 0&&q!==void 0&&ot.actor!==q?void 0:ot.sessionId}}let ne=G??$,le=(ot,ht)=>fI({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:t,functionName:s,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,...e.shape?{shape:e.shape}:{},idempotencyKey:ot,sessionKey:ht,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:gt=>{p.reportAdmission(gt),gt.sessionId&&!l&&(l=gt.sessionId,U=gt.sessionId,v&&v.sessionId!==gt.sessionId&&J({...v,sessionId:gt.sessionId}),E||(e.sessionKey||Xq(a,gt.sessionId,h),b.setSessionId(gt.sessionId)))},onRequest:J}),Ce;try{Ce=await le(I,ne)}catch(ot){let ht=ot instanceof Ut&&ot.code==="session_name_not_yours"&&ne!==void 0&&ne===l&&i?.sessionId===void 0&&e.sessionKey===void 0;if($===void 0&&!ht||!(ot instanceof Ut)||ot.code!=="session_name_not_yours")throw ot;let gt=$??ne;if(gt===void 0)throw ot;S.warn(`[urun] session_name_not_yours: the control plane refused session ${gt} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),ht&&(l=void 0),zq(a,q)?.sessionId===gt&&jI(a),Ce=await le(u(),void 0)}let nt=f?await f()??void 0:e.jwt;if(U&&U!==Ce.sessionId)throw v&&v.sessionId!==Ce.sessionId&&J({...v,sessionId:Ce.sessionId}),new Ut(`Gateway contract violation: admission minted session ${U} but allocation completed as ${Ce.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=Ce.sessionId,v&&v.sessionId!==Ce.sessionId&&J({...v,sessionId:Ce.sessionId}),E||(e.sessionKey||Xq(a,Ce.sessionId,h),b.setSessionId(Ce.sessionId),D=iv(Ce.baseUrl)?{baseUrl:Ce.baseUrl,sessionId:Ce.sessionId}:null,b.setArtifactsAuth($I({...m,baseUrl:Ce.baseUrl})),p.setEndsAt(Ce.endsAt),p.seedRegion(gI(Ce.response))),{url:Ce.wsUrl,sessionId:Ce.sessionId,jwt:nt,iceServers:Ce.response.ice_servers,endsAt:Ce.endsAt,sfuAttach:Ce.sfuAttach}},H,Y,D=null,Q=f?I=>!I?.redial&&H?H:Promise.resolve(f(I?.redial?{forceRefresh:!0,reason:"background"}:void 0)).then(U=>H=U??H):()=>H,re=()=>{let I=p.connectedUrl;return I?hv(I):void 0};if(p.setConnectionResolver(async()=>{let I=await V(u());return H=I.jwt,Y=I.sfuAttach,I}),p.setConnectionViewRefresher(async()=>D?aq({baseUrl:D.baseUrl,sessionId:D.sessionId,jwt:h}):null),p.on("connected",()=>{p.multiplexer&&w.setTarget(p.multiplexer);let I=p.connectedUrl;I&&b.setDocTransport({wsUrl:I,token:Q,attach:Y,resolveServerUrl:re})}),(async I=>{let U;try{U=await V(I)}catch(q){if(E){A({status:"unavailable",cause:q});return}S.error(`[urun] Failed to create session for ${s}:`,q),v&&X(v);let ne=q instanceof Error?q:new Error(String(q)),le=q instanceof Ut?q.httpStatus:void 0,Ce=q instanceof Ut?q.code:void 0,nt=q instanceof Ut?q.retryAfterSeconds:void 0;p.reportAllocationFailure(ne,le,Ce,nt),A({status:"unavailable",cause:q});return}if(E)return;let G=D!==null?null:e.baseUrl,$=v?.requestId;G!==null&&$!==void 0&&!E&&(O=Xoe({requestId:$,baseUrl:G,jwt:async()=>f?await f()??h:h,transport:p})),p.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers,sfuAttach:U.sfuAttach}),Ad()&&await Cg(),H=U.jwt,Y=U.sfuAttach,b.setDocTransport({wsUrl:U.url,token:Q,attach:Y,resolveServerUrl:re}),await p.connect({app:t,functionName:s,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback})})(d).catch(I=>{S.error(`[urun] Failed to connect session for ${s}:`,I)}),e.releaseOnLeave!==!1){let I=aR(()=>{if(E=!0,O?.(),O=void 0,p.leaveLeg())return;if(p.connectedUrl!==null){p.disconnect();return}p.disconnect();let ne=v;ne?j(ne):W=!0});b.onDisconnect(I);let U,G,$=!1,q=()=>{$||($=!0,U?.(),G?.())};C.then(ne=>{ne.status!=="ready"||$||(U=cR(()=>v!==void 0))}),G=b.onPhase(ne=>{let le=ne?.name;(le==="paused"||le==="error")&&q()}),$&&G(),b.onDisconnect(q)}return b}}})}var RNe=globalThis.require??(0,SH.createRequire)(B),EH="https://api.urun.sh",CH="URUN_DEV";function sae(){if(typeof process>"u")return!1;let t=process.env?.[CH];if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"}var Ug=class extends Error{status;code;constructor(t,e,r){super(t),this.name="ClientTokenError",this.status=e,this.code=r}};async function nae(t,e={}){if(!t)throw new Ug("[urun] createClientToken requires an org API key");let r=e.fetch??globalThis.fetch,s=cr(e.baseUrl??EH),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),e.bindPrincipal&&(n.bind_principal=!0),(e.dev??sae())&&(n.dev=!0);let i;try{i=await r(`${s}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(w){throw new Ug(`[urun] client token mint request failed: ${w instanceof Error?w.message:String(w)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let w=typeof o.message=="string"?o.message:`HTTP ${i.status}`,p=typeof o.error_code=="string"?o.error_code:void 0;throw new Ug(`[urun] client token mint failed: ${w}`,i.status,p)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,u=typeof o.expires_in=="number"?o.expires_in:void 0,d=typeof o.billing_audience=="string"?o.billing_audience:void 0,h=typeof o.credits_admission_ok=="boolean"?o.credits_admission_ok:void 0,f=typeof o.credits_refusal_reason=="string"?o.credits_refusal_reason:void 0;if(!a)throw new Ug("[urun] client token mint returned no token (control-plane contract violation)",i.status);let m=Number.isFinite(l)?new Date(l):new Date(Date.now()+(u??60)*1e3);return{token:a,expiresAt:m,orgId:c,...d!==void 0?{billingAudience:d}:{},...h!==void 0?{creditsAdmissionOk:h}:{},...f!==void 0?{creditsRefusalReason:f}:{}}}var gH=3e4,yH="stream:",iae=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(t,e){this._ws=t,this._multiplexer=e,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let n=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(n.timer),s.error?n.reject(new Error(s.error)):n.resolve(s.result)}})}async get(t){return this._sendRpc("store.get",{key:t})}async has(t){return await this._sendRpc("store.has",{key:t})}on(t,e){let r=`${yH}${t}`;return this._multiplexer.on(r,s=>{e(s)})}emit(t,e){let r=`${yH}${t}`,s=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{data:e};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(t,e){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let n=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(n)&&(this._pendingRpc.delete(n),s(new Error(`RPC request "${t}" timed out after ${gH}ms`)))},gH);this._pendingRpc.set(n,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:n,type:t,...e}))})}};function oae(t){let e=`${t.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(t.orgId)}`,r=new WebSocket(e);(t.jwt||t.apiKey)&&r.addEventListener("open",()=>{r.send(JSON.stringify({type:"auth",orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,apiKey:t.apiKey}))});let s=new X1(r);return new iae(r,s)}var aae='video/mp4; codecs="avc1.42E01E"';function cae(t,e){let r=e?.codec??aae,s=document.createElement("video");s.muted=!0,s.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);s.src=i,n.addEventListener("sourceopen",()=>{let h;try{h=n.addSourceBuffer(r)}catch(p){throw p instanceof DOMException&&p.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):p}let f=t.getReader();function m(){return h.updating?new Promise(p=>{h.addEventListener("updateend",()=>p(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:p,value:b}=await f.read();if(p){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{h.appendBuffer(b)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let E=h.buffered;if(E.length>0){let O=E.start(E.length-1);h.remove(0,O),await m(),h.appendBuffer(b)}else throw v}else throw v}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}w()}),s.play().catch(()=>{});let o=s,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(s),l=c.getTracks(),u=0,d=l.length;if(d===0)s.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let h of l)h.addEventListener("ended",()=>{u++,u>=d&&URL.revokeObjectURL(i)});return c}function lae(t){return t.status.startsWith("pending_")}var Tv=class extends Error{status;code;constructor(t,e){super(t),this.name="CreditsError",this.status=e.status,this.code=e.code,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},PR=class extends Tv{constructor(t="[urun] credits: unauthorized",e="unauthorized"){super(t,{status:401,code:e}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function dae(t,e,r){let s=r||e||`HTTP ${t}`;return t===401?new PR(s,e??"unauthorized"):new Tv(s,{status:t,code:e??`http_${t}`})}var kH=class{constructor(t){this._options=t,this._base=`${t.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let t=await this._request("GET","/balance");if(!t||typeof t!="object"||typeof t.org_id!="string")throw new Tv("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return t}async getLedger(t={}){let e=(await this._request("GET","/ledger",{params:t.limit!==void 0?{limit:String(t.limit)}:void 0})).entries;return Array.isArray(e)?e:[]}async _request(t,e,r={}){let s=this._buildUrl(e,r.params),n=await this._resolveToken(),i=await this._fetch(s,t,n);if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await this._fetch(s,t,n))}if(!i.ok){let{code:o,message:a}=await this._readError(i);throw dae(i.status,o,a)}return this._readJson(i)}_buildUrl(t,e){let r=`${this._base}${t}`,s=Object.entries(e??{}).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(t,e,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(t,{method:e,headers:s})}async _resolveToken(){if(this._options.getAccessToken){let e=await this._options.getAccessToken();if(e)return e}let t=this._options.jwt??this._options.apiKey;if(!t)throw new PR("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return t}async _readJson(t){try{return await t.json()}catch{return{}}}async _readError(t){try{let e=(await t.json()).error;if(e&&typeof e=="object"){let{code:r,message:s}=e;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${t.status}`}}}catch{}return{message:`HTTP ${t.status}`}}};function uae(t){return new kH(t)}var TH=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function bH(t){let e=[];return t.audio&&e.push("audio"),t.video&&e.push("video"),e.join("+")}function xH(t,e){return e==="audio"?t.getAudioTracks():t.getVideoTracks()}function wH(t,e){let r=t.getTracks();if(r.length===1&&r[0]===e)return t;try{return new MediaStream([e])}catch{return t}}function AR(t,e){for(let r of[...t.lostListeners])try{r(e)}catch{}}var AH=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(t){this.injectedGetUserMedia=t?.getUserMedia}claim(t,e){return this.enqueue(async()=>{let r=this.claims.get(t);r&&(this.claims.delete(t),r.released=!0,r.track=null,r.stream=null,AR(r,new Error(`${t} capture claim superseded by a newer claim`)));let s=this.createState(t,e);return this.claims.set(t,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(t){let e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!t?.getUserMedia)throw new TH;return e=>t.getUserMedia(e)}async converge(t){let e=[];for(let o of this.claims.values())o!==t&&o.track&&e.push(o);if(e.length>0)try{let o=await this.resolveGetUserMedia()({[t.kind]:t.constraints}),a=xH(o,t.kind)[0]??null;if(a){t.track=a,t.stream=wH(o,a);return}}catch{}for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let r=this.resolveGetUserMedia(),s={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await r(s)}catch(o){let a=`one-capture getUserMedia(${bH(s)}) failed`,c=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==t){let u=new Error(`${a} \u2014 ${l.kind} capture lost: ${c||o}`);u.cause=o,AR(l,u)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===t?1:a===t?-1:0);for(let o of i){let a=xH(n,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${bH(s)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===t)throw c;AR(o,c);continue}if(o.track=a,o.stream=wH(n,a),o!==t)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(t,e){let r=this,s={kind:t,constraints:e,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:t,get track(){return s.track},get stream(){return s.stream},update(n){return r.enqueue(async()=>{if(s.released)throw new Error(`${t} capture claim already released`);if(s.constraints=n,await r.converge(s),!s.track)throw new Error(`${t} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(t)===s&&r.claims.delete(t),s.track?.stop(),s.track=null,s.stream=null)},onTrack(n){return s.trackListeners.add(n),()=>s.trackListeners.delete(n)},onLost(n){return s.lostListeners.add(n),()=>s.lostListeners.delete(n)}}};return s}},hae=null;function fae(){return hae??=new AH}var IH="input",pae=30;function mae(t){let e=t.now??Date.now,r=t.field??IH,s=1e3/Math.max(t.hz??30,.001),n=new Set,i=0,o=0,a=0,c=0,l,u=null,d=!1,h=()=>{if(d)return;l=e(),c+=1;let m={keys:[...n],buttons:i,pointer:{x:o,y:a},seq:c,at:l};try{t.awareness.setLocalStateField(r,m)}catch{}},f=()=>{if(d)return;let m=e();if(l===void 0||m-l>=s){u&&(clearTimeout(u),u=null),h();return}if(u)return;let w=Math.max(s-(m-l),0);u=setTimeout(()=>{u=null,h()},w),u.unref?.()};return{keyDown(m){let w=String(m).toLowerCase();n.has(w)||(n.add(w),f())},keyUp(m){let w=String(m).toLowerCase();n.delete(w)&&f()},setButtons(m){let w=Number.isFinite(m)?Number(m):0;w!==i&&(i=w,f())},movePointer(m,w){let p=Number.isFinite(m)?Number(m):0,b=Number.isFinite(w)?Number(w):0;p===0&&b===0||(o+=p,a+=b,f())},heldKeys(){return[...n]},clear(){d||(n.clear(),i=0,u&&(clearTimeout(u),u=null),h())},dispose(){if(d)return;let m=n.size>0||i!==0;n.clear(),i=0,u&&(clearTimeout(u),u=null),m&&h(),d=!0}}}var gae=1024,yae=.92,bae=262144,xae=256e3,IR=[.9,.8,.7,.6,.5],vH=.8,wae=8;function DR(t,e,r){if(!(t>0)||!(e>0))throw new Error(`reference image has no pixels (${t}x${e})`);let s=Math.min(1,r/Math.max(t,e));return{width:Math.max(1,Math.round(t*s)),height:Math.max(1,Math.round(e*s))}}async function vae(t){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(t,{imageOrientation:"from-image"})}async function RH(t,e,r){let s=await new Promise(n=>{t.toBlob(n,e,e==="image/jpeg"?r:void 0)});if(!s)throw new Error(`could not encode the reference image as ${e}`);return s}function _H(t,e){S.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${t} -> ${e} bytes`)}async function RR(t,e,r,s,n){let i=document.createElement("canvas");i.width=e,i.height=r;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return s==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,r)),o.drawImage(t,0,0,e,r),await RH(i,s,n)}async function _ae(t,e,r,s){let{width:n,height:i}=e,o=await RR(t,n,i,r,s);if(o.size<=256e3)return{blob:o,width:n,height:i};if(r==="image/jpeg"){for(let c of IR)if(!(c>=s)&&(o=await RR(t,n,i,r,c),o.size<=256e3))return _H(`quality ${s} -> ${c}`,o.size),{blob:o,width:n,height:i}}let a=r==="image/jpeg"?IR[IR.length-1]:s;for(let c=0;c<wae;c++)if(n=Math.max(16,Math.round(n*vH)),i=Math.max(16,Math.round(i*vH)),o=await RR(t,n,i,r,a),o.size<=256e3)return _H(`downscaled to ${n}x${i} @ q${a}`,o.size),{blob:o,width:n,height:i};throw new Error(`this image cannot be sent: even at ${n}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Sae(t,e){let{maxSize:r=1024,type:s="image/jpeg",quality:n=.92,source:i}=e,o=await vae(t);try{let a=DR(o.width,o.height,r),c=await _ae(o,a,s,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:s,width:c.width,height:c.height,source:i}}finally{o.close()}}function Eae(t){let e=t instanceof Error?t.name:"",r=t instanceof Error?t.message:String(t);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(r)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(r)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(r)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Cae(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function kae(t,e){let r=t.videoWidth,s=t.videoHeight;if(!(r>0)||!(s>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=DR(r,s,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let l=c.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(t,0,0,a.width,a.height);let u=await RH(c,i,o);return{bytes:new Uint8Array(await u.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Tae=new Set(["w","a","s","d"]),nf=(t,e)=>Math.min(e,Math.max(-e,t));function Aae(t={}){let{panPerPixel:e=9e-4,zoomPerSecond:r=.35,strafePerSecond:s=.18,decayTauMs:n=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=t,c=0,l=0,u=0,d=null,h=new Set;return{pointerDelta(f,m){c=nf(c-f*e,o),l=nf(l-m*e,o)},keyDown(f){let m=f.toLowerCase();Tae.has(m)&&h.add(m)},keyUp(f){h.delete(f.toLowerCase())},clearKeys(){h.clear()},frameArrived(){let f=1-i;c*=f,l*=f,u*=f},tick(f){if(d===null){d=f;return}let m=Math.max(0,Math.min(100,f-d))/1e3;d=f,h.has("w")&&(u=nf(u+r*m,a)),h.has("s")&&(u=nf(u-r*m,a)),h.has("a")&&(c=nf(c+s*m,o)),h.has("d")&&(c=nf(c-s*m,o));let w=Math.exp(-m*1e3/n);c*=w,l*=w,u*=w},transform(){return{translateX:c,translateY:l,scale:Math.exp(u)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(l)<f&&Math.abs(u)<f},reset(){c=0,l=0,u=0,h.clear()}}}g();y();var HH=require("@earendil-works/pi-ai"),of=require("fs"),VH=require("path");g();y();g();y();g();y();async function PH(t,e,r){if(t.synced===!0||typeof t.onSynced!="function")return;let s;await new Promise((n,i)=>{let o=t.onSynced(()=>{clearTimeout(s),n()});s=setTimeout(()=>{o(),i(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${r} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}g();y();g();y();var BH=require("module");var JNe=globalThis.require??(0,BH.createRequire)(B),Iae=["inflight","progress","responses","tokens"];function DH(t,e){if(t===null||typeof t!="object"||!(e in t))return!1;let r=Reflect.get(t,e);return r===null||typeof r!="object"||!("status"in r)?!1:r.status==="done"||r.status==="error"}function Av(t,e,r=6e4){t.delete(["requests",e]);let s=()=>{for(let a of Iae)t.delete([a,e])};if(DH(t.get("inflight"),e)){s();return}let n=()=>{},i=t.on("change",a=>{DH(a.inflight,e)&&(i(),n(),s())}),o=setTimeout(i,r);n=()=>clearTimeout(o),typeof o=="object"&&"unref"in o&&o.unref()}g();y();function LH(t,e,r,s){let n=t.response??{},i={request_id:r,consumer_id:s,stream:!0,kind:"chat",messages:e};return typeof n.instructions=="string"&&(i.instructions=n.instructions),Array.isArray(n.modalities)&&(i.modalities=n.modalities),typeof n.temperature=="number"&&(i.temperature=n.temperature),typeof n.max_output_tokens=="number"&&(i.max_output_tokens=n.max_output_tokens),n.tools!==void 0&&(i.tools=n.tools),i}function OH(t,e,r){let s={request_id:e,consumer_id:r,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(s.model=t.model),t.tools!==void 0&&(s.tools=t.tools),t.tool_choice!==void 0&&(s.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(s.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(s.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(s.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(s.stop=t.stop),typeof t.reasoning_effort=="string"&&(s.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(s.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(s.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(s.response_format=t.response_format),typeof t.voice=="string"&&(s.voice=t.voice),typeof t.language=="string"&&(s.language=t.language),s}g();y();g();y();function NH(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,r=e.body??{},s=r.error,n=s?.message??r.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:s?.type??"urun_error",code:e.code??s?.code??null,message:n}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Rae="llm-resp";async function*Pae(t,e){let r=`resp_${t}`,s=new Map;for await(let n of e){let i=n;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let o of i.tool_calls){let a=typeof o.index=="number"?o.index:0,c=s.get(a)??{};o.id&&(c.id=o.id),o.function?.name&&(c.name=o.function.name),s.set(a,c),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:c.id,name:c.name,delta:o.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield NH(i);return}}}async function*LR(t,e){let r=`${Rae}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Pae(e,t.stream(r).messages())}finally{try{Av(t.doc("llm"),e)}catch{}}}var Iv=class{constructor(e,r=15e3,s){this.session=e;this.docSyncTimeoutMs=r;this.sessionTag=s===void 0?e.sessionId??globalThis.crypto.randomUUID():s}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,r){return this.writeGated(r,()=>{let s=OH(e,r,this.consumerId);return this.write(s),LR(this.session,r)})}sendResponseCreate(e,r,s){return this.writeGated(s,()=>{let n=LH(e,r,s,this.consumerId);return this.write(n),LR(this.session,s)})}cancelTurn(e){try{Av(this.session.doc("llm"),e)}catch{}}async writeGated(e,r){try{await PH(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(s){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${s instanceof Error?s.message:String(s)}`)}return r()}};var UH=0;function Bae(){return UH+=1,`req_${Date.now().toString(36)}_${UH.toString(36)}`}var Rv=class{transport;constructor(e,r){this.transport=new Iv(e,void 0,r?.sessionTag)}responses={create:async e=>{let r=Bae(),s=await this.transport.sendResponses(e,r);return Object.assign((async function*(){yield*s})(),{requestId:r})}}};$v();g();y();g();y();var Uae=require("crypto");g();y();g();y();g();y();g();y();g();y();var OR="https://api.urun.sh/v1";async function MH(t){let e=t.fetchImpl??fetch,r=`${t.apiUrl.replace(/\/+$/,"")}/apps`,s=await e(r,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${r} \u2192 ${s.status}`);let n=await s.json();if(!Array.isArray(n.apps))throw new Error(`org apps listing returned no "apps" array (GET ${r})`);if(n.truncated===!0)throw new Error(`org apps listing was truncated (GET ${r} returned ${n.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return n.apps}async function jH(t){let e=await MH(t),r=e.filter(s=>s.function_name===t.fnName&&s.deployment_status==="active").map(s=>s.app_slug);if(r.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return r.sort()}var UR="urun-serve",Mae="serve",jae=131072,$ae=16384,$H=3,Fae=42e4,qae=6e4,FH=2,Hae=15e3;function Vae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||OR,fnName:(t.URUN_FUNCTION??"").trim()||Mae}}function WH(t){let e=(t.URUN_BASE_URL??"").trim(),r=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!r)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let s=(t.URUN_JWT??"").trim();if(s)return{baseUrl:e,orgId:r,auth:{lane:"jwt",jwt:s}};let n=(t.URUN_API_KEY??"").trim();if(!n)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let i=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:r,auth:{lane:"api-key",apiKey:n,gatewayUrl:i}}}function zH(t){let e=null;return r=>{e===null&&((0,of.mkdirSync)((0,VH.dirname)(t),{recursive:!0}),e=(0,of.openSync)(t,"a"));let s=r.detail?` ${JSON.stringify(r.detail)}`:"";(0,of.writeSync)(e,`${new Date().toISOString()} [${r.level}] [urun] ${r.message}${s}
|
|
178
|
+
`));let r=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of r)try{s()}catch{}try{try{this._lifecycleUnsub?.()}catch{}this._lifecycleUnsub=null;try{this._dialNegotiation?.dispose()}catch(n){S.error("[urun] session detach: dial negotiation dispose failed:",n)}this._dialNegotiation=null;try{this._activity?.dispose()}catch{}this._activity=null;try{this._presenceDetachNow()}catch{}try{this._presenceTracker?.dispose()}catch{}this._presenceTracker=null;try{this._activation.dispose()}catch{}try{this._generationTickStop?.()}catch{}this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let s=Array.from(this._activeRequests);this._activeRequests.clear();for(let n of s)try{n(new ev)}catch{}this._gateOff=!0,clearTimeout(this._gateTimer??void 0),this._gateTimer=null;for(let n of this._gateDocUnsubs.splice(0))n();for(let[n,i]of this._docs)try{i.dispose()}catch(o){S.error(`[urun] session detach: doc '${n}' dispose failed:`,o)}this._docs.clear();for(let[n,i]of this._streams)try{i.dispose()}catch(o){S.error(`[urun] session detach: stream '${n}' dispose failed:`,o)}this._streams.clear()}finally{this._transport.disconnect(e)}}},zoe={failed:!0,rejected:!0,expired:!0,cancelled:!0,canceled:!0,closed:!0},Koe={idle:!0,queued:!0,provisioning:!0,waiting_for_capacity:!0,unavailable:!0,connecting:!0};function Goe(t){return Koe[t]===!0}function Xoe(t){let e=t.fetchImpl??globalThis.fetch,r=t.baseUrl.replace(/\/+$/,""),s=null,n=!1,i=!1,o=0,a=t.transport.on("phase",h);function c(){i||(i=!0,a(),d())}function l(){o+=1,o>=15&&c()}async function u(){if(!n){n=!0;try{let f=await t.jwt?.(),m=await e(`${r}/api/session-requests/${encodeURIComponent(t.requestId)}?wait_s=15`,{...f?{headers:{authorization:`Bearer ${f}`}}:{},signal:Yoe(20*1e3)});if(m.status===404||m.status===410){c();return}if(m.ok){let w=await m.json().catch(()=>{}),p=typeof w?.status=="string"?w.status:void 0;if(p!==void 0&&zoe[p]===!0){c();return}o=0;return}l()}catch{l()}finally{n=!1}}}function d(){s!==null&&(clearInterval(s),s=null)}function h(){if(Goe(t.transport.phase.name)){s===null&&(s=setInterval(()=>{u()},2e4),s.unref?.());return}d()}return h(),c}function Yoe(t){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(t):void 0}function Joe(t){return`urun:session:v2:${t.orgId}:${t.app}:${t.functionName}`}function CR(){try{return globalThis.sessionStorage??null}catch{return null}}var kR=new Map;function qI(t){if(!t)return;let e=t.split(".");if(!(e.length<2))try{let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=JSON.parse(atob(r+"=".repeat((4-r.length%4)%4)));return typeof s?.sub=="string"&&s.sub.length>0?s.sub:void 0}catch{return}}function Qoe(t,e){return t!==void 0&&e!==void 0&&t!==e}function zq(t,e){let r=CR(),s=null;if(r)try{let i=r.getItem(t);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(s={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{s=null}let n=kR.get(t)??s??null;return!n||Qoe(n.actor,e)?null:n}function Zoe(t,e){let r={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};kR.set(t,r);let s=CR();if(s)try{s.setItem(t,JSON.stringify(r))}catch{}}function jI(t){kR.delete(t);let e=CR();if(e)try{e.removeItem(t)}catch{}}var Kq=new Set(["paused","acquiring","live"]),eae=new Set(["24h","keep"]);function Gq(t){if(typeof t!="string"||t.length===0)return null;let e=new Date(t);return Number.isFinite(e.getTime())?e:null}function tae(t){if(typeof t?.id!="string"||t.id.length===0)throw new Gi("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof t.state!="string"||!Kq.has(t.state))throw new Gi(`[urun] session ${t.id} reported an unrecognized state ${JSON.stringify(t.state)} \u2014 this @urun-sh/core build knows only ${[...Kq].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof t.recordings_expired=="boolean"?e=t.recordings_expired:S.warn(`[urun] session ${t.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:t.id,label:typeof t.label=="string"&&t.label.length>0?t.label:null,state:t.state,app:typeof t.app=="string"?t.app:"",functionName:typeof t.function=="string"?t.function:"",createdAt:Gq(t.created_at),lastActiveAt:Gq(t.last_active_at),archived:t.archived===!0,preview:typeof t.preview=="string"&&t.preview.length>0?t.preview:null,recordingsExpired:e,retention:eae.has(t.retention)?t.retention:(t.retention!==void 0&&S.warn(`[urun] session ${t.id} reported an unrecognized retention ${JSON.stringify(t.retention)} \u2014 defaulting to '24h'`),"24h")}}var TR=class{_request;_app;constructor(t,e){this._app=t,this._request=e}async list(t={}){let{rows:e,nextCursor:r}=await cq({...this._request,app:t.app??this._app,functionName:t.functionName,includeArchived:t.includeArchived,limit:t.limit,cursor:t.cursor});return{sessions:e.map(tae),nextCursor:r}}async end(t){await lq({...this._request,sessionId:t})}async archive(t){await pI({...this._request,sessionId:t,archived:!0})}async unarchive(t){await pI({...this._request,sessionId:t,archived:!1})}async setName(t,e,r={}){await dq({...this._request,sessionId:t,name:e,source:r.source})}};function Xq(t,e,r){let s=qI(r);Zoe(t,s!==void 0?{sessionId:e,actor:s}:{sessionId:e})}var rae=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function pH(t,e){return new TR(t,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function mH(t,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(r,s){if(!(rae.has(s)||typeof s!="string"))return(n,i)=>{let o=n??{},a=Joe({orgId:e.orgId,app:t,functionName:s}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,l,u=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,d=u(),h=e.jwt,f=e.getAccessToken?async I=>{let U=await e.getAccessToken(I);return U&&(h=U),U}:void 0,m={...e,getAccessToken:f},w=new Y1,p=new uv({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:d,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new ER(d,w,p,hH(m),$I(m),{activity:i?.activity,presenceIdleMs:i?.presenceIdleMs}),v,E=!1,O,W=!1,P,A,C=new Promise(I=>{A=I}),R,j=I=>{I.sessionId||P||(P="teardown",R="ticket",Ag({baseUrl:I.baseUrl,requestId:I.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider}))},X=I=>{P||I.sessionId||(P="abandon",Ag({baseUrl:I.baseUrl,requestId:I.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider,reason:"client_abandoned"}))},J=I=>{let U=I.sessionId||!l?I:{...I,sessionId:l};v=U,A({status:"ready",handle:U}),(W||P==="teardown")&&j(U)};b.setNamedSessionIdProbe(()=>v?.sessionId),b.setEndHandler(async()=>{let I=v?{status:"ready",handle:v}:await C;if(I.status==="unavailable")throw new Td("[urun] session allocation failed before a releasable request was created",{cause:I.cause});let U=v??I.handle;return jI(a),P==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(P="end",U.sessionId?hI({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):uI({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let I=v?{status:"ready",handle:v}:await C;if(I.status==="unavailable")throw new Td("[urun] session allocation failed before a cancellable request was created",{cause:I.cause});let U=v??I.handle;if(U.sessionId)throw new Sn(`[urun] cancel() is for a queued admission request, but this call already has session ${U.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:U.sessionId,code:"cancel_on_live_session"});P="end";try{let G=await uI({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return jI(a),G}catch(G){throw P==="end"&&(P=void 0),G}});let V=async I=>{let U,G=i?.sessionId??e.sessionKey??l,$,q;if(G===void 0&&!c){let ot=zq(a);if(ot?.sessionId){if(q=qI(h),ot.actor!==void 0&&q===void 0&&f){let ht=await Promise.resolve(f()).catch(()=>{});q=qI(ht??e.jwt)}$=ot.actor!==void 0&&q!==void 0&&ot.actor!==q?void 0:ot.sessionId}}let ne=G??$,le=(ot,ht)=>fI({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:t,functionName:s,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,...e.shape?{shape:e.shape}:{},idempotencyKey:ot,sessionKey:ht,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:gt=>{p.reportAdmission(gt),gt.sessionId&&!l&&(l=gt.sessionId,U=gt.sessionId,v&&v.sessionId!==gt.sessionId&&J({...v,sessionId:gt.sessionId}),E||(e.sessionKey||Xq(a,gt.sessionId,h),b.setSessionId(gt.sessionId)))},onRequest:J}),Ce;try{Ce=await le(I,ne)}catch(ot){let ht=ot instanceof Ut&&ot.code==="session_name_not_yours"&&ne!==void 0&&ne===l&&i?.sessionId===void 0&&e.sessionKey===void 0;if($===void 0&&!ht||!(ot instanceof Ut)||ot.code!=="session_name_not_yours")throw ot;let gt=$??ne;if(gt===void 0)throw ot;S.warn(`[urun] session_name_not_yours: the control plane refused session ${gt} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),ht&&(l=void 0),zq(a,q)?.sessionId===gt&&jI(a),Ce=await le(u(),void 0)}let nt=f?await f()??void 0:e.jwt;if(U&&U!==Ce.sessionId)throw v&&v.sessionId!==Ce.sessionId&&J({...v,sessionId:Ce.sessionId}),new Ut(`Gateway contract violation: admission minted session ${U} but allocation completed as ${Ce.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=Ce.sessionId,v&&v.sessionId!==Ce.sessionId&&J({...v,sessionId:Ce.sessionId}),E||(e.sessionKey||Xq(a,Ce.sessionId,h),b.setSessionId(Ce.sessionId),D=iv(Ce.baseUrl)?{baseUrl:Ce.baseUrl,sessionId:Ce.sessionId}:null,b.setArtifactsAuth($I({...m,baseUrl:Ce.baseUrl})),p.setEndsAt(Ce.endsAt),p.seedRegion(gI(Ce.response))),{url:Ce.wsUrl,sessionId:Ce.sessionId,jwt:nt,iceServers:Ce.response.ice_servers,endsAt:Ce.endsAt,sfuAttach:Ce.sfuAttach}},H,Y,D=null,Q=f?I=>!I?.redial&&H?H:Promise.resolve(f(I?.redial?{forceRefresh:!0,reason:"background"}:void 0)).then(U=>H=U??H):()=>H,re=()=>{let I=p.connectedUrl;return I?hv(I):void 0};if(p.setConnectionResolver(async()=>{let I=await V(u());return H=I.jwt,Y=I.sfuAttach,I}),p.setConnectionViewRefresher(async()=>D?aq({baseUrl:D.baseUrl,sessionId:D.sessionId,jwt:h}):null),p.on("connected",()=>{p.multiplexer&&w.setTarget(p.multiplexer);let I=p.connectedUrl;I&&b.setDocTransport({wsUrl:I,token:Q,attach:Y,resolveServerUrl:re})}),(async I=>{let U;try{U=await V(I)}catch(q){if(E){A({status:"unavailable",cause:q});return}S.error(`[urun] Failed to create session for ${s}:`,q),v&&X(v);let ne=q instanceof Error?q:new Error(String(q)),le=q instanceof Ut?q.httpStatus:void 0,Ce=q instanceof Ut?q.code:void 0,nt=q instanceof Ut?q.retryAfterSeconds:void 0;p.reportAllocationFailure(ne,le,Ce,nt),A({status:"unavailable",cause:q});return}if(E)return;let G=D!==null?null:e.baseUrl,$=v?.requestId;G!==null&&$!==void 0&&!E&&(O=Xoe({requestId:$,baseUrl:G,jwt:async()=>f?await f()??h:h,transport:p})),p.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers,sfuAttach:U.sfuAttach}),Ad()&&await Cg(),H=U.jwt,Y=U.sfuAttach,b.setDocTransport({wsUrl:U.url,token:Q,attach:Y,resolveServerUrl:re}),await p.connect({app:t,functionName:s,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback})})(d).catch(I=>{S.error(`[urun] Failed to connect session for ${s}:`,I)}),e.releaseOnLeave!==!1){let I=aR(()=>{if(E=!0,O?.(),O=void 0,p.leaveLeg())return;if(p.connectedUrl!==null){p.disconnect();return}p.disconnect();let ne=v;ne?j(ne):W=!0});b.onDisconnect(I);let U,G,$=!1,q=()=>{$||($=!0,U?.(),G?.())};C.then(ne=>{ne.status!=="ready"||$||(U=cR(()=>v!==void 0))}),G=b.onPhase(ne=>{let le=ne?.name;(le==="paused"||le==="error")&&q()}),$&&G(),b.onDisconnect(q)}return b}}})}var RNe=globalThis.require??(0,SH.createRequire)(B),EH="https://api.urun.sh",CH="URUN_DEV";function sae(){if(typeof process>"u")return!1;let t=process.env?.[CH];if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"}var Ug=class extends Error{status;code;constructor(t,e,r){super(t),this.name="ClientTokenError",this.status=e,this.code=r}};async function nae(t,e={}){if(!t)throw new Ug("[urun] createClientToken requires an org API key");let r=e.fetch??globalThis.fetch,s=cr(e.baseUrl??EH),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),e.bindPrincipal&&(n.bind_principal=!0),(e.dev??sae())&&(n.dev=!0);let i;try{i=await r(`${s}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(w){throw new Ug(`[urun] client token mint request failed: ${w instanceof Error?w.message:String(w)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let w=typeof o.message=="string"?o.message:`HTTP ${i.status}`,p=typeof o.error_code=="string"?o.error_code:void 0;throw new Ug(`[urun] client token mint failed: ${w}`,i.status,p)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,u=typeof o.expires_in=="number"?o.expires_in:void 0,d=typeof o.billing_audience=="string"?o.billing_audience:void 0,h=typeof o.credits_admission_ok=="boolean"?o.credits_admission_ok:void 0,f=typeof o.credits_refusal_reason=="string"?o.credits_refusal_reason:void 0;if(!a)throw new Ug("[urun] client token mint returned no token (control-plane contract violation)",i.status);let m=Number.isFinite(l)?new Date(l):new Date(Date.now()+(u??60)*1e3);return{token:a,expiresAt:m,orgId:c,...d!==void 0?{billingAudience:d}:{},...h!==void 0?{creditsAdmissionOk:h}:{},...f!==void 0?{creditsRefusalReason:f}:{}}}var gH=3e4,yH="stream:",iae=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(t,e){this._ws=t,this._multiplexer=e,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let n=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(n.timer),s.error?n.reject(new Error(s.error)):n.resolve(s.result)}})}async get(t){return this._sendRpc("store.get",{key:t})}async has(t){return await this._sendRpc("store.has",{key:t})}on(t,e){let r=`${yH}${t}`;return this._multiplexer.on(r,s=>{e(s)})}emit(t,e){let r=`${yH}${t}`,s=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{data:e};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(t,e){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let n=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(n)&&(this._pendingRpc.delete(n),s(new Error(`RPC request "${t}" timed out after ${gH}ms`)))},gH);this._pendingRpc.set(n,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:n,type:t,...e}))})}};function oae(t){let e=`${t.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(t.orgId)}`,r=new WebSocket(e);(t.jwt||t.apiKey)&&r.addEventListener("open",()=>{r.send(JSON.stringify({type:"auth",orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,apiKey:t.apiKey}))});let s=new X1(r);return new iae(r,s)}var aae='video/mp4; codecs="avc1.42E01E"';function cae(t,e){let r=e?.codec??aae,s=document.createElement("video");s.muted=!0,s.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);s.src=i,n.addEventListener("sourceopen",()=>{let h;try{h=n.addSourceBuffer(r)}catch(p){throw p instanceof DOMException&&p.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):p}let f=t.getReader();function m(){return h.updating?new Promise(p=>{h.addEventListener("updateend",()=>p(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:p,value:b}=await f.read();if(p){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{h.appendBuffer(b)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let E=h.buffered;if(E.length>0){let O=E.start(E.length-1);h.remove(0,O),await m(),h.appendBuffer(b)}else throw v}else throw v}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}w()}),s.play().catch(()=>{});let o=s,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(s),l=c.getTracks(),u=0,d=l.length;if(d===0)s.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let h of l)h.addEventListener("ended",()=>{u++,u>=d&&URL.revokeObjectURL(i)});return c}function lae(t){return t.status.startsWith("pending_")}var Tv=class extends Error{status;code;constructor(t,e){super(t),this.name="CreditsError",this.status=e.status,this.code=e.code,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},PR=class extends Tv{constructor(t="[urun] credits: unauthorized",e="unauthorized"){super(t,{status:401,code:e}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function dae(t,e,r){let s=r||e||`HTTP ${t}`;return t===401?new PR(s,e??"unauthorized"):new Tv(s,{status:t,code:e??`http_${t}`})}var kH=class{constructor(t){this._options=t,this._base=`${t.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let t=await this._request("GET","/balance");if(!t||typeof t!="object"||typeof t.org_id!="string")throw new Tv("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return t}async getLedger(t={}){let e=(await this._request("GET","/ledger",{params:t.limit!==void 0?{limit:String(t.limit)}:void 0})).entries;return Array.isArray(e)?e:[]}async _request(t,e,r={}){let s=this._buildUrl(e,r.params),n=await this._resolveToken(),i=await this._fetch(s,t,n);if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await this._fetch(s,t,n))}if(!i.ok){let{code:o,message:a}=await this._readError(i);throw dae(i.status,o,a)}return this._readJson(i)}_buildUrl(t,e){let r=`${this._base}${t}`,s=Object.entries(e??{}).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(t,e,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(t,{method:e,headers:s})}async _resolveToken(){if(this._options.getAccessToken){let e=await this._options.getAccessToken();if(e)return e}let t=this._options.jwt??this._options.apiKey;if(!t)throw new PR("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return t}async _readJson(t){try{return await t.json()}catch{return{}}}async _readError(t){try{let e=(await t.json()).error;if(e&&typeof e=="object"){let{code:r,message:s}=e;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${t.status}`}}}catch{}return{message:`HTTP ${t.status}`}}};function uae(t){return new kH(t)}var TH=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function bH(t){let e=[];return t.audio&&e.push("audio"),t.video&&e.push("video"),e.join("+")}function xH(t,e){return e==="audio"?t.getAudioTracks():t.getVideoTracks()}function wH(t,e){let r=t.getTracks();if(r.length===1&&r[0]===e)return t;try{return new MediaStream([e])}catch{return t}}function AR(t,e){for(let r of[...t.lostListeners])try{r(e)}catch{}}var AH=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(t){this.injectedGetUserMedia=t?.getUserMedia}claim(t,e){return this.enqueue(async()=>{let r=this.claims.get(t);r&&(this.claims.delete(t),r.released=!0,r.track=null,r.stream=null,AR(r,new Error(`${t} capture claim superseded by a newer claim`)));let s=this.createState(t,e);return this.claims.set(t,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(t){let e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!t?.getUserMedia)throw new TH;return e=>t.getUserMedia(e)}async converge(t){let e=[];for(let o of this.claims.values())o!==t&&o.track&&e.push(o);if(e.length>0)try{let o=await this.resolveGetUserMedia()({[t.kind]:t.constraints}),a=xH(o,t.kind)[0]??null;if(a){t.track=a,t.stream=wH(o,a);return}}catch{}for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let r=this.resolveGetUserMedia(),s={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await r(s)}catch(o){let a=`one-capture getUserMedia(${bH(s)}) failed`,c=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==t){let u=new Error(`${a} \u2014 ${l.kind} capture lost: ${c||o}`);u.cause=o,AR(l,u)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===t?1:a===t?-1:0);for(let o of i){let a=xH(n,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${bH(s)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===t)throw c;AR(o,c);continue}if(o.track=a,o.stream=wH(n,a),o!==t)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(t,e){let r=this,s={kind:t,constraints:e,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:t,get track(){return s.track},get stream(){return s.stream},update(n){return r.enqueue(async()=>{if(s.released)throw new Error(`${t} capture claim already released`);if(s.constraints=n,await r.converge(s),!s.track)throw new Error(`${t} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(t)===s&&r.claims.delete(t),s.track?.stop(),s.track=null,s.stream=null)},onTrack(n){return s.trackListeners.add(n),()=>s.trackListeners.delete(n)},onLost(n){return s.lostListeners.add(n),()=>s.lostListeners.delete(n)}}};return s}},hae=null;function fae(){return hae??=new AH}var IH="input",pae=30;function mae(t){let e=t.now??Date.now,r=t.field??IH,s=1e3/Math.max(t.hz??30,.001),n=new Set,i=0,o=0,a=0,c=0,l,u=null,d=!1,h=()=>{if(d)return;l=e(),c+=1;let m={keys:[...n],buttons:i,pointer:{x:o,y:a},seq:c,at:l};try{t.awareness.setLocalStateField(r,m)}catch{}},f=()=>{if(d)return;let m=e();if(l===void 0||m-l>=s){u&&(clearTimeout(u),u=null),h();return}if(u)return;let w=Math.max(s-(m-l),0);u=setTimeout(()=>{u=null,h()},w),u.unref?.()};return{keyDown(m){let w=String(m).toLowerCase();n.has(w)||(n.add(w),f())},keyUp(m){let w=String(m).toLowerCase();n.delete(w)&&f()},setButtons(m){let w=Number.isFinite(m)?Number(m):0;w!==i&&(i=w,f())},movePointer(m,w){let p=Number.isFinite(m)?Number(m):0,b=Number.isFinite(w)?Number(w):0;p===0&&b===0||(o+=p,a+=b,f())},heldKeys(){return[...n]},clear(){d||(n.clear(),i=0,u&&(clearTimeout(u),u=null),h())},dispose(){if(d)return;let m=n.size>0||i!==0;n.clear(),i=0,u&&(clearTimeout(u),u=null),m&&h(),d=!0}}}var gae=1024,yae=.92,bae=262144,xae=256e3,IR=[.9,.8,.7,.6,.5],vH=.8,wae=8;function DR(t,e,r){if(!(t>0)||!(e>0))throw new Error(`reference image has no pixels (${t}x${e})`);let s=Math.min(1,r/Math.max(t,e));return{width:Math.max(1,Math.round(t*s)),height:Math.max(1,Math.round(e*s))}}async function vae(t){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(t,{imageOrientation:"from-image"})}async function RH(t,e,r){let s=await new Promise(n=>{t.toBlob(n,e,e==="image/jpeg"?r:void 0)});if(!s)throw new Error(`could not encode the reference image as ${e}`);return s}function _H(t,e){S.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${t} -> ${e} bytes`)}async function RR(t,e,r,s,n){let i=document.createElement("canvas");i.width=e,i.height=r;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return s==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,r)),o.drawImage(t,0,0,e,r),await RH(i,s,n)}async function _ae(t,e,r,s){let{width:n,height:i}=e,o=await RR(t,n,i,r,s);if(o.size<=256e3)return{blob:o,width:n,height:i};if(r==="image/jpeg"){for(let c of IR)if(!(c>=s)&&(o=await RR(t,n,i,r,c),o.size<=256e3))return _H(`quality ${s} -> ${c}`,o.size),{blob:o,width:n,height:i}}let a=r==="image/jpeg"?IR[IR.length-1]:s;for(let c=0;c<wae;c++)if(n=Math.max(16,Math.round(n*vH)),i=Math.max(16,Math.round(i*vH)),o=await RR(t,n,i,r,a),o.size<=256e3)return _H(`downscaled to ${n}x${i} @ q${a}`,o.size),{blob:o,width:n,height:i};throw new Error(`this image cannot be sent: even at ${n}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Sae(t,e){let{maxSize:r=1024,type:s="image/jpeg",quality:n=.92,source:i}=e,o=await vae(t);try{let a=DR(o.width,o.height,r),c=await _ae(o,a,s,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:s,width:c.width,height:c.height,source:i}}finally{o.close()}}function Eae(t){let e=t instanceof Error?t.name:"",r=t instanceof Error?t.message:String(t);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(r)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(r)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(r)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Cae(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function kae(t,e){let r=t.videoWidth,s=t.videoHeight;if(!(r>0)||!(s>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=DR(r,s,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let l=c.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(t,0,0,a.width,a.height);let u=await RH(c,i,o);return{bytes:new Uint8Array(await u.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Tae=new Set(["w","a","s","d"]),nf=(t,e)=>Math.min(e,Math.max(-e,t));function Aae(t={}){let{panPerPixel:e=9e-4,zoomPerSecond:r=.35,strafePerSecond:s=.18,decayTauMs:n=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=t,c=0,l=0,u=0,d=null,h=new Set;return{pointerDelta(f,m){c=nf(c-f*e,o),l=nf(l-m*e,o)},keyDown(f){let m=f.toLowerCase();Tae.has(m)&&h.add(m)},keyUp(f){h.delete(f.toLowerCase())},clearKeys(){h.clear()},frameArrived(){let f=1-i;c*=f,l*=f,u*=f},tick(f){if(d===null){d=f;return}let m=Math.max(0,Math.min(100,f-d))/1e3;d=f,h.has("w")&&(u=nf(u+r*m,a)),h.has("s")&&(u=nf(u-r*m,a)),h.has("a")&&(c=nf(c+s*m,o)),h.has("d")&&(c=nf(c-s*m,o));let w=Math.exp(-m*1e3/n);c*=w,l*=w,u*=w},transform(){return{translateX:c,translateY:l,scale:Math.exp(u)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(l)<f&&Math.abs(u)<f},reset(){c=0,l=0,u=0,h.clear()}}}g();y();var HH=require("@earendil-works/pi-ai"),of=require("fs"),VH=require("path");g();y();g();y();g();y();async function PH(t,e,r){if(t.synced===!0||typeof t.onSynced!="function")return;let s;await new Promise((n,i)=>{let o=t.onSynced(()=>{clearTimeout(s),n()});s=setTimeout(()=>{o(),i(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${r} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}g();y();g();y();var BH=require("module");var JNe=globalThis.require??(0,BH.createRequire)(B),Iae=["inflight","progress","responses","tokens"];function DH(t,e){if(t===null||typeof t!="object"||!(e in t))return!1;let r=Reflect.get(t,e);return r===null||typeof r!="object"||!("status"in r)?!1:r.status==="done"||r.status==="error"}function Av(t,e,r=6e4){t.delete(["requests",e]);let s=()=>{for(let a of Iae)t.delete([a,e])};if(DH(t.get("inflight"),e)){s();return}let n=()=>{},i=t.on("change",a=>{DH(a.inflight,e)&&(i(),n(),s())}),o=setTimeout(i,r);n=()=>clearTimeout(o),typeof o=="object"&&"unref"in o&&o.unref()}g();y();function LH(t,e,r,s){let n=t.response??{},i={request_id:r,consumer_id:s,stream:!0,kind:"chat",messages:e};return typeof n.instructions=="string"&&(i.instructions=n.instructions),typeof n.model=="string"&&n.model&&(i.model=n.model),Array.isArray(n.modalities)&&(i.modalities=n.modalities),typeof n.temperature=="number"&&(i.temperature=n.temperature),typeof n.max_output_tokens=="number"&&(i.max_output_tokens=n.max_output_tokens),n.tools!==void 0&&(i.tools=n.tools),i}function OH(t,e,r){let s={request_id:e,consumer_id:r,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(s.model=t.model),t.tools!==void 0&&(s.tools=t.tools),t.tool_choice!==void 0&&(s.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(s.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(s.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(s.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(s.stop=t.stop),typeof t.reasoning_effort=="string"&&(s.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(s.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(s.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(s.response_format=t.response_format),typeof t.voice=="string"&&(s.voice=t.voice),typeof t.language=="string"&&(s.language=t.language),s}g();y();g();y();function NH(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,r=e.body??{},s=r.error,n=s?.message??r.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:s?.type??"urun_error",code:e.code??s?.code??null,message:n}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var Rae="llm-resp";async function*Pae(t,e){let r=`resp_${t}`,s=new Map;for await(let n of e){let i=n;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let o of i.tool_calls){let a=typeof o.index=="number"?o.index:0,c=s.get(a)??{};o.id&&(c.id=o.id),o.function?.name&&(c.name=o.function.name),s.set(a,c),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:c.id,name:c.name,delta:o.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield NH(i);return}}}async function*LR(t,e){let r=`${Rae}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Pae(e,t.stream(r).messages())}finally{try{Av(t.doc("llm"),e)}catch{}}}var Iv=class{constructor(e,r=15e3,s){this.session=e;this.docSyncTimeoutMs=r;this.sessionTag=s===void 0?e.sessionId??globalThis.crypto.randomUUID():s}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,r){return this.writeGated(r,()=>{let s=OH(e,r,this.consumerId);return this.write(s),LR(this.session,r)})}sendResponseCreate(e,r,s){return this.writeGated(s,()=>{let n=LH(e,r,s,this.consumerId);return this.write(n),LR(this.session,s)})}cancelTurn(e){try{Av(this.session.doc("llm"),e)}catch{}}async writeGated(e,r){try{await PH(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(s){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${s instanceof Error?s.message:String(s)}`)}return r()}};var UH=0;function Bae(){return UH+=1,`req_${Date.now().toString(36)}_${UH.toString(36)}`}var Rv=class{transport;constructor(e,r){this.transport=new Iv(e,void 0,r?.sessionTag)}responses={create:async e=>{let r=Bae(),s=await this.transport.sendResponses(e,r);return Object.assign((async function*(){yield*s})(),{requestId:r})}}};$v();g();y();g();y();var Uae=require("crypto");g();y();g();y();g();y();g();y();g();y();var OR="https://api.urun.sh/v1";async function MH(t){let e=t.fetchImpl??fetch,r=`${t.apiUrl.replace(/\/+$/,"")}/apps`,s=await e(r,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${r} \u2192 ${s.status}`);let n=await s.json();if(!Array.isArray(n.apps))throw new Error(`org apps listing returned no "apps" array (GET ${r})`);if(n.truncated===!0)throw new Error(`org apps listing was truncated (GET ${r} returned ${n.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return n.apps}async function jH(t){let e=await MH(t),r=e.filter(s=>s.function_name===t.fnName&&s.deployment_status==="active").map(s=>s.app_slug);if(r.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return r.sort()}var UR="urun-serve",Mae="serve",jae=131072,$ae=16384,$H=3,Fae=42e4,qae=6e4,FH=2,Hae=15e3;function Vae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||OR,fnName:(t.URUN_FUNCTION??"").trim()||Mae}}function WH(t){let e=(t.URUN_BASE_URL??"").trim(),r=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!r)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let s=(t.URUN_JWT??"").trim();if(s)return{baseUrl:e,orgId:r,auth:{lane:"jwt",jwt:s}};let n=(t.URUN_API_KEY??"").trim();if(!n)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let i=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:r,auth:{lane:"api-key",apiKey:n,gatewayUrl:i}}}function zH(t){let e=null;return r=>{e===null&&((0,of.mkdirSync)((0,VH.dirname)(t),{recursive:!0}),e=(0,of.openSync)(t,"a"));let s=r.detail?` ${JSON.stringify(r.detail)}`:"";(0,of.writeSync)(e,`${new Date().toISOString()} [${r.level}] [urun] ${r.message}${s}
|
|
179
179
|
`)}}function Bv(t){let e=zH(Vg());return async(r,s,n)=>{let{baseUrl:i,orgId:o,auth:a}=WH(r),{App:c,createClientToken:l}=await t(),d=(a.lane==="jwt"?c(s,{baseUrl:i,orgId:o,jwt:a.jwt,diagnosticSink:e}):c(s,{baseUrl:i,orgId:o,diagnosticSink:e,getAccessToken:async()=>(await l(a.apiKey,{baseUrl:a.gatewayUrl,expiresIn:300,allowedFunctions:[`${s}/${n}`]})).token}))[n];if(typeof d!="function")throw new Error(`urun pi extension: app "${s}" has no function "${n}"`);let h=d();if(typeof h.end!="function")throw new Error(`urun pi extension: app "${s}" function "${n}" returned a session without end()`);let f=h.connect;return typeof f=="function"&&await f.call(h),h}}var Wae=Bv(async()=>{let{createRequire:t}=await import("module"),e=t(B);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function zae(t,e){try{return Promise.resolve(t.end()).then(()=>{},r=>e(r))}catch(r){return e(r),Promise.resolve()}}function Kae(t){if(t?.hasUI===!1)return!0;if(t?.hasUI===!0)return!1;let e=process.argv.slice(2);if(e.includes("-p")||e.includes("--print"))return!0;let r=e.indexOf("--mode");return r!==-1&&(e[r+1]==="json"||e[r+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function KH(t,e){return`uRun: releasing the pooled "${t}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${e instanceof Error?e.message:String(e)}`}var Pv=class{constructor(e,r,s,n=(i,o)=>S.warn(KH(i,o))){this.open=e;this.env=r;this.fnName=s;this.onReleaseError=n}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(e){let r=this.pool.get(e);if(!r){let s=Promise.resolve(this.open(this.env,e,this.fnName)).then(n=>({session:n,responses:new Rv(n)}));r=s,this.pool.set(e,s),s.catch(()=>{this.pool.get(e)===s&&this.pool.delete(e)})}return r}evict(e){let r=this.pool.get(e);if(!r)return Promise.resolve();this.pool.delete(e);let s=r.then(n=>zae(n.session,i=>this.onReleaseError(e,i)),()=>{});return this.releasing.add(s),s.then(()=>this.releasing.delete(s)),s}closeAll(){let e=[...this.pool.keys()].map(r=>this.evict(r));return Promise.all([...e,...this.releasing]).then(()=>{})}};function GH(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let r of t.messages){if(r.role==="toolResult"){e.push({type:"function_call_output",call_id:r.toolCallId,output:Xae(r.content)});continue}if(r.role==="assistant"&&Array.isArray(r.content)){let n="",i=()=>{n&&(e.push({role:"assistant",content:n}),n="")};for(let o of r.content)if(o.type==="text")n+=String(o.text??"");else if(o.type==="toolCall")i(),e.push({type:"function_call",call_id:String(o.id??""),name:String(o.name??""),arguments:JSON.stringify(o.arguments??{})});else{if(o.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(o.type)}"`)}i();continue}let s=r.role==="assistant"?"assistant":"user";e.push({role:s,content:Gae(r.content)})}return XH(e)}function XH(t){let e=[];for(let r of t){let s=e[e.length-1];s&&"role"in s&&"role"in r&&s.role===r.role?s.content=[s.content,r.content].filter(n=>n.length>0).join(`
|
|
180
180
|
|
|
181
181
|
`):e.push({...r})}return e}function Gae(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e?String(e.text):"").join(""):""}function Xae(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e="";for(let r of t){let s=String(r.type??"");if(s!=="text")throw new Error(`urun pi extension: unsupported toolResult content part "${s}" \u2014 the serve lane carries text tool results only`);e+=String(r.text??"")}return e}function Yae(t){if(!(!Array.isArray(t)||t.length===0))return t.map(e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))}function qH(t,e){if(!e.trim())return{};try{return JSON.parse(e)}catch{throw new Error(`uRun serve error: tool call "${t}" arguments are not valid JSON: ${e}`)}}function Jae(t){let e=t?.output;return Array.isArray(e)?e.filter(r=>r.type==="function_call"):[]}function YH(t,e){let r=e?.usage;if(!r||typeof r!="object")return;let s=typeof r.input_tokens=="number"?r.input_tokens:void 0,n=typeof r.output_tokens=="number"?r.output_tokens:void 0;s===void 0||n===void 0||(t.input=s,t.output=n,t.totalTokens=typeof r.total_tokens=="number"?r.total_tokens:s+n)}function Qae(t){let e=t?.output;if(!Array.isArray(e))return"";let r="";for(let s of e)if(!(s.type!=="reasoning"||!Array.isArray(s.content)))for(let n of s.content)n.type==="reasoning_text"&&(r+=String(n.text??""));return r}var Zae=["<tool_call>","<function="];function ece(t,e){let r=Zae.find(s=>e.includes(s));if(r)return new Error(`serving row emitted a prose tool call (literal ${JSON.stringify(r)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`)}var Dv=class extends Error{};function tce(t){let e=t instanceof Error?t.message:String(t),r=t?.code;return/\b529\b/.test(e)||/overloaded/i.test(e)||r===529||r==="529"}function rce(t){return new Promise(e=>setTimeout(e,t))}function sce(t,e,r,s){return new Promise((n,i)=>{let o=!1,a=u=>{o||(o=!0,clearTimeout(c),s?.removeEventListener("abort",l),u())},c=setTimeout(()=>a(()=>i(r())),e),l=()=>a(()=>i(new Error("aborted")));if(s?.aborted){l();return}s?.addEventListener("abort",l,{once:!0}),Promise.resolve(t).then(u=>a(()=>n(u)),u=>a(()=>i(u)))})}async function*nce(t,e){let r=t[Symbol.asyncIterator](),s,n=new Promise((i,o)=>{s=()=>o(new Error("aborted")),e.addEventListener("abort",s,{once:!0})});try{for(;;){if(e.aborted)throw new Error("aborted");let i=await Promise.race([r.next(),n]);if(i.done)return;yield i.value}}finally{s&&e.removeEventListener("abort",s),r.return?.(void 0)}}function NR(t,e){if(t?.hasUI===!1){jv(`${e}
|
package/dist/pooler/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as Ce}from"../chunk-LM4E5YM2.js";import{a as te,b as ne,c as se,d as re}from"../chunk-
|
|
2
|
+
import{a as Ce}from"../chunk-LM4E5YM2.js";import{a as te,b as ne,c as se,d as re}from"../chunk-7OUSAG7O.js";import{a as X}from"../chunk-XGAF2NDT.js";import{c as W,v as N,w as z}from"../chunk-H4KFMIEV.js";import{a as Q,b as Z,d as ee}from"../chunk-XNRPTMSL.js";import{a as J}from"../chunk-7KRHHEKZ.js";import{j as q}from"../chunk-C452ZIU5.js";import{b as Ge,c as p}from"../chunk-YSFSRI3D.js";p();var mn=Ge(Ce(),1);import R from"process";import{Redis as kt}from"ioredis";p();p();var D=`
|
|
3
3
|
local slot, retired, meta, idx = KEYS[1], KEYS[2], KEYS[3], KEYS[4]
|
|
4
4
|
local key, gen, now = ARGV[1], tonumber(ARGV[2]), ARGV[3]
|
|
5
5
|
-- The session-as-routing-identity schema (docs/pooler-session-registry.md
|