@urun-sh/openai 0.6.49 → 0.6.50

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.
@@ -1,9 +1,9 @@
1
- import{a as Wn,c as Vn,d as Fe,e as Tt,f as re,g as zn,h as Kn,i as Xn,j as Yn,k as Qn,l as Zn,m as er,n as tr,r as nr,t as rr,u as sr,v as ir,w as or,x as ar}from"./chunk-X5BLQXHK.js";import{a as sn,e as on}from"./chunk-64VO62LW.js";import{a as Te,b as ye,v as Oe}from"./chunk-3JZAWWVV.js";import{a as Gn,e as lt,f as Jn,i as J,j as Q,k as an,l as un}from"./chunk-C452ZIU5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as qs}from"crypto";import{WebSocketServer as Us}from"ws";var Bs=256,Ot=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Bs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},js="local",dt=n=>n.slice(0,120),Pt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Vn,dt(e.message));return}if(e instanceof Q){this.ws.close(Tt,dt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,dt(e.message));return}this.ws.close(Fe,dt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=zn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=tr(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=rr(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:nr);return}this.transcript.push(...sr(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=Qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Tt);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Tt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Yn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Kn]=Xn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(or(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=qs();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Zn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(er(e.timeLeftMs)),this.ws.close(Fe,dt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=ir(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=ar(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Hs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new De(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ur(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Us({noServer:!0}),s=new Ot;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Wn&&(a.on("error",()=>{}),(async()=>{let d=Hs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:js}}r.handleUpgrade(o,a,u,p=>{new Pt(p,c,s)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
1
+ import{a as Wn,c as Vn,d as Fe,e as Tt,f as re,g as zn,h as Kn,i as Xn,j as Yn,k as Qn,l as Zn,m as er,n as tr,r as nr,t as rr,u as sr,v as ir,w as or,x as ar}from"./chunk-X5BLQXHK.js";import{a as sn,e as on}from"./chunk-64VO62LW.js";import{a as Te,b as ye,v as Oe}from"./chunk-6WTMEJZS.js";import{a as Gn,e as lt,f as Jn,i as J,j as Q,k as an,l as un}from"./chunk-C452ZIU5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as qs}from"crypto";import{WebSocketServer as Us}from"ws";var Bs=256,Ot=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Bs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},js="local",dt=n=>n.slice(0,120),Pt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Vn,dt(e.message));return}if(e instanceof Q){this.ws.close(Tt,dt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,dt(e.message));return}this.ws.close(Fe,dt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=zn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=tr(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=rr(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:nr);return}this.transcript.push(...sr(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=Qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Tt);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Tt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Yn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Kn]=Xn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(or(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=qs();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Zn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(er(e.timeLeftMs)),this.ws.close(Fe,dt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=ir(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=ar(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Hs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new De(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ur(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Us({noServer:!0}),s=new Ot;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Wn&&(a.on("error",()=>{}),(async()=>{let d=Hs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:js}}r.handleUpgrade(o,a,u,p=>{new Pt(p,c,s)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
2
2
  Connection: close\r
3
3
  \r
4
4
  ${m}\r
