@urun-sh/openai 0.6.55 → 0.6.56

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,4 +1,4 @@
1
- import{a as te}from"./chunk-CAR4AEQJ.js";import{e as pe,f as W,g as fe,h as me}from"./chunk-PPEND4SP.js";import{d as ee,g as V,h as ne,q as oe}from"./chunk-MYNG74AX.js";import{a as ge,b as G}from"./chunk-KNWFUWXY.js";import{c as ue}from"./chunk-Z74YK7AL.js";import{a as H}from"./chunk-526ZJAOW.js";import{b as Z,d as j}from"./chunk-AWCC5WRB.js";import{b as se,c as re,d as ie,g as ae,j as F,m as B,n as _,o as ce,r as R,s as L,t as de,u as le}from"./chunk-N3Y2GDQK.js";import{c as b}from"./chunk-YSFSRI3D.js";b();import{App as J,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Be,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as We,SessionFailedError as z}from"@urun-sh/core";b();import{SessionFailedError as _e}from"@urun-sh/core";var q=2;function Le(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Te(e){let t=e?.type;return t==="response.completed"||t==="error"}function ye(e){return async function(r,i){let a=await e.sessionFor(r.model);return(async function*(){for(let l=1;l<=q;l++){let{app:g,entry:y,identity:S}=l===1?a:await e.sessionFor(r.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:S});let p=!1,u=!1;try{let f=await e.createStream(y,r);for await(let m of f){if(Te(m)&&(p=!0),Le(m)){if(l>1)continue}else u=!0;yield m}}catch(f){if(f instanceof _e&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,f)}catch{}throw f}if(l<q&&!u){await e.evict(g,y);continue}throw f}if(p)return;if(l<q&&!u){await e.evict(g,y);continue}return}})()}}import{randomUUID as Oe}from"crypto";b();import{request as Fe}from"http";var Re="/pooler/v1/inference",k=class extends Error{constructor(r,i,a,c){super(a);this.status=r;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Me=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let t=e.messages?.find(r=>r.role==="system"||r.role==="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content)},Ne=e=>{let t=e.messages?.find(r=>r.role!=="system"&&r.role!=="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let r=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(r===void 0)return;if(typeof r=="string")return r;if(r!==null&&typeof r=="object"&&"content"in r){let i=r.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(r)}},he=e=>new Promise((t,r)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>t(Buffer.concat(i).toString("utf8"))),e.on("error",r)}),De=async e=>{let t="pooler_error",r=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await he(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(t=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(r=a.message)}}catch{}return new k(e.status,t,r,e.retryAfterSeconds)};async function xe(e,t,r,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Re}`),l=JSON.stringify({region:e.region,model:i,request_id:r,streaming:a,payload:t,affinity:{systemPrompt:Me(t),firstMessage:Ne(t)}});return new Promise((g,y)=>{let S=Fe({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},p=>{let u=Number(p.headers["retry-after"]??"");g({status:p.statusCode??0,retryAfterSeconds:Number.isFinite(u)?u:void 0,body:p})});S.on("error",p=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${p.message}`))),S.end(l)})}var we=e=>{if(!e.startsWith("data: "))return null;let t=e.slice(6).trim();if(t===""||t==="[DONE]")return null;let r;try{r=JSON.parse(t)}catch{return null}if(r===null||typeof r!="object")return null;let i=r;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*Ce(e){let t="";for await(let i of e.body)for(t+=String(i);;){let a=t.indexOf(`
1
+ import{a as te}from"./chunk-CAR4AEQJ.js";import{e as pe,f as W,g as fe,h as me}from"./chunk-MBIJRS4O.js";import{d as ee,g as V,h as ne,q as oe}from"./chunk-MYNG74AX.js";import{a as ge,b as G}from"./chunk-KNWFUWXY.js";import{c as ue}from"./chunk-6R3TCKOH.js";import{a as H}from"./chunk-526ZJAOW.js";import{b as Z,d as j}from"./chunk-AWCC5WRB.js";import{b as se,c as re,d as ie,g as ae,j as F,m as B,n as _,o as ce,r as R,s as L,t as de,u as le}from"./chunk-N3Y2GDQK.js";import{c as b}from"./chunk-YSFSRI3D.js";b();import{App as J,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Be,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as We,SessionFailedError as z}from"@urun-sh/core";b();import{SessionFailedError as _e}from"@urun-sh/core";var q=2;function Le(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Te(e){let t=e?.type;return t==="response.completed"||t==="error"}function ye(e){return async function(r,i){let a=await e.sessionFor(r.model);return(async function*(){for(let l=1;l<=q;l++){let{app:g,entry:y,identity:S}=l===1?a:await e.sessionFor(r.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:S});let p=!1,u=!1;try{let f=await e.createStream(y,r);for await(let m of f){if(Te(m)&&(p=!0),Le(m)){if(l>1)continue}else u=!0;yield m}}catch(f){if(f instanceof _e&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,f)}catch{}throw f}if(l<q&&!u){await e.evict(g,y);continue}throw f}if(p)return;if(l<q&&!u){await e.evict(g,y);continue}return}})()}}import{randomUUID as Oe}from"crypto";b();import{request as Fe}from"http";var Re="/pooler/v1/inference",k=class extends Error{constructor(r,i,a,c){super(a);this.status=r;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Me=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let t=e.messages?.find(r=>r.role==="system"||r.role==="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content)},Ne=e=>{let t=e.messages?.find(r=>r.role!=="system"&&r.role!=="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let r=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(r===void 0)return;if(typeof r=="string")return r;if(r!==null&&typeof r=="object"&&"content"in r){let i=r.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(r)}},he=e=>new Promise((t,r)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>t(Buffer.concat(i).toString("utf8"))),e.on("error",r)}),De=async e=>{let t="pooler_error",r=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await he(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(t=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(r=a.message)}}catch{}return new k(e.status,t,r,e.retryAfterSeconds)};async function xe(e,t,r,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Re}`),l=JSON.stringify({region:e.region,model:i,request_id:r,streaming:a,payload:t,affinity:{systemPrompt:Me(t),firstMessage:Ne(t)}});return new Promise((g,y)=>{let S=Fe({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},p=>{let u=Number(p.headers["retry-after"]??"");g({status:p.statusCode??0,retryAfterSeconds:Number.isFinite(u)?u:void 0,body:p})});S.on("error",p=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${p.message}`))),S.end(l)})}var we=e=>{if(!e.startsWith("data: "))return null;let t=e.slice(6).trim();if(t===""||t==="[DONE]")return null;let r;try{r=JSON.parse(t)}catch{return null}if(r===null||typeof r!="object")return null;let i=r;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*Ce(e){let t="";for await(let i of e.body)for(t+=String(i);;){let a=t.indexOf(`
2
2
 
3
3
  `);if(a===-1)break;let c=t.slice(0,a);t=t.slice(a+2);let l=we(c);l!==null&&(yield l)}let r=we(t);r!==null&&(yield r)}async function on(e,t,r,i){let a=Z(t,r,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await xe(e,a,r,c,t.stream===!0);if(l.status>=400)throw await De(l);let g=t.stream===!0?j(r,Ce(l)):await Ue(l,r);return(async function*(){yield{type:"response.created",response:{id:`resp_${r}`,status:"in_progress"}},yield*g})()}async function Ue(e,t){let r=await he(e.body),i=null;try{let c=JSON.parse(r);c!==null&&typeof c=="object"&&(i=c)}catch{i=null}if(i===null)throw new k(502,"pooler_bad_body","the pooler answered a non-object body");let a=i;return j(t,(async function*(){yield a})())}b();import{encodeStreamEnvelope as Se}from"@urun-sh/core";var $e="audio";function Pe(e){let t=e.streamEndpoint($e);return{sessionId:e.id,appendInputAudio(r,i){let a=Buffer.from(r,"base64");if(a.byteLength!==0){if(i===void 0){t.send(Se(new Uint8Array(a)));return}t.send(Se({pcm16:r,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}b();import{encodeStreamEnvelope as je}from"@urun-sh/core";var Ve="rt-video-in";function ve(e){let t=e.streamEndpoint(Ve);return{sendInputFrame:async r=>{t.send(je(r))}}}var Ge=0,qe=4,Je=4;function Fn(e,t){let r=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let S=Number.parseInt(y,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):Ge;if(!Number.isInteger(a)||a<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=r("URUN_DECISION_POOL_MAX",Math.max(a,qe));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:r("URUN_DECISION_POOL_INFLIGHT_CAP",Je),replicaId:(e.URUN_REPLICA_ID??"").trim()||t||"proxy"}}function Rn(e){let t=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!t)return W;let r=Number.parseInt(t,10);if(!Number.isInteger(r)||r<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return r*1e3}function K(e,t,r,i){let a=e[r];if(typeof a!="function")throw new Error(`app "${t}" has no function "${r}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${t}" function "${r}" returned a session without end()`);return c}function ke(e,t,r,i){let{baseUrl:a,orgId:c,auth:l}=e,g=t.fnName??e.fnName,y=e.sessionStartOptions?.(r),S={...t.sharedApp?{sharedApp:!0}:{},...y,...i,presenceIdleMs:3e4},p=h=>({session:h,responses:new H(h),gone:ge(h,r)});if(l.lane==="jwt"){let h=J(t.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return p(K(h,t.appSlug,g,S))}if(l.lane==="machine"||l.lane==="user"){let h=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:I}=l,C=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),T=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(h,{baseUrl:I,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:C,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(T,t.appSlug,g,S))}let{apiKey:u,gatewayUrl:f}=l,m=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),w=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(u,{baseUrl:f,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:m,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(w,t.appSlug,g,S))}function Ie(e){let t=e.session.id;if(typeof t!="string"||t.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return t}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let t=e.status.error?.httpStatus,r=e.status.error?.code;return t===410||t===409&&(r==="cancelled"||r==="expired")?!0:r==="client_ended"}var Ke=new Set(["error","paused"]);function Mn(e){let{auth:t,catalog:r}=e,i=null,a=(l,g)=>{let y=ke(e,l,g);return e.onSessionOpen&&typeof y.session.id=="string"&&y.session.id!==""&&e.onSessionOpen(g,y.session.id),y.gone.onGone(()=>{i?.evict(g,y)}),y},c=new le({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,callerOrgId:e.orgId,openSession:a,closeSession:async l=>{if(l.gone.dispose(),l.audioDispose?.(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:t.lane==="api-key"?()=>ce({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:e.catalogRows??(r?()=>te(r):null),listPrices:r?()=>ie(r):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return se(l)}:t.lane==="api-key"?()=>re({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,sessionKey:Ie});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},L({appSlug:e.defaultApp}))),c}function Nn(e,t){let r=e.decisionPool;if(!r)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=r.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=p=>{process.stderr.write(`[decision-pool] ${p}
4
4
  `)},y=(p,u)=>{let f=a.get(u);if(f)return f;let m=new pe({min:r.min,max:r.max,idleGraceMs:r.idleGraceMs,inFlightCap:r.inFlightCap,replicaId:i,onLease:w=>w.session.activity?.(),openSlot:async w=>{let h=ke(e,p,u,{concurrencyKey:w.concurrencyKey});return h.gone.onGone(I=>I.bindingLost?m.evict(h):m.markSessionDead(h)),await x(h.session),g(`slot attached pool=${u} slot=${w.concurrencyKey} session=${h.session.id??"(no id)"}`),h},closeSlot:async w=>{w.gone.dispose(),w.audioDispose?.(),await w.session.end()},onDetach:(w,h)=>g(`slot detached pool=${u} slot=${w.concurrencyKey} reason=${h}`),terminalOpenFailure:w=>w instanceof z&&X(w)});return c.set(u,{target:p,env:r}),a.set(u,m),m},S=async(p,u)=>{let f=c.get(u);if(f)try{let m=await t.poolTuningFor(p);y(p,u).retune({min:m?.min??f.env.min,max:m?.max??f.env.max,inFlightCap:m?.in_flight_cap??f.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){g(`pool tuning refresh failed pool=${u} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let p={appSlug:e.defaultApp};await y(p,L(p)).boot()},async sessionFor(p){let u=await t.resolveTargetFor(p),f=L(u),m=y(u,f);await S(u,f);let w=await m.acquire({timeoutMs:m.requestWaitMs}),h=l.get(w.entry)??[];return h.push(w),l.set(w.entry,h),{app:f,entry:w.entry,identity:de(u)}},async warmFor(p){let u=await t.resolveTargetFor(p);await y(u,L(u)).boot()},end(p){let u=l.get(p)?.shift();u&&(l.get(p)?.length===0&&l.delete(p),u.release())},evict(p){for(let u of a.values())u.evict(p)},markSessionDead(p){for(let u of a.values())u.markSessionDead(p)},reap(){for(let[p,{target:u}]of c)S(u,p).then(()=>{let f=a.get(p);f&&f.reap()})},async pingReady(p){for(let u of a.values())if(await u.pingReady(p))return!0;return!1},stats(){return[...a.entries()].map(([p,u])=>({poolKey:p,...u.stats()}))},async drain(p){await Promise.all([...a.values()].map(u=>u.drain({timeoutMs:p})))},async close(){await Promise.all([...a.values()].map(p=>p.close()))}}}function ze(e){return We(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:Be:be}async function x(e,t){let r=e.whenLive;if(typeof r!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await r.call(e,{timeout:ze(e.phase),signal:t})}async function Xe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}async function Ae(e){let t=e.phase?.name;if(t==="live"||t==="paused"){if(typeof e.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");e.detach();return}if(typeof e.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await e.end()}function D(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Dn(e,t=ne,r,i,a=W,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,S=new WeakMap,p=new Map,u=new WeakMap,f=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},m="lane",w=n=>{let s=_(n);if(!c||!s||s.app!==m)return null;let o=c.entryFor(s.key);if(!o)throw new F(`the lane behind this handle (${s.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:s.key,entry:o}},h=async n=>w(n)?.entry??(await e.sessionForHandle(n)).entry,I=n=>{let s=l.get(n);if(!s){let o={waiting:0,gone:new AbortController};u.set(n,o),s=(async()=>{if(await x(n.session,o.gone.signal),o.gone.signal.aborted)throw D(o.gone.signal);u.get(n)===o&&u.delete(n);let d=await ee(n.session,await t());return Object.assign(d,{sessionId:n.session.id})})(),l.set(n,s),s.then(d=>{l.get(n)===s&&(n.audioDispose=()=>d.dispose())},()=>{}),s.catch(()=>{l.get(n)===s&&l.delete(n)}),s.then(()=>{u.get(n)===o&&u.delete(n)},()=>{u.get(n)===o&&u.delete(n)})}return s},C=n=>{let s=S.get(n);return s||(s=(async()=>{let o=await I(n);return{appendInputAudio:(d,v)=>o.appendInputAudio(d,v),onOutputAudio:d=>o.onOutputAudio(d),sessionId:f(n)}})(),S.set(n,s),s.catch(()=>{S.get(n)===s&&S.delete(n)})),s},T=async(n,s,o,d=!1)=>{let v=()=>d?Ae(n.session):Xe(n.session);if(o?.aborted){let O=u.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await v().catch(()=>{}),D(o)}let E=s(n),P=u.get(n);return P!==void 0&&P.waiting++,o===void 0?E:new Promise((O,A)=>{let Q=()=>{P!==void 0&&--P.waiting===0&&u.get(n)===P&&(P.gone.abort(),u.delete(n),l.delete(n),S.delete(n),v().catch(()=>{})),A(D(o))};o.addEventListener("abort",Q,{once:!0});let Y=()=>o.removeEventListener("abort",Q);E.then($=>{Y(),O($)},$=>{Y(),A($)})})},U=async(n,s,o)=>{try{return await o}catch(d){throw(d instanceof F||d instanceof z&&X(d))&&(e.evict(n,s),d instanceof z&&r?.(n,d.kind==="never-live"?"never-live":"create-failed")),d}};return{createResponse:ye({sessionFor:c?async n=>{let s=await e.resolveTargetFor(n);if(s.sharedApp)try{let o=await c.sessionFor(n,s);return{app:o.app,entry:o.entry,identity:o.identity}}catch(o){if(o instanceof ue)return i?i.sessionFor(n):e.sessionFor(n);if(o instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${o.name} ${o.code}: ${o.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw o}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>f(n),evict:(n,s)=>{c&&c.owns(s)?c.evict(s):i?i.evict(s):e.evict(n,s)},onAdmissionVerdict:(n,s,o)=>{X(o)&&(c&&c.owns(s)?c.evict(s):i?i.markSessionDead(s):e.evict(n,s),r?.(n,o.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>{try{await x(n.session);let o=fe(G(await n.responses.responses.create(s),n.gone),a);if(!i&&!c)return o;let d=n;return(async function*(){try{yield*o}catch(E){throw me(E)&&(c&&c.owns(d)?c.evict(d):i&&(E instanceof F&&!E.bindingLost?i.markSessionDead(d):i.evict(d))),E}finally{c&&c.owns(d)?c.release(d):i?.end(d)}})()}catch(o){throw c&&c.owns(n)?c.release(n):i&&i.end(n),o}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,s)=>e.supportsImages(n,s),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,s)=>{let{app:o,entry:d}=await e.sessionFor(n);return await U(o,d,T(d,I,s))},openAudioOn:async(n,s,o,d)=>{let v=w(n);if(v){let A=v.entry.session;return Pe(A)}let{app:E,entry:P}=await e.sessionForHandle(n);if(d&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;d({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let O=_(n)?.app.startsWith(R)??!1;return await U(E,P,T(P,C,s,O))},openTurnsOn:async function*(n,s){if(s?.aborted)throw D(s);let o=await h(n);yield*ae(o.session,s)},openVideoOn:async n=>{let s=w(n);if(s)return ve(s.entry.session);let{entry:o}=await e.sessionForHandle(n),d=g.get(o);return d||(d=V(o.session),g.set(o,d)),d},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),o=g.get(s);return o||(o=V(s.session),g.set(s,o)),o},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),o=y.get(s);return o||(o=oe(s.session),y.set(s,o)),o},sessionHandle:async n=>{if(c){let s=await e.resolveTargetFor(n);if(s.sharedApp){let o=await c.sessionFor(n,s),d=f(o.entry);if(d===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return B(m,d)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:o,entry:d}=await e.dedicatedSessionFor(n);return B(o,Ie(d))},touchSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);o||(o=new Map,p.set(n,o)),o.set(s,Date.now());let d=null;try{d=await h(n)}catch{return}d.session.activity?.()})()},detachSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);if(o?.delete(s),o&&o.size===0&&p.delete(n),o&&o.size>0)return;let d=null;try{d=await h(n)}catch{return}d.session.presenceDetach?.()})()},releaseSessionHandle:n=>{let s=_(n);if(!s)return;if(s.app.startsWith(R)){(async()=>{let d=null;try{d=(await e.sessionForHandle(n)).entry}catch{return}await Ae(d.session).catch(()=>{}),await e.evict(s.app,d)})();return}if(!c||s.app!==m)return;let o=c.entryFor(s.key);o&&c.release(o)},endDedicatedSession:async n=>{let s=_(n);if(!s||!s.app.startsWith(R))return;let o=null;try{o=(await e.sessionForHandle(n)).entry}catch{return}if(typeof o.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let d=await o.session.end();return await e.evict(s.app,o),d},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:o}=await e.sessionForHandle(n);await e.evict(s,o)},createResponseOn:async(n,s,o)=>{let d=await h(n);await x(d.session);let v=o!==void 0&&w(n)?new H({...d.session,consumerId:o},{sessionTag:o}):d.responses;return G(await v.responses.create(s),d.gone)},onSessionEnd:async(n,s)=>{let o=w(n);if(o)return o.entry.gone.onGone(P=>s({timeLeftMs:null,reason:P.message}));let{entry:d}=await e.sessionForHandle(n),v=d.session;if(typeof v.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return v.onPhase(P=>{if(E||!Ke.has(P.name))return;E=!0;let O=v.endsAt??null;s({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}export{k as a,on as b,Fn as c,Rn as d,Mn as e,Nn as f,Dn as g};
@@ -1,4 +1,4 @@
1
- import{a as Me,b as Ct,c as xt,e as De,f as Mt,g as He}from"./chunk-HLSJAQHY.js";import{A as Ot,B as Tt,C as Pt,D as Ut,E as Nt,b as ct,d as dt,i as ht,j as pt,l as mt,m as yt,n as wt,o as bt,p as vt,q as _t,r as St,t as kt,u as de,v as Et,w as Rt,x as Lt,y as It,z as At}from"./chunk-PPEND4SP.js";import{a as lt}from"./chunk-KV3UXLNF.js";import{a as Ht,e as Wt}from"./chunk-BVM4ZQ2Y.js";import{a as $t}from"./chunk-KNWFUWXY.js";import{a as ut,b as le,c as ft,o as gt,p as ce}from"./chunk-Z74YK7AL.js";import{a as Dt,c as te,e as We}from"./chunk-XNRPTMSL.js";import{a as ot}from"./chunk-526ZJAOW.js";import{e as it,j as ie,p as at,q as ae,r as xe}from"./chunk-N3Y2GDQK.js";import{c as T}from"./chunk-YSFSRI3D.js";T();import{Counter as J,Gauge as ue,Histogram as fe,Registry as Un,collectDefaultMetrics as Nn}from"@prometheus-io/client";import{createServer as Cn}from"http";var Ds=9464,Ft="/metrics",he="(other)",$n="(none)",xn=64,Mn=128,Dn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",kt,Rt,it],Hn=new Set(Dn);function Wn(t){return Hn.has(t)?t:he}function Fn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?$n:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,he):(this.admitted.add(e),e):he}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ge=class{registry=new Un;modelLabel=new pe(xn);orgLabel=new pe(Mn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ue({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new J({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new fe({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new fe({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new J({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new J({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new J({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Lt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ue({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},It()),this.ledgerQueue.set({measure:"oldest_age_seconds"},At()/1e3)}}),this.labelCardinality=new ue({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new J({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new ue({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new fe({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new fe({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new J({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new J({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&Nn({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=Wn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),a=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?he:e.method,status_class:Fn(e.status),stream:l,model:o,org:a}),this.duration.observe({lane:n,stream:l,model:o,org:a},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:a},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Gt(t){return Cn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ft){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ft}
1
+ import{a as Me,b as Ct,c as xt,e as De,f as Mt,g as He}from"./chunk-NMNR3SQ5.js";import{A as Ot,B as Tt,C as Pt,D as Ut,E as Nt,b as ct,d as dt,i as ht,j as pt,l as mt,m as yt,n as wt,o as bt,p as vt,q as _t,r as St,t as kt,u as de,v as Et,w as Rt,x as Lt,y as It,z as At}from"./chunk-MBIJRS4O.js";import{a as lt}from"./chunk-KV3UXLNF.js";import{a as Ht,e as Wt}from"./chunk-B3GQYAJ5.js";import{a as $t}from"./chunk-KNWFUWXY.js";import{a as ut,b as le,c as ft,o as gt,p as ce}from"./chunk-6R3TCKOH.js";import{a as Dt,c as te,e as We}from"./chunk-XNRPTMSL.js";import{a as ot}from"./chunk-526ZJAOW.js";import{e as it,j as ie,p as at,q as ae,r as xe}from"./chunk-N3Y2GDQK.js";import{c as T}from"./chunk-YSFSRI3D.js";T();import{Counter as J,Gauge as ue,Histogram as fe,Registry as Un,collectDefaultMetrics as Nn}from"@prometheus-io/client";import{createServer as Cn}from"http";var Ds=9464,Ft="/metrics",he="(other)",$n="(none)",xn=64,Mn=128,Dn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",kt,Rt,it],Hn=new Set(Dn);function Wn(t){return Hn.has(t)?t:he}function Fn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?$n:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,he):(this.admitted.add(e),e):he}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ge=class{registry=new Un;modelLabel=new pe(xn);orgLabel=new pe(Mn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ue({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new J({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new fe({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new fe({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new J({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new J({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new J({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Lt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ue({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},It()),this.ledgerQueue.set({measure:"oldest_age_seconds"},At()/1e3)}}),this.labelCardinality=new ue({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new J({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new ue({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new fe({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new fe({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new J({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new J({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&Nn({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=Wn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),a=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?he:e.method,status_class:Fn(e.status),stream:l,model:o,org:a}),this.duration.observe({lane:n,stream:l,model:o,org:a},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:a},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Gt(t){return Cn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ft){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ft}
2
2
  `);return}let s=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(s)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
3
3
  `);return}n.end()})})}T();import{createHash as Kt}from"crypto";import{createServer as Gn}from"http";var Bs=9465,Bn="x-urun-key-id",Kn="x-urun-key-fingerprint",jn="urun-ratelimit-bucket:",Jn="urun-ratelimit-tier:",Bt="anonymous",zn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function qn(t){return Kt("sha256").update(`${jn}${t}`).digest("hex")}function Vn(t){return Kt("sha256").update(`${Jn}${t}`).digest("hex")}function Yn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return zn.test(n)?n:null}function jt(){return Gn((t,e)=>{let n=Yn(t.headers.authorization);e.setHeader(Bn,n===null?Bt:qn(n)),e.setHeader(Kn,n===null?Bt:Vn(n)),e.writeHead(200),e.end()})}T();import{createClientToken as Qn,ClientTokenError as Jt}from"@urun-sh/core";import{createPublicKey as Xn,verify as Zn}from"crypto";var zt="urun-session-gateway",er="machine",tr=3e5;function Yt(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var N=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},q=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},G=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function be(t){let e=(t??"").trim();if(e==="")throw new N("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new N("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var nr=60,rr=6e4,sr=4096;function or(t){return t===401||t===403}var re=class{constructor(e){this.opts=e;this.mint=e.mint??Qn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new N("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<rr)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let s,o;try{let a=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:nr});s=a.orgId,o={...a.billingAudience!==void 0?{billingAudience:a.billingAudience}:{},...a.creditsAdmissionOk!==void 0?{creditsAdmissionOk:a.creditsAdmissionOk}:{},...a.creditsRefusalReason!==void 0?{creditsRefusalReason:a.creditsRefusalReason}:{}}}catch(a){throw a instanceof Jt&&a.status===402?(this.cache.delete(e),new q(a.code==="spend_cap_reached"||a.code==="insufficient_credits"?a.code:void 0)):a instanceof Jt&&or(a.status)?(this.cache.delete(e),new N(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new G(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${a instanceof Error?a.message:String(a)}`)}if(!s)throw new G(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=sr){let a=this.cache.keys().next();a.done||this.cache.delete(a.value)}return this.cache.set(e,{orgId:s,at:this.now(),...o}),{apiKey:e,orgId:s,credential:n,...o}}clear(){this.cache.clear()}};function ne(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function qt(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var me=class{constructor(e,n,r,s){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=s}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof G?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<tr)return r.keys;let s=this.inFlight.get(e);if(s!==void 0)return s;let o=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,o);let a=await o;return this.entries.set(e,{keys:a,at:this.now()}),a}async keyFor(e,n){let r=await this.keys(e,!1),s=n===""?void 0:r.find(o=>o.kid===n&&qt(o));return s===void 0&&(r=await this.keys(e,!0),s=n===""?void 0:r.find(o=>o.kid===n&&qt(o))),s}};function Qt(t,e,n){try{let r=Xn({key:n,format:"jwk"});return Zn("RSA-SHA256",t,r,e)}catch{return!1}}var ye=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new me(e.fetchImpl??fetch,e.now??Date.now,n=>new G("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new N("malformed machine token");let o,a;try{o=ne(n),a=ne(r)}catch{throw new N("malformed machine token")}if(o.alg!=="RS256")throw new N(`machine token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new N(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(a.aud!==zt)throw new N(`machine token audience must be ${zt} (got ${JSON.stringify(a.aud??null)})`);if(a.token_use!==er)throw new N(`bearer is a ${JSON.stringify(String(a.token_use??""))} token, not a machine token`);let h=typeof a.org_id=="string"?a.org_id:"";if(h==="")throw new N("machine token carries no org_id \u2014 no tenancy to route by");let f=typeof a.exp=="number"?a.exp:0;if(f<=Math.floor(this.now()/1e3))throw new N("machine token is expired \u2014 re-mint and retry");let m=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,i);if(m===void 0)throw new N(`machine token kid ${JSON.stringify(i)} is not in the machine issuer's JWKS`);let O=Buffer.from(`${n}.${r}`,"ascii"),P=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qt(O,P,m))throw new N("machine token signature failed verification");if(f<=Math.floor(this.now()/1e3))throw new N("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:h,credential:"machine"}}},ir="https://api.workos.com/sso/jwks/";function ar(t){return`${ir}${t.slice(t.lastIndexOf("/")+1)}`}var Fe=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new me(e.fetchImpl??fetch,this.now,n=>new G("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Yt(e))return!1;try{let n=ne(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new N("malformed user token");let o,a;try{o=ne(n),a=ne(r)}catch{throw new N("malformed user token")}if(o.alg!=="RS256")throw new N(`user token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new N(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let h=typeof a.org_id=="string"?a.org_id:"";if(h==="")throw new N("user token carries no org_id \u2014 no tenancy to route by");let f=typeof a.sub=="string"?a.sub:"",m=typeof a.exp=="number"?a.exp:0;if(m<=Math.floor(this.now()/1e3))throw new N("user token is expired \u2014 re-authenticate and retry");let O=await this.cache.keyFor(ar(l),i);if(O===void 0)throw new N(`user token kid ${JSON.stringify(i)} is not in the WorkOS issuer's JWKS`);let P=Buffer.from(`${n}.${r}`,"ascii"),c=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qt(P,c,O))throw new N("user token signature failed verification");if(m<=Math.floor(this.now()/1e3))throw new N("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:h,credential:"user",subject:f}}},lr=5e3,cr=1500,dr=4096,z=class extends Error{status=403;detail;constructor(e,n){super(e),this.name="MembershipRefusalError",this.detail=n}};function Vt(){return new z("this account is not an active member of the organization \u2014 the membership may have been removed; sign out and sign back in")}var Ge=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now,this.timeoutMs=e.timeoutMs??cr}opts;cache=new Map;fetchImpl;now;timeoutMs;async assertActive(e,n){if(n==="")throw new z("the user token carries no subject \u2014 organization membership cannot be confirmed");let r=`${e}\0${n}`,s=this.cache.get(r);if(s!==void 0&&this.now()-s.at<lr){if(!s.active)throw Vt();return}let o=!1,a;try{let i=await this.fetchImpl(`${this.opts.url}/membership-check`,{method:"POST",headers:{authorization:`Bearer ${this.opts.token}`,"content-type":"application/json"},body:JSON.stringify({org_id:e,subject:n}),signal:AbortSignal.timeout(this.timeoutMs)});if(i.status!==200)a=`membership-check answered HTTP ${i.status}`;else try{let l=await i.json();l===null||typeof l!="object"||Array.isArray(l)||!("active"in l)||typeof l.active!="boolean"?a="membership-check answered a malformed body (expected {active: boolean})":o=l.active}catch(l){a=`membership-check answered a body that is not JSON (${l instanceof Error?l.message:String(l)})`}}catch(i){a=`membership-check failed (${i instanceof Error?i.message:String(i)})`}if(a!==void 0)throw new z("organization membership for this account could not be confirmed \u2014 try again shortly",a);if(this.cache.size>=dr){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}if(this.cache.set(r,{active:o,at:this.now()}),!o)throw Vt()}},we=class{verifier;bindings;memberGate;warnedGateDisabled=!1;constructor(e){this.verifier=new Fe({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new re({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}}),this.memberGate=e.memberGate!==void 0?new Ge(e.memberGate):null}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e);this.memberGate!==null?await this.memberGate.assertActive(n.orgId,n.subject):this.warnedGateDisabled||(this.warnedGateDisabled=!0,process.stderr.write(`[member-gate] member gate disabled \u2014 removed-member window remains open
4
4
  `));let r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new N("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Be(t,e,n,r){if(Yt(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}T();var ur=8080,Ke="serve",Qs="0.0.0.0";function fr(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Xs(t=process.env){let e=(t.PORT??"").trim(),n=e===""?ur:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=gt(ce(fr(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),s=(t.URUN_API_URL??"").trim(),o=s?ce(s,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,a=(t.URUN_CATALOG_URL??"").trim(),i=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!a!=!!i)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=a?{catalogUrl:ce(a,"URUN_CATALOG_URL"),anonKey:i}:null,h=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),f=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!h!=!!f)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let m=h?{keyId:f,key:h}:void 0,O={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},P=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],c=P.filter((v,A)=>Object.values(O)[A]==="");if(c.length!==0&&c.length!==P.length)throw new Error(`${P.join(", ")} must be set together (or all left unset) \u2014 missing: ${c.join(", ")}, which would half-configure the lane plane`);let y=c.length===0?O:void 0,_={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},k=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=k.filter((v,A)=>Object.values(_)[A]==="");if(g.length!==0&&g.length!==k.length)throw new Error(`${k.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let E=g.length===0?_:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},d=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=d.filter((v,A)=>Object.values(p)[A]==="");if(S.length!==0&&S.length!==d.length)throw new Error(`${d.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let R=p.issuers.split(",").map(v=>v.trim()).filter(v=>v!=="");if(R.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let w=Number(p.tokenTtlS);if(S.length===0&&(!Number.isFinite(w)||w<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let I=S.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:R,tokenTtlS:w}:void 0,U=(t.URUN_WORKOS_ISSUERS??"").trim(),$=U.split(",").map(v=>v.trim()).filter(v=>v!=="");if(U!==""&&$.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let v of $){let A;try{A=new URL(v)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(v)}`)}if(A.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${v}) \u2014 the issuer is the user rung's trust root`)}let u=(t.URUN_CONTROL_PLANE_URL??"").trim(),b=(t.URUN_CONTROL_PLANE_TOKEN??"").trim(),L=u!==""&&b!==""?{url:u.replace(/\/+$/,""),token:b}:void 0;return{port:n,baseUrl:r,apiUrl:o,catalog:l,ledgerSigning:m,lane:y,pooler:E,machine:I,memberGate:L,...$.length>0?{userIssuers:$}:{}}}T();import{createHash as hr,randomUUID as Xt}from"crypto";var pr=512;function ve(t){return`urun-inference-proxy-${hr("sha256").update(t).digest("hex").slice(0,32)}`}var _e=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let s=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;if(o===void 0)return s;let a=this.opts.lanes;return Object.assign(Object.create(s),{createResponse:async(i,l)=>{if(a!==void 0&&r!==void 0&&(await r.resolveTargetFor(i.model).catch(()=>null))?.sharedApp)return await s.createResponse(i,l);let h=`px_${Xt()}`;return Ct(o,i,h,h)}})}build(e){if(this.opts.build){let o=this.opts.build(e);return o.decision&&this.ensureDecisionReaper(),{router:o.router,clients:this.label(o.clients,e,o.router),decision:o.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ke,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:xt(process.env,process.env.HOSTNAME)??void 0},r=De(n),s=n.decisionPool?Mt(n,r):null;return s&&this.ensureDecisionReaper(),{router:r,clients:this.label(He(r,void 0,void 0,s??void 0,void 0,this.opts.lanes),e,r),decision:s??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=pr;){let s=this.tenants.entries().next();if(s.done)break;let[o,a]=s.value;this.tenants.delete(o),a.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let s=[r.router.closeAll().catch(o=>{n.push(String(o instanceof Error?o.message:o))})];r.decision&&s.push(r.decision.close().catch(o=>{n.push(String(o instanceof Error?o.message:o))})),await Promise.all(s)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Zt=512,gr=1024,je=class extends Error{constructor(){super(`conversation capacity reached (${Zt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function mr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(ae))return{concurrencyKey:e};if(n.startsWith(ae)||n.startsWith(xe))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(ae)||n.startsWith(xe)||t.set(n,r)}}}function yr(t,e,n,r,s){let o=De({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ke,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...mr(r,s)});return{clients:He(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Se=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let s={id:n,subject:r!==void 0?`${ve(e.apiKey)}:live`:`${ve(e.apiKey)}:live:${n}`},o=new Map,a=this.opts.build?this.opts.build(e,s):yr(this.opts,e,s,o,r);return{id:n,backhaul:a,attachments:0,nativeRefs:o}}attachEntry(e,n,r){let s=this.byCaller.get(e.apiKey);s===void 0&&(s=new Map,this.byCaller.set(e.apiKey,s));let o=s.get(n);if(o!==void 0)return s.delete(n),s.set(n,o),o.attachments+=1,o;this.evictOverflow();let a=this.build(e,n,r);return a.attachments=1,s.set(n,a),a}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Zt;){let e=!1;for(let[n,r]of this.byCaller){for(let[s,o]of r)if(!(o.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),o.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new je}}dropHandleIndexFor(e,n){for(let[r,s]of this.byHandle)s.apiKey===e&&s.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,s=!1,o=()=>(r===null&&(r=this.attachEntry(e,Xt(),n)),r),a={createResponse:(i,l)=>o().backhaul.clients.createResponse(i,l),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let l=o().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),dedicatedSessionHandle:i=>{let l=o().backhaul.clients.dedicatedSessionHandle;return l===void 0?o().backhaul.clients.sessionHandle(i):l(i)},releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),endDedicatedSession:i=>o().backhaul.clients.endDedicatedSession?.(i),touchSessionPresence:(i,l)=>o().backhaul.clients.touchSessionPresence?.(i,l),detachSessionPresence:(i,l)=>o().backhaul.clients.detachSessionPresence?.(i,l),createResponseOn:(i,l,h)=>o().backhaul.clients.createResponseOn(i,l,h),onSessionEnd:(i,l)=>o().backhaul.clients.onSessionEnd(i,l)};return a.openAudio=async(i,l)=>{let h=o().backhaul.clients.openAudio;if(h===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return h(i,l)},a.openVideo=async i=>{let l=o().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(i)},a.openVideoOut=async i=>{let l=o().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(i)},a.supportsAudio=async i=>{let l=o().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(i)},a.supportsSpeech=async i=>{let l=o().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(i)},a.speechVoices=async i=>{let l=o().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(i)},a.speechSessionHandle=async i=>{let l=o().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(i)},a.openAudioOn=async(i,l,h)=>{let f=o().backhaul.clients.openAudioOn;if(f===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return f(i,l,h)},a.openVideoOn=async(i,l)=>{let h=o().backhaul.clients.openVideoOn;if(h===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return h(i,l)},a.openTurnsOn=(i,l)=>{let h=o().backhaul.clients.openTurnsOn;if(h===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return h(i,l)},a.evictSpeechSession=async i=>{let l=o().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(i)},a.supportsTranscription=async i=>{let l=o().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(i)},a.transcriptStreamFor=async i=>{let l=o().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(i)},a.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:a,bindResumeHandle:i=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=gr;){let h=this.byHandle.keys().next();if(h.done)break;this.byHandle.delete(h.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async i=>{let l=this.byHandle.get(i),h=l===void 0?void 0:this.byCaller.get(l.apiKey),f=l===void 0||h===void 0?void 0:h.get(l.conversationId);if(l===void 0||f===void 0||l.apiKey!==e.apiKey)throw new ie("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=f,f.attachments+=1,f.backhaul.clients},release:async()=>{if(s)return;s=!0;let i=r;r=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let s of r.values())e.push(s.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(s){n.push(String(s instanceof Error?s.message:s))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};T();var wr="/inference-ledger",br=1e4,ke=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},qe=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},H=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Ve=class extends N{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ye=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},vr=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",Je],["output_minutes",Je],["cost_nano_usd",Je],["price_version",t=>t===null||typeof t=="string"]];function _r(t){for(let[e,n]of vr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Sr(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:_r(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Je(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ze(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function kr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function en(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Er(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&en(t.started_at,n.started_at)&&en(t.completed_at,n.completed_at)&&ze(t.prompt_tokens,n.prompt_tokens)&&ze(t.completion_tokens,n.completion_tokens)&&ze(t.output_units,n.output_units)&&kr(t.output_minutes,n.output_minutes)}function Rr(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
@@ -389,8 +389,10 @@ interface RealtimeBinding<S = unknown> {
389
389
  * (urun.serve.transcribe_bridge wire shape: `t` = delta/final/turn_start/
390
390
  * turn_end/turn_eager_end/turn_resumed, `delta` text, additive `start_ms`
391
391
  * and semantic-VAD `confidence`). The resolver maps `session.stream('stt')
392
- * .messages()` onto this. Its `turn_end` IS the native commit and
393
- * `turn_start` IS the native barge-in — the adapter drives server-VAD
392
+ * .messages()` onto this. Its `turn_end` IS the native commit,
393
+ * `turn_start` IS the native barge-in, and `turn_dropped` closes a
394
+ * `turn_start` window that ended with NO user turn (speech_stopped, no
395
+ * commit) — the adapter drives server-VAD
394
396
  * emulation, real transcription events, and model-visible committed audio
395
397
  * from it. Absent = the backend wired no turn lane: manual mode only.
396
398
  *
@@ -401,7 +403,7 @@ interface RealtimeBinding<S = unknown> {
401
403
  * un-raced lane (its own teardown is then its own problem).
402
404
  */
403
405
  turns?: (signal?: AbortSignal) => AsyncIterable<{
404
- kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
406
+ kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
405
407
  text?: string;
406
408
  confidence?: number;
407
409
  startMs?: number;
@@ -426,9 +428,11 @@ interface RealtimeBinding<S = unknown> {
426
428
  * and serves no upstream turn seam. The connection subscribes its voice
427
429
  * OUT at connect; the engine's `turn_end` commits the user item but never
428
430
  * dispatches a model turn; engine speech opens a SERVER-INITIATED response
429
- * (`response.output_audio.delta`), closed `completed` by a quiet-track run
430
- * or `cancelled` by the user's `turn_start`; a client `response.create` is
431
- * the non-fatal `duplex_engine_owns_turns` error. Requires `voice`.
431
+ * (`response.output_audio.delta`) — never while the user's turn is open
432
+ * (`turn_start` → `turn_end`): frames inside it are dropped — closed
433
+ * `completed` by a quiet-track run or `cancelled` by the user's
434
+ * `turn_start`; a client `response.create` is the non-fatal
435
+ * `duplex_engine_owns_turns` error. Requires `voice`.
432
436
  */
433
437
  duplex?: boolean;
434
438
  /**
@@ -124,7 +124,7 @@ interface RealtimeBinding<S = unknown> {
124
124
  };
125
125
 
126
126
  turns?: (signal?: AbortSignal) => AsyncIterable<{
127
- kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
127
+ kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
128
128
  text?: string;
129
129
  confidence?: number;
130
130
  startMs?: number;
@@ -21,8 +21,8 @@ Connection: close\r
21
21
  Content-Type: text/plain; charset=utf-8\r
22
22
  Content-Length: ${Buffer.byteLength(o)}\r
23
23
  \r
24
- ${o}`)}function us(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Wp}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Ir(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==as){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ir(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let x=e.statusOf?.(E)??null;Ir(c,x?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new is(E,w,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Ir(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ls();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}T();T();var vs=require("@urun-sh/core");T();var ol=require("@urun-sh/core"),Xp={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},Qp={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 Dn(t,e){let n=Qp[t.code];return e?`${n} (${e})`:n}function Tr(t){if(t==null)return null;let e=Xp[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Or(t){if(t.kind==="create-failed")return Tr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ol.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Tr(e?"cold_start_exceeded":"queue_timeout")}var Hn=require("ws");T();var ll=require("@urun-sh/core");T();var il=require("crypto");function j(t){return`${t}_${(0,il.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Pr=4*1024*1024,ds=8*1024*1024,cs=512,an=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ot(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function ps(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Zp={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},ef={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},tf={format:!0,voice:!0,speed:!0};function nf(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function sn(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function sl(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var rf=10;function fs(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:rf})}function Fn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Zp));if(s.length>0)throw new z(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=sn(o.modalities,"modalities"),l=sn(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new z('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");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=sn(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('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");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!nf(l))throw new z(`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(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=fs(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("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 u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.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[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} 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.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("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(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.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")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new z("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in ef))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Fn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Fn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in tf))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.output.format"),d.speed!==void 0)throw new z("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 i.voice;else{if(typeof d.voice!="string")throw new z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Cr(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function ms(t,e){let n=t;if(!n||typeof n!="object")throw new z("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new z("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:j("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new z("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new z(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new z("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("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 l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Lr(t){let e=[],n=!1;for(let r of t){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 o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var of=1001,sf=1011,af=6e4,lf=3e5,hs=3;var Mr=class extends Error{},$r=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},gs=t=>t.slice(0,120),uf=/^[A-Za-z0-9+/=]*$/,df=600;function ys(t){return _r(Buffer.from(t,"base64"))}var Bn=class{id=j("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=ps();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;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??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??af,this.responseDeadlineMs=e.responseDeadlineMs??lf,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",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===$o&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:j("event"),session:Cr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.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 te&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(le(ot("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(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 n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){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:j("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:j("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:j("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),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:j("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);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:j("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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 i=j("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!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 n;try{n=e.toString()}catch{this.fail(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Pr){this.fail(fe("frame_too_large",`frame exceeds the ${Pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Mr){this.fail(ot(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
- ${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Fn(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&&n.turnDetection!==null){this.send(le(fe("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=n,this.send({type:"session.updated",event_id:j("event"),session:Cr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ms(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:j("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(le(fe("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:j("event"),item_id:n.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(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!uf.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=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,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>an&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${an}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${an} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>an&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("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 n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=j("item"),o=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",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("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(le(fe("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}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);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(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,gs("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("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,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Mr("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)");n.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(le({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 n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new $r),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?sn(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?sn(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("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??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("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,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=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 f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Lr(this.items),x=fs(typeof r.instructions=="string"?r.instructions:this.config.instructions),v=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,p=_==="inf"||_===void 0?void 0:_,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...v!==void 0?{temperature:v}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},O={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},b=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Lr(this.items)}let{input:$,sawAudioOnlyItem:M}=E??{input:[],sawAudioOnlyItem:!1},U={...S,input:$,...m?this.compositeTurnAsk(r):{}};M&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(U,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);O.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),O.contentFlowed=!0,O.messageOpen||(this.beginMessageItem(h,O.nextOutputIndex++),O.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(O.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),O.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),O.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${O.nextOutputIndex}`,N=O.tools.get(K);if(!N){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;N={outputIndex:O.nextOutputIndex++,name:ee,args:""},O.tools.set(K,N);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:N.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(N.name=G.name),N.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:N.outputIndex,call_id:K,name:N.name??"",delta:re});continue}if(G.type==="response.completed"){b=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof $r)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,b)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(O.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=hs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${hs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${hs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(ys(n))return;this.openDuplexResponse()}else if(ys(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=df){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(ys(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({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:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:j("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:j("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.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 n=e.error,r=rt(n);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 o=r??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}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(ot(No,"the organization is out of credits \u2014 top up to continue"),No))}failSessionGone(e){if(e instanceof te&&e.reason===$o){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===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 ${n}`:n===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: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ll.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cs&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Cn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Cn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("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(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,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>ds){this.ws.close(of,gs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(sf,gs(n)),this.teardown(n)}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 n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.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=>al(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),al(this.id,e)}},ws=[];function al(t,e){ws.push({id:t,reason:e}),ws.length>256&&ws.shift()}var jn="/v1/realtime",ul="urun.admission",dl=t=>t.slice(0,120);function cf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
24
+ ${o}`)}function us(t,e){let n=new bt.WebSocketServer({noServer:!0,maxPayload:Wp}),r=new Ct,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Ir(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==as){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ir(c,401,"invalid local proxy api key");return}let w;try{w=await a(d)}catch(E){let x=e.statusOf?.(E)??null;Ir(c,x?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,E=>{s.delete(c),o.add(E),E.on("close",()=>o.delete(E));try{new is(E,w,r,e.statusOf,e.operatorLog??(x=>console.error(x)))}catch{o.delete(E),E.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Ir(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=ls();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==bt.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}T();T();var vs=require("@urun-sh/core");T();var ol=require("@urun-sh/core"),Xp={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},Qp={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 Dn(t,e){let n=Qp[t.code];return e?`${n} (${e})`:n}function Tr(t){if(t==null)return null;let e=Xp[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Or(t){if(t.kind==="create-failed")return Tr(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ol.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Tr(e?"cold_start_exceeded":"queue_timeout")}var Hn=require("ws");T();var ll=require("@urun-sh/core");T();var il=require("crypto");function j(t){return`${t}_${(0,il.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Pr=4*1024*1024,ds=8*1024*1024,cs=512,an=20*1024*1024;function fe(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ot(t,e){return{type:"server_error",code:t,message:e}}function le(t){return{type:"error",event_id:j("event"),error:t}}function ps(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var z=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Zp={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},ef={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},tf={format:!0,voice:!0,speed:!0};function nf(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function sn(t,e){if(!Array.isArray(t)||t.length===0)throw new z(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new z(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function sl(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new z(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var rf=10;function fs(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:rf})}function Fn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new z("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Zp));if(s.length>0)throw new z(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let a=sn(o.modalities,"modalities"),l=sn(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new z("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new z(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new z(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new z('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");i.type=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new z(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=sn(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new z('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");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!nf(l))throw new z(`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(l!==null&&typeof l!="string")throw new z("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new z("instructions must be a string or null","instructions");i.instructions=fs(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new z("voice must be a string or null","voice");if(!n.voice)throw new z("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new z(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new z("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new z(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new z("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new z("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new z("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 u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new z(`turn_detection.type ${JSON.stringify(u.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[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new z(`turn_detection.${f} 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.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new z(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new z("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(!l||typeof l!="object"||Array.isArray(l))throw new z("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new z(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new z(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.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")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(l!==null)throw new z("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new z("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in ef))throw new z(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Fn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Fn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new z("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new z("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in tf))throw new z(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&sl(d.format,"audio.output.format"),d.speed!==void 0)throw new z("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 i.voice;else{if(typeof d.voice!="string")throw new z("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new z("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Cr(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function ms(t,e){let n=t;if(!n||typeof n!="object")throw new z("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new z("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:j("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new z('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new z("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new z("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new z(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new z("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new z("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new z("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new z("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new z("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 l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new z(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:j("item"),type:"message",role:r,content:o}}throw new z(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Lr(t){let e=[],n=!1;for(let r of t){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 o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var of=1001,sf=1011,af=6e4,lf=3e5,hs=3;var Mr=class extends Error{},$r=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ut=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},gs=t=>t.slice(0,120),uf=/^[A-Za-z0-9+/=]*$/,df=600;function ys(t){return _r(Buffer.from(t,"base64"))}var Bn=class{id=j("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=ps();sessionId=j("sess");conversationId=j("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;userTurnOpen=!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??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??af,this.responseDeadlineMs=e.responseDeadlineMs??lf,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",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===$o&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:j("event"),session:Cr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:j("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.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 te&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(le(ot("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(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 n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){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:j("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:j("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:j("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),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:j("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.userTurnOpen=!0,this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{this.userTurnOpen=!1;let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);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:j("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:j("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 i=j("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_dropped":{this.userTurnOpen=!1,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:j("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});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 n;try{n=e.toString()}catch{this.fail(fe("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Pr){this.fail(fe("frame_too_large",`frame exceeds the ${Pr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(fe("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(fe("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(le({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Mr){this.fail(ot(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
25
+ ${o?.stack??Ge(o)}`),this.send(le(ot(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Fn(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&&n.turnDetection!==null){this.send(le(fe("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=n,this.send({type:"session.updated",event_id:j("event"),session:Cr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=ms(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:j("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(le(fe("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:j("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(le(fe("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:j("event"),item_id:n.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(le(fe("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!uf.test(e.audio)){this.send(le(fe("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=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,n);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>an&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${an}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${an} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>an&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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:j("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(le(fe("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 n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=j("item"),o=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",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:j("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:j("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(le(fe("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(le(fe("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}if(this.binding.duplex){this.send(le(fe("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);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(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,gs("session ended by client"))}catch{}});return}case"ping":return;default:this.send(le(fe("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(le(fe("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,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Mr("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)");n.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(le({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 n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,a=new Promise((d,c)=>{i=setTimeout(()=>c(new $r),this.turnStallMs)}),l=n.next();l.catch(()=>{}),s=await(r?Promise.race([l,a,r]):Promise.race([l,a])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,n=!1){if(this.inFlight){this.send(le(fe("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?sn(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?sn(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.slice().sort().join(","))throw new z("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??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(le(fe("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,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},l=new Promise((A,P)=>{a=()=>P(new Ut)});this.turnCancelled=l,this.wakeTurnCancelled=()=>a(),l.catch(()=>{});let u=()=>{},d=new Promise((A,P)=>{u=()=>P(new Ut)});this.turnDialGate=d,this.wakeTurnDialGate=()=>u(),d.catch(()=>{});let c=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 f=j("req"),h=`resp_${f}`;this.activeResponseId=h,this.activeRequestId=f;let m=this.binding.composite===!0,w=m?0:this.items.length,E=m?null:Lr(this.items),x=fs(typeof r.instructions=="string"?r.instructions:this.config.instructions),v=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,p=_==="inf"||_===void 0?void 0:_,g=r.tools!==void 0?r.tools:this.config.tools,y=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...v!==void 0?{temperature:v}:{},...p!==void 0?{max_output_tokens:p}:{},...g!==void 0?{tools:g}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:A,captureWallMs:P}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(A,P);this.inFlight=(async()=>{let A=[],P=$=>{this.responseFlushed?this.send($):A.push($)},R=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:j("event"),response:this.responseObject(h,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(h,"in_progress")});for(let $ of A)this.send($);A.length=0,this.responseFlushed=!0}},O={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},b=null,C=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.responseObject(h,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(X=>{this.pendingTranscriptSettled=X}),this.cancelled||this.closed))throw new Ut;w=this.items.length,E=Lr(this.items)}let{input:$,sawAudioOnlyItem:M}=E??{input:[],sawAudioOnlyItem:!1},U={...S,input:$,...m?this.compositeTurnAsk(r):{}};M&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let q;try{let X=this.upstreamStream(U,f);Promise.resolve(X).catch(G=>{G instanceof te&&this.failSessionGone(G)}),q=await Promise.race([X,d])}catch(X){if(X instanceof Ut){this.deadlineFired&&!this.closed&&C();return}this.upstreamTurnFault(X,h);return}R();try{for await(let X of this.stallBoundedTurn(q)){if(this.cancelled)break;let G=X;if(G.type==="error"){let re=this.upstreamErrorBody(G);O.contentFlowed?this.send(le(re)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(h,re)});return}if(G.type==="response.output_text.delta"&&typeof G.delta=="string"){R(),O.contentFlowed=!0,O.messageOpen||(this.beginMessageItem(h,O.nextOutputIndex++),O.messageOpen=!0),this.config.outputModalities.includes("text")&&P({type:"response.output_text.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta}),this.turnOutputIsAudio()&&(O.transcriptDelta=!0,P({type:"response.output_audio_transcript.delta",event_id:j("event"),item_id:`${h}_msg_0`,response_id:h,output_index:0,content_index:0,delta:G.delta})),O.messageText+=G.delta;continue}if(G.type==="response.function_call_arguments.delta"){R(),O.contentFlowed=!0;let re=typeof G.delta=="string"?G.delta:"",K=typeof G.call_id=="string"&&G.call_id.length>0?G.call_id:`${h}_fc_${O.nextOutputIndex}`,N=O.tools.get(K);if(!N){let ee=typeof G.name=="string"&&G.name.length>0?G.name:void 0;N={outputIndex:O.nextOutputIndex++,name:ee,args:""},O.tools.set(K,N);let Fe={id:K,object:"realtime.item",type:"function_call",call_id:K,name:ee??"",arguments:"",status:"in_progress"};P({type:"response.output_item.added",event_id:j("event"),response_id:h,output_index:N.outputIndex,item:Fe}),this.emitAssistantItemAdded(Fe)}typeof G.name=="string"&&G.name.length>0&&(N.name=G.name),N.args+=re,P({type:"response.function_call_arguments.delta",event_id:j("event"),item_id:K,response_id:h,output_index:N.outputIndex,call_id:K,name:N.name??"",delta:re});continue}if(G.type==="response.completed"){b=G.response??null;continue}}}catch(X){if(this.closed)return;if(X instanceof Ut){this.deadlineFired&&C();return}if(this.cancelled)return;if(X instanceof $r)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${h} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(X,h);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&C();return}this.closeOpenItems(h,O,w),R(),this.send({type:"response.done",event_id:j("event"),response:this.doneResponse(h,w,b)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(O.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=hs){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${hs} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(le(ot("member_unresponsive",`the member served no content for ${hs} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(ys(n)||this.userTurnOpen)return;this.openDuplexResponse()}else if(ys(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=df){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(ys(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(le({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:j("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:j("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:j("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${j("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:j("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:j("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:j("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:j("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:j("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:j("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:j("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.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 n=e.error,r=rt(n);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 o=r??Ye(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}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(ot(No,"the organization is out of credits \u2014 top up to continue"),No))}failSessionGone(e){if(e instanceof te&&e.reason===$o){this.failInsufficientCredits();return}let n=e instanceof Error&&ze(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${Ge(e)}`);let r=this.binding.composite===!0?n===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 ${n}`:n===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: ${n}`;this.fail(ot("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof te){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ll.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ot(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(le(r)):this.send({type:"response.failed",event_id:j("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(le(fe("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:j("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cs&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(le(fe("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Cn){this.send(le(fe("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Cn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(le(fe("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(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(le(ot(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,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>ds){this.ws.close(of,gs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=De(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ge(e)}`),r.message}fail(e,n){this.send(le(e)),this.ws.close(sf,gs(n)),this.teardown(n)}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 n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.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=>al(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),al(this.id,e)}},ws=[];function al(t,e){ws.push({id:t,reason:e}),ws.length>256&&ws.shift()}var jn="/v1/realtime",ul="urun.admission",dl=t=>t.slice(0,120);function cf(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
26
26
  Connection: close\r
27
27
  Content-Type: text/plain\r
28
28
  \r
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{I as i,J as w,Z as v,_ as g,a as d,b as f,l as c}from"../chunk-4UE7XH7T.js";import"../chunk-HLSJAQHY.js";import"../chunk-CAR4AEQJ.js";import"../chunk-PPEND4SP.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-BVM4ZQ2Y.js";import"../chunk-KNWFUWXY.js";import{v as m,w as p}from"../chunk-Z74YK7AL.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
2
+ import{I as i,J as w,Z as v,_ as g,a as d,b as f,l as c}from"../chunk-WXO7IIRV.js";import"../chunk-NMNR3SQ5.js";import"../chunk-CAR4AEQJ.js";import"../chunk-MBIJRS4O.js";import"../chunk-KV3UXLNF.js";import"../chunk-MYNG74AX.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-B3GQYAJ5.js";import"../chunk-KNWFUWXY.js";import{v as m,w as p}from"../chunk-6R3TCKOH.js";import"../chunk-XNRPTMSL.js";import"../chunk-526ZJAOW.js";import"../chunk-AWCC5WRB.js";import"../chunk-7KRHHEKZ.js";import"../chunk-N3Y2GDQK.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
3
3
  `);let u=async e=>{o.stdout.write(`inference-proxy: ${e} \u2014 draining
4
4
  `),await g(n,P,I),await new Promise(t=>s.close(()=>t())),await new Promise(t=>a.close(()=>t()))};await new Promise(e=>{o.once("SIGINT",()=>{u("SIGINT").finally(e)}),o.once("SIGTERM",()=>{u("SIGTERM").finally(e)})})}$().then(()=>o.exit(0),r=>{o.stderr.write(`inference-proxy: ${String(r instanceof Error?r.stack??r.message:r)}
5
5
  `),o.exit(1)});