5
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of r.clients)o.close(1001,"server closing");await new Promise((o,a)=>r.close(u=>u===void 0?o():a(u)))})(),i)}function ka(n,e,t=new Ot){new Pt(n,e,t)}C();var Pe=class extends Error{code;status;retryAfterSeconds;constructor(e,t,r,s){super(s),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},ct=class extends Pe{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},ln=class extends Pe{constructor(e,t=!1){super("acquire_timeout",429,30,t?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},lr=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let t={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(t.min)||t.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(t.max)||t.max<t.min||t.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(t.inFlightCap)||t.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(t.warmWaitMs!==void 0&&(!Number.isInteger(t.warmWaitMs)||t.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=t.min,this.opts.max=t.max,this.opts.inFlightCap=t.inFlightCap,this.opts.warmWaitMs=t.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,t=0){let r=`decision:${this.opts.replicaId}:${e}`;return t===0?r:`${r}:${t}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let t=this.now(),r=this.slots.filter(s=>s.state==="paused"&&!s.opening&&(e||!s.dead)&&(!s.dead||t>=s.nextDialAt)).sort((s,i)=>s.slot.index-i.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let t=this.slots[e];t.dead&&!t.opening&&t.inFlight===0&&(t.backoffTimer&&(clearTimeout(t.backoffTimer),t.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(t)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${t instanceof Error?t.message:String(t)}`):(e.state="paused",this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new ct;this.lastDemandAt=this.now();let t=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let s=this.tryLease();if(s)return this.pump(),s;if(this.draining)throw new ct;let i=this.slots.some(c=>c.state==="queued"),o=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let u=r+t-Date.now();if(u<=0)throw new ln(t,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,u)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new ct}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let t=this.tryLease();if(t)return t;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(i=>i.state==="attached"),s=this.slots.some(i=>i.dead&&!i.opening&&this.now()>=i.nextDialAt);(r||s)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let i=s.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=r.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1;let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.opening=null,this.rotate(t,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,t){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,t),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),t=this.slots.filter(i=>i.state==="attached"&&i.inFlight===0&&i.idleSince!==null&&e-i.idleSince>=this.idleGraceMs).sort((i,o)=>(i.idleSince??0)-(o.idleSince??0)||o.slot.index-i.slot.index),r=this.slots.filter(i=>i.state==="attached").length,s=Math.max(0,Math.min(t.length,r-this.opts.min));for(let i of t.slice(0,s))this.endSlot(i);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(t=>t.state==="attached"||t.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(s=>s.state==="attached").length,t=this.slots.filter(s=>s.state==="queued").length,r=this.slots.filter(s=>s.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:r,inFlight:this.slots.reduce((s,i)=>s+i.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,t)=>e+t.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let t of this.waiters.splice(0))t.settled||(t.settled=!0,t.resolve());if(this.slots.reduce((t,r)=>t+r.inFlight,0)>0){if(!this.drainComplete){let r,s=new Promise(i=>{r=i});this.drainComplete={promise:s,resolve:r}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let s of this.waiters.splice(0))s.settled||(s.settled=!0,s.resolve());let e=this.slots.map(s=>s.entry).filter(s=>s!==null);for(let s of this.slots)clearTimeout(s.backoffTimer),s.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(s=>this.opts.closeSlot(s)))).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};C();import{SessionFailedError as Qs}from"@urun-sh/core";C();C();import{SessionFailedError as dr}from"@urun-sh/core";var we=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},Gs=33e4;function Ta(n,e=Gs){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,i=new Promise((l,d)=>{s=d}),o=setTimeout(()=>s(new Mt),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof Q||l instanceof dr&&l.kind==="transport-failed"?l:l instanceof Mt?(await r.return?.(void 0),new we("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new we("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(o)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new we("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Mt=class extends Error{constructor(){super("stream idle timeout")}};function Oa(n){return n instanceof we?!1:n instanceof Q?!0:n instanceof dr?n.kind==="transport-failed":!1}var Js=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ve(n){return!Js.some(e=>e.test(n))}function be(n){return n==null||n===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${n} when reporting it`}function de(n,e){if(n instanceof Q)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let t=cr(n);return t||{message:be(e?.inferenceId??null),redacted:!0}}function cr(n){return n instanceof Jn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof Gn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof J?{message:n.message,redacted:!1}:n instanceof Te?{message:n.message,redacted:!1}:n instanceof Pe?{message:n.message,redacted:!1}:n instanceof we?ve(n.message)?{message:n.message,redacted:!1}:null:n instanceof _e?{message:n.message,redacted:!1}:n instanceof ye?{message:n.message,redacted:!1}:null}function ze(n,e,t){let r=t??(o=>console.error(o)),s=cr(e);if(s)return s.redacted&&r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed: ${s.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ve(i)?`the ${n} upstream failed: ${i}`:(r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed while serving this request`)}function Se(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ve(e)?e:null}function pe(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}C();import{randomUUID as Ws}from"crypto";function A(n){return`${n}_${Ws().replace(/-/g,"").slice(0,24)}`}var Ct=4*1024*1024,dn=8*1024*1024,cn=512,Lt=20*1024*1024;function X(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Re(n,e){return{type:"server_error",code:n,message:e}}function G(n){return{type:"error",event_id:A("event"),error:n}}function pn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},Vs={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},zs={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ks={format:!0,voice:!0,speed:!0};function Xs(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ke(n,e){if(!Array.isArray(n)||n.length===0)throw new E(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let r of n){if(r!=="text"&&r!=="audio")throw new E(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(r)||t.push(r)}return t}function pr(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new E(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Ys=10;function mn(n){if(n==null)return n;let e;try{e=JSON.parse(n)}catch{return n}if(e===null||typeof e!="object"||Array.isArray(e))return n;let t=e;return t.hz!==void 0||t.cadence_ms!==void 0||!("questions"in t)&&!("question"in t)?n:JSON.stringify({...t,hz:Ys})}function pt(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new E("session must be an object","session","invalid_request");let s=n,i=Object.keys(s).filter(a=>!(a in Vs));if(i.length>0)throw new E(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(s.modalities!==void 0&&s.output_modalities!==void 0){let a=Ke(s.modalities,"modalities"),u=Ke(s.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new E("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let o={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(s))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new E(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new E(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!t.turns)throw new E('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");o.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new E(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=Ke(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new E('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");o.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Xs(u))throw new E(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new E("model must be a string or null","model");o.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new E("instructions must be a string or null","instructions");o.instructions=mn(u??void 0)??void 0;break;case"voice":if(u===null){delete o.voice;break}if(typeof u!="string")throw new E("voice must be a string or null","voice");if(!t.voice)throw new E("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");o.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new E(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new E("temperature must be a finite number or null","temperature");o.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new E(`${a} must be a positive integer, "inf" or null`,a);o.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new E("tools must be an array","tools");o.tools=u;break;case"tool_choice":o.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new E("metadata must be an object or null","metadata");o.metadata=u??null;break;case"turn_detection":{if(u===null){o.turnDetection=null;break}if(!t.turns)throw new E("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new E(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new E(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new E(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}o.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){o.inputAudioTranscription=!1;break}if(!t.turns)throw new E("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new E("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new E(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==t.model)throw new E(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${t.model===void 0?"the unnamed default app":JSON.stringify(t.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}o.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new E("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in zs))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&pr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=pt({input_audio_transcription:d.transcription},o,t,r);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=pt({turn_detection:d.turn_detection},o,t,r);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new E("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ks))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&pr(d.format,"audio.output.format"),d.speed!==void 0)throw new E("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete o.voice;else{if(typeof d.voice!="string")throw new E("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new E("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");o.voice=d.voice}d.format!==void 0&&!o.outputModalities.includes("audio")&&(o.outputModalities=["text","audio"])}break}default:break}return o}function $t(n,e){return{id:e,object:"realtime.session",type:n.type??"realtime",model:n.model??null,instructions:n.instructions??"",modalities:[...n.outputModalities],voice:n.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:n.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:n.turnDetection?{type:"server_vad",create_response:n.turnDetection.createResponse,interrupt_response:n.turnDetection.interruptResponse}:null,temperature:n.temperature??null,max_response_output_tokens:n.maxOutputTokens??"inf",tool_choice:n.toolChoice??"auto",tools:n.tools??[],metadata:n.metadata??null}}function fn(n,e){let t=n;if(!t||typeof t!="object")throw new E("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new E("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:A("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let r=t.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new E("message item content must be an array","item.content","invalid_request");let s=[];for(let i of t.content){let o=i;if(!o||typeof o!="object")throw new E("content part must be an object","item.content","invalid_request");if(o.type==="input_text"||r==="assistant"&&o.type==="output_text"){if(typeof o.text!="string")throw new E(`${String(o.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){if(!e)throw new E("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof o.audio!="string")throw new E("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}if(o.type==="input_image"){if(r!=="user")throw new E("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof o.image_url=="string"?o.image_url:o.image_url?.url;if(typeof a!="string"||a.length===0)throw new E("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new E("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof o.detail=="string"?o.detail:void 0;s.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new E(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:A("item"),type:"message",role:r,content:s}}throw new E(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Ft(n){let e=[],t=!1;for(let r of n){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let s=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let o=i.transcript;if(typeof o=="string"&&o.trim().length>0){s.push({type:"input_text",text:o});continue}t=!0;continue}}e.push({role:r.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Zs=1001,ei=1011,ti=15e3,ni=3e5;var Dt=class extends Error{},Nt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ne=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},hn=n=>n.slice(0,120),ri=/^[A-Za-z0-9+/=]*$/,si=2;function ii(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>si)return!1;return!0}var mt=class{id=A("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=pn();sessionId=A("sess");conversationId=A("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(t=>console.error(t)),this.turnStallMs=e.turnStallMs??ti,this.responseDeadlineMs=e.responseDeadlineMs??ni,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(t=>{t.reason===an&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:A("event"),session:$t(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:A("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let t of e.replayFrames??[])this.onMessage(t)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let r=await t.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof Q&&this.binding.composite===!0)this.failSessionGone(r);else{let s=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,s):this.send(G(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${s}`)))}}finally{this.turnLaneIterator===t&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let t=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,t),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:e,content_index:0,transcript:t});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,t){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:A("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:t}}),this.emitItemDone(e)}writeItemTranscript(e,t){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:t},...(r.content??[]).slice(1)])}emitItemDone(e){let t=this.items.findIndex(r=>r.id===e);t<0||this.send({type:"conversation.item.done",event_id:A("event"),previous_item_id:t>0?this.items[t-1].id:null,item:this.itemToProtocol(this.items[t])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,t.length>0&&(this.turnTranscript.text+=t),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&t.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:A("event"),item_id:r??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:A("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let s=this.turnTranscript.text.trim(),i=s.length>0?s:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=A("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:o,content_index:0,transcript:i}),this.emitItemDone(o),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(X("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>Ct){this.fail(X("frame_too_large",`frame exceeds the ${Ct}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(X("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(X("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(s instanceof Dt){this.fail(Re(null,this.callerLine(s,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
6
- ${s?.stack??pe(s)}`),this.send(G(Re(null,this.callerLine(s,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let t=pt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(G(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=t,this.send({type:"session.updated",event_id:A("event"),session:$t(this.config,this.sessionId)});return}case"conversation.item.create":{let t=fn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,s=t.content??[];(s.length===0||s.some(i=>i.type!=="input_image"))&&this.pushItem(t),this.forwardImageFrames(t),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:r,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(r=>r.id===e.item_id);if(t<0){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:A("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(r=>r.id===e.item_id);if(!t){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:A("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(r=>r.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(G(X("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:A("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(G(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ri.test(e.audio)){this.send(G(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,t);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Lt){this.send(G(X("buffer_full",`uncommitted input audio exceeds the ${Lt}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:t}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:A("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(G(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=A("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(t!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:t}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(G(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(G(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:t==null?"none":t instanceof Error?`error: ${t.message}`:t}))}).catch(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${t instanceof Error?t.message:String(t)}`}))}).finally(()=>{try{this.ws.close(1e3,hn("session ended by client"))}catch{}});return}default:this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(X("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new Dt("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(G({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let t=e[Symbol.asyncIterator](),r=this.turnCancelled,s=!0;try{for(;;){let i;if(s||this.turnStallMs<=0){s=!1;let o=t.next();o.catch(()=>{}),i=r?await Promise.race([o,r]):await o}else{let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Nt),this.turnStallMs)}),u=t.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(o))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(t.return?.()).catch(()=>{})}}async upstreamStream(e,t){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],t)}let s=this.binding.clients;if(s&&typeof s.createResponse=="function"){let{response:i,input:o,...a}=e;return await s.createResponse({...a,input:o})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(G(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{},r=t.modalities!==void 0?Ke(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?Ke(t.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&s!==void 0&&r.slice().sort().join(",")!==s.slice().sort().join(","))throw new E("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??r)?.includes("audio")&&!this.ensureVoice())return;if(t.input!==void 0){this.send(G(X("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let o=()=>{},a=new Promise((x,S)=>{o=()=>S(new Ne)});this.turnCancelled=a,this.wakeTurnCancelled=()=>o(),a.catch(()=>{});let u=()=>{},l=new Promise((x,S)=>{u=()=>S(new Ne)});this.turnDialGate=l,this.wakeTurnDialGate=()=>u(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=A("req"),p=`resp_${c}`;this.activeResponseId=p,this.activeRequestId=c;let m=this.binding.composite===!0,f=m?0:this.items.length,b=m?null:Ft(this.items),k=mn(typeof t.instructions=="string"?t.instructions:this.config.instructions),_=typeof t.temperature=="number"?t.temperature:this.config.temperature,y=t.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=t.tools!==void 0?t.tools:this.config.tools,$=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,P={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},..._!==void 0?{temperature:_}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...$!==void 0?{tool_choice:$}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:x,captureWallMs:S}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,S);this.inFlight=(async()=>{let x=[],S=M=>{this.responseFlushed?this.send(M):x.push(M)},I=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:A("event"),response:this.responseObject(p,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(p,"in_progress")});for(let M of x)this.send(M);x.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},v=null,R=()=>{this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.responseObject(p,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))throw new Ne;f=this.items.length,b=Ft(this.items)}let{input:M,sawAudioOnlyItem:j}=b??{input:[],sawAudioOnlyItem:!1},H={...P,input:M,...m?this.compositeTurnAsk(t):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let L;try{let O=this.upstreamStream(H,c);Promise.resolve(O).catch(D=>{D instanceof Q&&this.failSessionGone(D)}),L=await Promise.race([O,l])}catch(O){if(O instanceof Ne){this.deadlineFired&&!this.closed&&R();return}this.upstreamTurnFault(O,p);return}I();try{for await(let O of this.stallBoundedTurn(L)){if(this.cancelled)break;let D=O;if(D.type==="error"){let U=this.upstreamErrorBody(D);h.contentFlowed?this.send(G(U)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(p,U)});return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){I(),h.contentFlowed=!0,h.messageOpen||(this.beginMessageItem(p,h.nextOutputIndex++),h.messageOpen=!0),this.config.outputModalities.includes("text")&&S({type:"response.output_text.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta}),this.turnOutputIsAudio()&&(h.transcriptDelta=!0,S({type:"response.output_audio_transcript.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta})),h.messageText+=D.delta;continue}if(D.type==="response.function_call_arguments.delta"){I(),h.contentFlowed=!0;let U=typeof D.delta=="string"?D.delta:"",z=typeof D.call_id=="string"&&D.call_id.length>0?D.call_id:`${p}_fc_${h.nextOutputIndex}`,T=h.tools.get(z);if(!T){let q=typeof D.name=="string"&&D.name.length>0?D.name:void 0;T={outputIndex:h.nextOutputIndex++,name:q,args:""},h.tools.set(z,T);let W={id:z,object:"realtime.item",type:"function_call",call_id:z,name:q??"",arguments:"",status:"in_progress"};S({type:"response.output_item.added",event_id:A("event"),response_id:p,output_index:T.outputIndex,item:W}),this.emitAssistantItemAdded(W)}typeof D.name=="string"&&D.name.length>0&&(T.name=D.name),T.args+=U,S({type:"response.function_call_arguments.delta",event_id:A("event"),item_id:z,response_id:p,output_index:T.outputIndex,call_id:z,name:T.name??"",delta:U});continue}if(D.type==="response.completed"){v=D.response??null;continue}}}catch(O){if(this.closed)return;if(O instanceof Ne){this.deadlineFired&&R();return}if(this.cancelled)return;if(O instanceof Nt)this.operatorLog(`[realtime] turn ${p} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(O,p);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&R();return}this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.doneResponse(p,f,v)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){if(ii(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:A("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let t=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let s={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:r,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,r){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,i=this.messageItemOpenForAudio,o=this.config.outputModalities.includes("text"),a=t.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),t.messageText.length>0&&o&&this.send({type:"response.output_text.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:t.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),t.messageText.length>0&&u.push({type:"output_text",text:t.messageText});let l={id:s,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[s,i]of t.tools){let o=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:A("event"),item_id:s,response_id:e,output_index:i.outputIndex,call_id:s,name:i.name??"",arguments:o});let a={id:s,type:"function_call",callId:s,name:i.name,arguments:o};this.pushItem(a),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,r){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,r){let s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let o=t;o<this.items.length;o++)i.push(this.itemToProtocol(this.items[o]));return this.responseObject(e,"completed",{output:i,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let t=e.error,r=Se(t);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let s=r??be(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Re(un,"the organization is out of credits \u2014 top up to continue"),un))}failSessionGone(e){if(e instanceof Q&&e.reason===an){this.failInsufficientCredits();return}let t=e instanceof Error&&ve(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${pe(e)}`);let r=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(Re("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Qs&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Re(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(r)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(t,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let t=this.activeRequestId,r=this.binding.session;t!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(t),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let t=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:A("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cn&&this.items.shift()}forwardImageFrames(e){for(let t of e.content??[]){if(t.type!=="input_image")continue;let r=t.imageUrl.indexOf(","),s=r>=0?Buffer.from(t.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(s.byteLength===0){this.send(G(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(s.byteLength>on){this.send(G(X("frame_too_large",`input_image frame is ${s.byteLength} bytes \u2014 over the ${on}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(G(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(s))).catch(i=>this.send(G(Re(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:s.type==="input_image"?{type:"input_image",image_url:s.imageUrl,...s.detail?{detail:s.detail}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>dn){this.ws.close(Zs,hn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${pe(e)}`),r.message}fail(e,t){this.send(G(e)),this.ws.close(ei,hn(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let t=this.turnLaneIterator;if(this.turnLaneIterator=null,t!==null){let r=t.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>mr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),mr(this.id,e)}},gn=[];function mr(n,e){gn.push({id:n,reason:e}),gn.length>256&&gn.shift()}C();import{SessionFailedError as fr}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as oi}from"@urun-sh/core";var ai={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},ui={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function ft(n,e){let t=ui[n.code];return e?`${t} (${e})`:t}function qt(n){if(n==null)return null;let e=ai[n];return e===void 0?null:{status:e,code:n,retryable:e!==502,openaiType:n==="no_capacity"||n==="queue_full"?"capacity_error":n==="queue_timeout"||n==="cold_start_exceeded"||n==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Ut(n){if(n.kind==="create-failed")return qt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=oi;return qt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocket as hr,WebSocketServer as li}from"ws";var _n="/v1/realtime",gr="urun.admission",yr=n=>n.slice(0,120);function di(n,e,t){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
5
+ `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of r.clients)o.close(1001,"server closing");await new Promise((o,a)=>r.close(u=>u===void 0?o():a(u)))})(),i)}function ka(n,e,t=new Ot){new Pt(n,e,t)}C();var Pe=class extends Error{code;status;retryAfterSeconds;constructor(e,t,r,s){super(s),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},ct=class extends Pe{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},ln=class extends Pe{constructor(e,t=!1){super("acquire_timeout",429,30,t?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},lr=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let t={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(t.min)||t.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(t.max)||t.max<t.min||t.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(t.inFlightCap)||t.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(t.warmWaitMs!==void 0&&(!Number.isInteger(t.warmWaitMs)||t.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=t.min,this.opts.max=t.max,this.opts.inFlightCap=t.inFlightCap,this.opts.warmWaitMs=t.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,t=0){let r=`decision:${this.opts.replicaId}:${e}`;return t===0?r:`${r}:${t}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let t=this.now(),r=this.slots.filter(s=>s.state==="paused"&&!s.opening&&(e||!s.dead)&&(!s.dead||t>=s.nextDialAt)).sort((s,i)=>s.slot.index-i.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let t=this.slots[e];t.dead&&!t.opening&&t.inFlight===0&&(t.backoffTimer&&(clearTimeout(t.backoffTimer),t.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(t)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${t instanceof Error?t.message:String(t)}`):(e.state="paused",this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new ct;this.lastDemandAt=this.now();let t=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let s=this.tryLease();if(s)return this.pump(),s;if(this.draining)throw new ct;let i=this.slots.some(c=>c.state==="queued"),o=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let u=r+t-Date.now();if(u<=0)throw new ln(t,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,u)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new ct}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let t=this.tryLease();if(t)return t;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(i=>i.state==="attached"),s=this.slots.some(i=>i.dead&&!i.opening&&this.now()>=i.nextDialAt);(r||s)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let i=s.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=r.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1,this.opts.onLease?.(t);let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.opening=null,this.rotate(t,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,t){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,t),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),t=this.slots.filter(i=>i.state==="attached"&&i.inFlight===0&&i.idleSince!==null&&e-i.idleSince>=this.idleGraceMs).sort((i,o)=>(i.idleSince??0)-(o.idleSince??0)||o.slot.index-i.slot.index),r=this.slots.filter(i=>i.state==="attached").length,s=Math.max(0,Math.min(t.length,r-this.opts.min));for(let i of t.slice(0,s))this.endSlot(i);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(t=>t.state==="attached"||t.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(s=>s.state==="attached").length,t=this.slots.filter(s=>s.state==="queued").length,r=this.slots.filter(s=>s.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:r,inFlight:this.slots.reduce((s,i)=>s+i.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,t)=>e+t.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let t of this.waiters.splice(0))t.settled||(t.settled=!0,t.resolve());if(this.slots.reduce((t,r)=>t+r.inFlight,0)>0){if(!this.drainComplete){let r,s=new Promise(i=>{r=i});this.drainComplete={promise:s,resolve:r}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let s of this.waiters.splice(0))s.settled||(s.settled=!0,s.resolve());let e=this.slots.map(s=>s.entry).filter(s=>s!==null);for(let s of this.slots)clearTimeout(s.backoffTimer),s.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(s=>this.opts.closeSlot(s)))).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};C();import{SessionFailedError as Qs}from"@urun-sh/core";C();C();import{SessionFailedError as dr}from"@urun-sh/core";var we=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},Gs=33e4;function Ta(n,e=Gs){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,i=new Promise((l,d)=>{s=d}),o=setTimeout(()=>s(new Mt),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof Q||l instanceof dr&&l.kind==="transport-failed"?l:l instanceof Mt?(await r.return?.(void 0),new we("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new we("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(o)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new we("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Mt=class extends Error{constructor(){super("stream idle timeout")}};function Oa(n){return n instanceof we?!1:n instanceof Q?!0:n instanceof dr?n.kind==="transport-failed":!1}var Js=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ve(n){return!Js.some(e=>e.test(n))}function be(n){return n==null||n===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${n} when reporting it`}function de(n,e){if(n instanceof Q)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let t=cr(n);return t||{message:be(e?.inferenceId??null),redacted:!0}}function cr(n){return n instanceof Jn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof Gn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof J?{message:n.message,redacted:!1}:n instanceof Te?{message:n.message,redacted:!1}:n instanceof Pe?{message:n.message,redacted:!1}:n instanceof we?ve(n.message)?{message:n.message,redacted:!1}:null:n instanceof _e?{message:n.message,redacted:!1}:n instanceof ye?{message:n.message,redacted:!1}:null}function ze(n,e,t){let r=t??(o=>console.error(o)),s=cr(e);if(s)return s.redacted&&r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed: ${s.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ve(i)?`the ${n} upstream failed: ${i}`:(r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed while serving this request`)}function Se(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ve(e)?e:null}function pe(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}C();import{randomUUID as Ws}from"crypto";function A(n){return`${n}_${Ws().replace(/-/g,"").slice(0,24)}`}var Ct=4*1024*1024,dn=8*1024*1024,cn=512,Lt=20*1024*1024;function X(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Re(n,e){return{type:"server_error",code:n,message:e}}function G(n){return{type:"error",event_id:A("event"),error:n}}function pn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},Vs={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},zs={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ks={format:!0,voice:!0,speed:!0};function Xs(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ke(n,e){if(!Array.isArray(n)||n.length===0)throw new E(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let r of n){if(r!=="text"&&r!=="audio")throw new E(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(r)||t.push(r)}return t}function pr(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new E(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Ys=10;function mn(n){if(n==null)return n;let e;try{e=JSON.parse(n)}catch{return n}if(e===null||typeof e!="object"||Array.isArray(e))return n;let t=e;return t.hz!==void 0||t.cadence_ms!==void 0||!("questions"in t)&&!("question"in t)?n:JSON.stringify({...t,hz:Ys})}function pt(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new E("session must be an object","session","invalid_request");let s=n,i=Object.keys(s).filter(a=>!(a in Vs));if(i.length>0)throw new E(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(s.modalities!==void 0&&s.output_modalities!==void 0){let a=Ke(s.modalities,"modalities"),u=Ke(s.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new E("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let o={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(s))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new E(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new E(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!t.turns)throw new E('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");o.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new E(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=Ke(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new E('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");o.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Xs(u))throw new E(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new E("model must be a string or null","model");o.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new E("instructions must be a string or null","instructions");o.instructions=mn(u??void 0)??void 0;break;case"voice":if(u===null){delete o.voice;break}if(typeof u!="string")throw new E("voice must be a string or null","voice");if(!t.voice)throw new E("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");o.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new E(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new E("temperature must be a finite number or null","temperature");o.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new E(`${a} must be a positive integer, "inf" or null`,a);o.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new E("tools must be an array","tools");o.tools=u;break;case"tool_choice":o.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new E("metadata must be an object or null","metadata");o.metadata=u??null;break;case"turn_detection":{if(u===null){o.turnDetection=null;break}if(!t.turns)throw new E("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new E(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new E(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new E(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}o.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){o.inputAudioTranscription=!1;break}if(!t.turns)throw new E("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new E("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new E(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==t.model)throw new E(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${t.model===void 0?"the unnamed default app":JSON.stringify(t.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}o.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new E("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in zs))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&pr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=pt({input_audio_transcription:d.transcription},o,t,r);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=pt({turn_detection:d.turn_detection},o,t,r);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new E("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ks))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&pr(d.format,"audio.output.format"),d.speed!==void 0)throw new E("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete o.voice;else{if(typeof d.voice!="string")throw new E("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new E("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");o.voice=d.voice}d.format!==void 0&&!o.outputModalities.includes("audio")&&(o.outputModalities=["text","audio"])}break}default:break}return o}function $t(n,e){return{id:e,object:"realtime.session",type:n.type??"realtime",model:n.model??null,instructions:n.instructions??"",modalities:[...n.outputModalities],voice:n.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:n.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:n.turnDetection?{type:"server_vad",create_response:n.turnDetection.createResponse,interrupt_response:n.turnDetection.interruptResponse}:null,temperature:n.temperature??null,max_response_output_tokens:n.maxOutputTokens??"inf",tool_choice:n.toolChoice??"auto",tools:n.tools??[],metadata:n.metadata??null}}function fn(n,e){let t=n;if(!t||typeof t!="object")throw new E("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new E("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:A("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let r=t.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new E("message item content must be an array","item.content","invalid_request");let s=[];for(let i of t.content){let o=i;if(!o||typeof o!="object")throw new E("content part must be an object","item.content","invalid_request");if(o.type==="input_text"||r==="assistant"&&o.type==="output_text"){if(typeof o.text!="string")throw new E(`${String(o.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){if(!e)throw new E("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof o.audio!="string")throw new E("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}if(o.type==="input_image"){if(r!=="user")throw new E("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof o.image_url=="string"?o.image_url:o.image_url?.url;if(typeof a!="string"||a.length===0)throw new E("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new E("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof o.detail=="string"?o.detail:void 0;s.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new E(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:A("item"),type:"message",role:r,content:s}}throw new E(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Ft(n){let e=[],t=!1;for(let r of n){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let s=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let o=i.transcript;if(typeof o=="string"&&o.trim().length>0){s.push({type:"input_text",text:o});continue}t=!0;continue}}e.push({role:r.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Zs=1001,ei=1011,ti=6e4,ni=3e5;var Dt=class extends Error{},Nt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ne=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},hn=n=>n.slice(0,120),ri=/^[A-Za-z0-9+/=]*$/,si=2;function ii(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>si)return!1;return!0}var mt=class{id=A("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=pn();sessionId=A("sess");conversationId=A("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(t=>console.error(t)),this.turnStallMs=e.turnStallMs??ti,this.responseDeadlineMs=e.responseDeadlineMs??ni,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(t=>{t.reason===an&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:A("event"),session:$t(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:A("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let t of e.replayFrames??[])this.onMessage(t)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let r=await t.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof Q&&this.binding.composite===!0)this.failSessionGone(r);else{let s=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,s):this.send(G(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${s}`)))}}finally{this.turnLaneIterator===t&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let t=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,t),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:e,content_index:0,transcript:t});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,t){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:A("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:t}}),this.emitItemDone(e)}writeItemTranscript(e,t){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:t},...(r.content??[]).slice(1)])}emitItemDone(e){let t=this.items.findIndex(r=>r.id===e);t<0||this.send({type:"conversation.item.done",event_id:A("event"),previous_item_id:t>0?this.items[t-1].id:null,item:this.itemToProtocol(this.items[t])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,t.length>0&&(this.turnTranscript.text+=t),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&t.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:A("event"),item_id:r??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:A("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let s=this.turnTranscript.text.trim(),i=s.length>0?s:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=A("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:o,content_index:0,transcript:i}),this.emitItemDone(o),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(X("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>Ct){this.fail(X("frame_too_large",`frame exceeds the ${Ct}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(X("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(X("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(s instanceof Dt){this.fail(Re(null,this.callerLine(s,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
6
+ ${s?.stack??pe(s)}`),this.send(G(Re(null,this.callerLine(s,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let t=pt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(G(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=t,this.send({type:"session.updated",event_id:A("event"),session:$t(this.config,this.sessionId)});return}case"conversation.item.create":{let t=fn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,s=t.content??[];(s.length===0||s.some(i=>i.type!=="input_image"))&&this.pushItem(t),this.forwardImageFrames(t),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:r,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(r=>r.id===e.item_id);if(t<0){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:A("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(r=>r.id===e.item_id);if(!t){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:A("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(r=>r.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(G(X("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:A("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(G(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ri.test(e.audio)){this.send(G(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,t);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Lt){this.send(G(X("buffer_full",`uncommitted input audio exceeds the ${Lt}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:t}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:A("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(G(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=A("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(t!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:t}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(G(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(G(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:t==null?"none":t instanceof Error?`error: ${t.message}`:t}))}).catch(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${t instanceof Error?t.message:String(t)}`}))}).finally(()=>{try{this.ws.close(1e3,hn("session ended by client"))}catch{}});return}case"ping":return;default:this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(X("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new Dt("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(G({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let t=e[Symbol.asyncIterator](),r=this.turnCancelled,s=!0;try{for(;;){let i;if(s||this.turnStallMs<=0){s=!1;let o=t.next();o.catch(()=>{}),i=r?await Promise.race([o,r]):await o}else{let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Nt),this.turnStallMs)}),u=t.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(o))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(t.return?.()).catch(()=>{})}}async upstreamStream(e,t){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],t)}let s=this.binding.clients;if(s&&typeof s.createResponse=="function"){let{response:i,input:o,...a}=e;return await s.createResponse({...a,input:o})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(G(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{},r=t.modalities!==void 0?Ke(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?Ke(t.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&s!==void 0&&r.slice().sort().join(",")!==s.slice().sort().join(","))throw new E("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??r)?.includes("audio")&&!this.ensureVoice())return;if(t.input!==void 0){this.send(G(X("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let o=()=>{},a=new Promise((x,S)=>{o=()=>S(new Ne)});this.turnCancelled=a,this.wakeTurnCancelled=()=>o(),a.catch(()=>{});let u=()=>{},l=new Promise((x,S)=>{u=()=>S(new Ne)});this.turnDialGate=l,this.wakeTurnDialGate=()=>u(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=A("req"),p=`resp_${c}`;this.activeResponseId=p,this.activeRequestId=c;let m=this.binding.composite===!0,f=m?0:this.items.length,b=m?null:Ft(this.items),k=mn(typeof t.instructions=="string"?t.instructions:this.config.instructions),_=typeof t.temperature=="number"?t.temperature:this.config.temperature,y=t.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=t.tools!==void 0?t.tools:this.config.tools,$=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,P={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},..._!==void 0?{temperature:_}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...$!==void 0?{tool_choice:$}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:x,captureWallMs:S}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,S);this.inFlight=(async()=>{let x=[],S=M=>{this.responseFlushed?this.send(M):x.push(M)},I=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:A("event"),response:this.responseObject(p,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(p,"in_progress")});for(let M of x)this.send(M);x.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},v=null,R=()=>{this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.responseObject(p,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))throw new Ne;f=this.items.length,b=Ft(this.items)}let{input:M,sawAudioOnlyItem:j}=b??{input:[],sawAudioOnlyItem:!1},H={...P,input:M,...m?this.compositeTurnAsk(t):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let L;try{let O=this.upstreamStream(H,c);Promise.resolve(O).catch(D=>{D instanceof Q&&this.failSessionGone(D)}),L=await Promise.race([O,l])}catch(O){if(O instanceof Ne){this.deadlineFired&&!this.closed&&R();return}this.upstreamTurnFault(O,p);return}I();try{for await(let O of this.stallBoundedTurn(L)){if(this.cancelled)break;let D=O;if(D.type==="error"){let U=this.upstreamErrorBody(D);h.contentFlowed?this.send(G(U)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(p,U)});return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){I(),h.contentFlowed=!0,h.messageOpen||(this.beginMessageItem(p,h.nextOutputIndex++),h.messageOpen=!0),this.config.outputModalities.includes("text")&&S({type:"response.output_text.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta}),this.turnOutputIsAudio()&&(h.transcriptDelta=!0,S({type:"response.output_audio_transcript.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta})),h.messageText+=D.delta;continue}if(D.type==="response.function_call_arguments.delta"){I(),h.contentFlowed=!0;let U=typeof D.delta=="string"?D.delta:"",z=typeof D.call_id=="string"&&D.call_id.length>0?D.call_id:`${p}_fc_${h.nextOutputIndex}`,T=h.tools.get(z);if(!T){let q=typeof D.name=="string"&&D.name.length>0?D.name:void 0;T={outputIndex:h.nextOutputIndex++,name:q,args:""},h.tools.set(z,T);let W={id:z,object:"realtime.item",type:"function_call",call_id:z,name:q??"",arguments:"",status:"in_progress"};S({type:"response.output_item.added",event_id:A("event"),response_id:p,output_index:T.outputIndex,item:W}),this.emitAssistantItemAdded(W)}typeof D.name=="string"&&D.name.length>0&&(T.name=D.name),T.args+=U,S({type:"response.function_call_arguments.delta",event_id:A("event"),item_id:z,response_id:p,output_index:T.outputIndex,call_id:z,name:T.name??"",delta:U});continue}if(D.type==="response.completed"){v=D.response??null;continue}}}catch(O){if(this.closed)return;if(O instanceof Ne){this.deadlineFired&&R();return}if(this.cancelled)return;if(O instanceof Nt)this.operatorLog(`[realtime] turn ${p} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(O,p);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&R();return}this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.doneResponse(p,f,v)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){if(ii(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:A("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let t=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let s={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:r,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,r){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,i=this.messageItemOpenForAudio,o=this.config.outputModalities.includes("text"),a=t.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),t.messageText.length>0&&o&&this.send({type:"response.output_text.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:t.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),t.messageText.length>0&&u.push({type:"output_text",text:t.messageText});let l={id:s,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[s,i]of t.tools){let o=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:A("event"),item_id:s,response_id:e,output_index:i.outputIndex,call_id:s,name:i.name??"",arguments:o});let a={id:s,type:"function_call",callId:s,name:i.name,arguments:o};this.pushItem(a),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,r){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,r){let s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let o=t;o<this.items.length;o++)i.push(this.itemToProtocol(this.items[o]));return this.responseObject(e,"completed",{output:i,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let t=e.error,r=Se(t);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let s=r??be(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Re(un,"the organization is out of credits \u2014 top up to continue"),un))}failSessionGone(e){if(e instanceof Q&&e.reason===an){this.failInsufficientCredits();return}let t=e instanceof Error&&ve(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${pe(e)}`);let r=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(Re("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Qs&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Re(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(r)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(t,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let t=this.activeRequestId,r=this.binding.session;t!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(t),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let t=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:A("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cn&&this.items.shift()}forwardImageFrames(e){for(let t of e.content??[]){if(t.type!=="input_image")continue;let r=t.imageUrl.indexOf(","),s=r>=0?Buffer.from(t.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(s.byteLength===0){this.send(G(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(s.byteLength>on){this.send(G(X("frame_too_large",`input_image frame is ${s.byteLength} bytes \u2014 over the ${on}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(G(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(s))).catch(i=>this.send(G(Re(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:s.type==="input_image"?{type:"input_image",image_url:s.imageUrl,...s.detail?{detail:s.detail}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>dn){this.ws.close(Zs,hn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${pe(e)}`),r.message}fail(e,t){this.send(G(e)),this.ws.close(ei,hn(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let t=this.turnLaneIterator;if(this.turnLaneIterator=null,t!==null){let r=t.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>mr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),mr(this.id,e)}},gn=[];function mr(n,e){gn.push({id:n,reason:e}),gn.length>256&&gn.shift()}C();import{SessionFailedError as fr}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as oi}from"@urun-sh/core";var ai={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},ui={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function ft(n,e){let t=ui[n.code];return e?`${t} (${e})`:t}function qt(n){if(n==null)return null;let e=ai[n];return e===void 0?null:{status:e,code:n,retryable:e!==502,openaiType:n==="no_capacity"||n==="queue_full"?"capacity_error":n==="queue_timeout"||n==="cold_start_exceeded"||n==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Ut(n){if(n.kind==="create-failed")return qt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=oi;return qt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocket as hr,WebSocketServer as li}from"ws";var _n="/v1/realtime",gr="urun.admission",yr=n=>n.slice(0,120);function di(n,e,t){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
7
7
  Connection: close\r
8
8
  Content-Type: text/plain\r
9
9
  \r
@@ -63,4 +63,4 @@ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:P.message}}
63
63
 
64
64
  `):c.write(`data: ${JSON.stringify({error:{message:P.message,type:"upstream_error",code:$}})}
65
65
 
66
- `)),c.end()})}}function Jl(n){let{clients:e,apiKey:t}=n,r=qo(ua(n)),s=Er(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),i=wn(r,{resolver:Ms(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),o=r.close.bind(r);return r.close=(a=>(s.close(),i(),o(a))),ur(r,{clients:e,apiKey:t}),r}C();var Ee=(n,e)=>Object.assign(new Error(e),{status:n}),ca='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Bn=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Un=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof J?Ee(404,t.message):t}};async function Ds(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ee(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ca}`);if(s==="transcription")throw Ee(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(m){throw m instanceof J?Ee(404,m.message):m}if(!p)throw Ee(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(m){throw m instanceof J?Ee(404,m.message):m}if(p!=="stt")throw Ee(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Un(n,t.stt),o=await Un(n,e),a=await Un(n,t.tts),u=await n.openAudioOn(i,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,pa({clients:n,chatHandle:o,ttsHandle:a,chatModel:e,companions:t},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(i,p)}catch(m){throw m instanceof Q?Bn("stt",t.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Ns(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var It=class extends Error{};async function*pa(n,e,t,r){let{clients:s,chatHandle:i,ttsHandle:o,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,f=null,b=null,k=[],_=null,y=new Promise((v,R)=>{t&&t.addEventListener("abort",()=>R(new It),{once:!0})}),g=()=>m||t?.aborted===!0,w=async v=>{if(g())return;let R;try{R=await s.createResponseOn(o,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:v}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(j){throw j instanceof Q?Bn("tts",u.tts,j):j}let M=R[Symbol.asyncIterator]();b=M;try{for(;;){let j=M.next(),H;try{H=await Promise.race([j,y])}catch(O){if(j.catch(()=>{}),O instanceof It)return;throw O}if(H.done)return;let L=H.value;if(L.type==="error"){let O=L.error&&typeof L.error.message=="string"?L.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${O}`)}if(L.type==="response.completed")return}}finally{b===M&&(b=null)}},$=async()=>{for(;k.length>0&&!g();){let v=k.shift();await w(v)}},P=v=>{if(v===""||g()||(k.push(v),_!==null))return;let R=$();_=R,R.then(()=>{_===R&&(_=null)},M=>{_===R&&(_=null),f??=M})},x=()=>{m=!0,k.length=0;let v=b;if(b=null,v){let R=v.return?.();R&&R.catch(()=>{})}},S=async()=>{for(;k.length>0||_!==null;){let v=_;if(v===null){await w(k.shift());continue}await v}},I=p?new at({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},v=>P(v)):null,h=null;try{let v;try{v=await s.createResponseOn(i,d)}catch(M){throw M instanceof Q?Bn("chat",a,M):M}let R=v[Symbol.asyncIterator]();try{for(;;){let M=R.next(),j;try{j=await Promise.race([M,y])}catch(O){if(M.catch(()=>{}),O instanceof It)break;throw O}if(j.done)break;let H=j.value;if(g())return;let L=H;if(L.type==="error"){yield H;return}if(L.type==="response.output_text.delta"&&typeof L.delta=="string"){yield H,I?.push(L.delta);continue}if(L.type==="response.function_call_arguments.delta"){I?.flush(),yield H;continue}if(L.type==="response.completed"){h=H.response;continue}}}finally{Promise.resolve(R.return?.()).catch(()=>{})}I?.flush(),I?.dispose(),p&&await S(),h!==null&&(yield{type:"response.completed",response:h})}finally{I?.dispose(),x();try{if(f instanceof Q)throw f}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function fa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function ha(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}function ud(n){let e=new URL(n.url??"/","http://localhost").searchParams.get("session"),t=n.headers?.["x-urun-session"],r=(e??(typeof t=="string"?t:t?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var ga='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ya(n,e,t,r,s){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await n.supportsAudio(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(!i){let m=null;if(n.realtimeCompanionsFor)try{m=await n.realtimeCompanionsFor(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(m!==null)return await Ds(n,e,m,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let m;try{m=await n.transcriptStreamFor(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(m!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ga}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=n.dedicatedSessionHandle?await n.dedicatedSessionHandle(e):await n.sessionHandle(e)}catch(m){throw m instanceof ye?ce(503,m.message):m}let u=n.realtimeBillingIdentityFor?await n.realtimeBillingIdentityFor(e):null,l=`conn_${ma()}`,c={audio:await n.openAudioOn(a,t,l,s).catch(m=>{throw n.releaseSessionHandle?.(a),m})},p={clients:{createResponse:async m=>await n.createResponseOn(a,m,l)},voice:i,audioSession:c};return n.openVideoOn&&(p.video=()=>n.openVideoOn(a,t)),o&&(p.turns=m=>n.openTurnsOn(a,m)),r==="transcription"&&(p.intent="transcription"),n.releaseSessionHandle&&(p.release=()=>n.releaseSessionHandle(a)),n.endDedicatedSession&&(p.endSession=()=>n.endDedicatedSession(a)),n.onSessionEnd&&(p.onSessionEnd=m=>n.onSessionEnd(a,m)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Ms(n,e,t){let r=Ns(n,t);return{resolve:async(s,i,o)=>{if(e!==void 0){let a=s.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw ce(401,"invalid local proxy api key")}return ya(r,fa(s),i,ha(s),o)}}}export{Ot as a,ur as b,ka as c,ht as d,lr as e,Gs as f,Ta as g,Oa as h,Ii as i,Er as j,mt as k,_n as l,wn as m,Ns as n,fa as o,ha as p,ud as q,ya as r,Ms as s,fs as t,ne as u,rl as v,Mn as w,dl as x,cl as y,pl as z,ml as A,fl as B,Is as C,$s as D,ua as E,Jl as F};
66
+ `)),c.end()})}}function Jl(n){let{clients:e,apiKey:t}=n,r=qo(ua(n)),s=Er(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),i=wn(r,{resolver:Ms(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),o=r.close.bind(r);return r.close=(a=>(s.close(),i(),o(a))),ur(r,{clients:e,apiKey:t}),r}C();var Ee=(n,e)=>Object.assign(new Error(e),{status:n}),ca='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Bn=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Un=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof J?Ee(404,t.message):t}};async function Ds(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ee(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ca}`);if(s==="transcription")throw Ee(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(m){throw m instanceof J?Ee(404,m.message):m}if(!p)throw Ee(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(m){throw m instanceof J?Ee(404,m.message):m}if(p!=="stt")throw Ee(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Un(n,t.stt),o=await Un(n,e),a=await Un(n,t.tts),u=await n.openAudioOn(i,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,pa({clients:n,chatHandle:o,ttsHandle:a,chatModel:e,companions:t},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(i,p)}catch(m){throw m instanceof Q?Bn("stt",t.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Ns(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var It=class extends Error{};async function*pa(n,e,t,r){let{clients:s,chatHandle:i,ttsHandle:o,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,f=null,b=null,k=[],_=null,y=new Promise((v,R)=>{t&&t.addEventListener("abort",()=>R(new It),{once:!0})}),g=()=>m||t?.aborted===!0,w=async v=>{if(g())return;let R;try{R=await s.createResponseOn(o,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:v}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(j){throw j instanceof Q?Bn("tts",u.tts,j):j}let M=R[Symbol.asyncIterator]();b=M;try{for(;;){let j=M.next(),H;try{H=await Promise.race([j,y])}catch(O){if(j.catch(()=>{}),O instanceof It)return;throw O}if(H.done)return;let L=H.value;if(L.type==="error"){let O=L.error&&typeof L.error.message=="string"?L.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${O}`)}if(L.type==="response.completed")return}}finally{b===M&&(b=null)}},$=async()=>{for(;k.length>0&&!g();){let v=k.shift();await w(v)}},P=v=>{if(v===""||g()||(k.push(v),_!==null))return;let R=$();_=R,R.then(()=>{_===R&&(_=null)},M=>{_===R&&(_=null),f??=M})},x=()=>{m=!0,k.length=0;let v=b;if(b=null,v){let R=v.return?.();R&&R.catch(()=>{})}},S=async()=>{for(;k.length>0||_!==null;){let v=_;if(v===null){await w(k.shift());continue}await v}},I=p?new at({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},v=>P(v)):null,h=null;try{let v;try{v=await s.createResponseOn(i,d)}catch(M){throw M instanceof Q?Bn("chat",a,M):M}let R=v[Symbol.asyncIterator]();try{for(;;){let M=R.next(),j;try{j=await Promise.race([M,y])}catch(O){if(M.catch(()=>{}),O instanceof It)break;throw O}if(j.done)break;let H=j.value;if(g())return;let L=H;if(L.type==="error"){yield H;return}if(L.type==="response.output_text.delta"&&typeof L.delta=="string"){yield H,I?.push(L.delta);continue}if(L.type==="response.function_call_arguments.delta"){I?.flush(),yield H;continue}if(L.type==="response.completed"){h=H.response;continue}}}finally{Promise.resolve(R.return?.()).catch(()=>{})}I?.flush(),I?.dispose(),p&&await S(),h!==null&&(yield{type:"response.completed",response:h})}finally{I?.dispose(),x();try{if(f instanceof Q)throw f}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function fa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function ha(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}function ud(n){let e=new URL(n.url??"/","http://localhost").searchParams.get("session"),t=n.headers?.["x-urun-session"],r=(e??(typeof t=="string"?t:t?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var ga='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ya(n,e,t,r,s){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await n.supportsAudio(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(!i){let m=null;if(n.realtimeCompanionsFor)try{m=await n.realtimeCompanionsFor(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(m!==null)return await Ds(n,e,m,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let m;try{m=await n.transcriptStreamFor(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(m!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ga}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=n.dedicatedSessionHandle?await n.dedicatedSessionHandle(e):await n.sessionHandle(e)}catch(m){throw m instanceof ye?ce(503,m.message):m}let u=n.realtimeBillingIdentityFor?await n.realtimeBillingIdentityFor(e):null,l=`conn_${ma()}`,c={audio:await n.openAudioOn(a,t,l,s).catch(m=>{throw n.releaseSessionHandle?.(a),m})},p={clients:{createResponse:async m=>await n.createResponseOn(a,m,l)},voice:i,audioSession:c};return n.openVideoOn&&(p.video=()=>n.openVideoOn(a,t)),o&&(p.turns=m=>n.openTurnsOn(a,m)),r==="transcription"&&(p.intent="transcription"),n.releaseSessionHandle&&(p.release=()=>n.releaseSessionHandle(a)),(n.touchSessionPresence||n.detachSessionPresence)&&(p.presence={touch:m=>n.touchSessionPresence?.(a,m),detach:m=>n.detachSessionPresence?.(a,m)}),n.endDedicatedSession&&(p.endSession=()=>n.endDedicatedSession(a)),n.onSessionEnd&&(p.onSessionEnd=m=>n.onSessionEnd(a,m)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Ms(n,e,t){let r=Ns(n,t);return{resolve:async(s,i,o)=>{if(e!==void 0){let a=s.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw ce(401,"invalid local proxy api key")}return ya(r,fa(s),i,ha(s),o)}}}export{Ot as a,ur as b,ka as c,ht as d,lr as e,Gs as f,Ta as g,Oa as h,Ii as i,Er as j,mt as k,_n as l,wn as m,Ns as n,fa as o,ha as p,ud as q,ya as r,Ms as s,fs as t,ne as u,rl as v,Mn as w,dl as x,cl as y,pl as z,ml as A,fl as B,Is as C,$s as D,ua as E,Jl as F};
@@ -1,2 +1,2 @@
1
- import{c as D}from"./chunk-3JZAWWVV.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
1
+ import{c as D}from"./chunk-6WTMEJZS.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
2
2
  `)}return c=f,h=t(),f},y=()=>c===null||t()-h>=s;return{rows(){return y()?(u||(u=_().finally(()=>{u=null})),u):Promise.resolve(c)},close(){c=null,u=null}}}export{G as a,X as b,Y as c,J as d,ne as e};
@@ -373,6 +373,17 @@ interface RealtimeBinding<S = unknown> {
373
373
  intent?: 'transcription';
374
374
  /** True when `session` is a resumed authorized session (vs a fresh private one). */
375
375
  resumed?: boolean;
376
+ /**
377
+ * THE EXPLICIT-PRESENCE RELAY (owner GO 2026-11-16): the connection stamps
378
+ * ONE caller's presence activity on the bound pooled session (`touch`, per
379
+ * `session.presence` frame and — EXPEDIENT — every client event) and
380
+ * removes it at socket close (`detach`). Absent ⇒ the composition wired no
381
+ * presence seam; the connection sends nothing.
382
+ */
383
+ presence?: {
384
+ touch(connId: string): void;
385
+ detach(connId: string): void;
386
+ };
376
387
  /**
377
388
  * The backend's OWN turn/transcript lane — the §5 `stt` named stream
378
389
  * (urun.serve.transcribe_bridge wire shape: `t` = delta/final/turn_start/
@@ -2897,6 +2908,20 @@ interface ProxyClients {
2897
2908
  * the caller's frame with the standard `unknown_event` error.
2898
2909
  */
2899
2910
  endDedicatedSession?(handle: string): Promise<unknown> | unknown;
2911
+ /**
2912
+ * THE EXPLICIT-PRESENCE SEAMS (owner GO 2026-11-16, hub-primary): a seat is
2913
+ * held only while a client is explicitly present. `touchSessionPresence`
2914
+ * records one caller connection's activity on the handle's bound pooled
2915
+ * session (`{"type":"session.presence"}` frames — and, EXPEDIENT until a
2916
+ * minimum SDK version ships the frame, ANY client-originated realtime
2917
+ * event); `detachSessionPresence` removes ONE caller's contribution at its
2918
+ * socket close, detaching the pooled session's `$presence` state when no
2919
+ * still-active caller remains. Optional at the seam: a composition that
2920
+ * wires none keeps today's behavior (presence rides the session's own
2921
+ * activity clock alone).
2922
+ */
2923
+ touchSessionPresence?(handle: string, connId: string): void;
2924
+ detachSessionPresence?(handle: string, connId: string): void;
2900
2925
  /**
2901
2926
  * THE REALTIME LANE'S BILLING IDENTITY (session-time billing, DDR
2902
2927
  * addendum): the {@link TurnCatalogIdentity} the model's dial resolves,
@@ -118,6 +118,11 @@ interface RealtimeBinding<S = unknown> {
118
118
 
119
119
  resumed?: boolean;
120
120
 
121
+ presence?: {
122
+ touch(connId: string): void;
123
+ detach(connId: string): void;
124
+ };
125
+
121
126
  turns?: (signal?: AbortSignal) => AsyncIterable<{
122
127
  kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
123
128
  text?: string;
@@ -717,6 +722,9 @@ interface ProxyClients {
717
722
 
718
723
  endDedicatedSession?(handle: string): Promise<unknown> | unknown;
719
724
 
725
+ touchSessionPresence?(handle: string, connId: string): void;
726
+ detachSessionPresence?(handle: string, connId: string): void;
727
+
720
728
  realtimeBillingIdentityFor?(model: string | undefined): Promise<TurnCatalogIdentity>;
721
729
 
722
730
  speechSessionHandle?(model: string | undefined): Promise<string>;