@urun-sh/openai 0.6.50 → 0.6.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{f as r}from"./chunk-PXV7QBSD.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(t,n){this.transport=new r(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=a(),i=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*i})(),{requestId:n})}}};export{o as a};
1
+ import{f as r}from"./chunk-AWCC5WRB.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(t,n){this.transport=new r(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=a(),i=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*i})(),{requestId:n})}}};export{o as a};
@@ -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-V6WQRPUO.js";import{c as ee,f as V,g as ne,p as oe}from"./chunk-64VO62LW.js";import{a as ge,b as G}from"./chunk-XGAF2NDT.js";import{c as ue}from"./chunk-6WTMEJZS.js";import{a as H}from"./chunk-Q3AIBMET.js";import{b as Z,d as j}from"./chunk-PXV7QBSD.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-C452ZIU5.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-AW5X2PRN.js";import{c as ee,f as V,g as ne,p as oe}from"./chunk-64VO62LW.js";import{a as ge,b as G}from"./chunk-XGAF2NDT.js";import{c as ue}from"./chunk-H4KFMIEV.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-C452ZIU5.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,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,2 +1,2 @@
1
- import{c as D}from"./chunk-6WTMEJZS.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
1
+ import{c as D}from"./chunk-H4KFMIEV.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
2
2
  `)}return c=f,h=t(),f},y=()=>c===null||t()-h>=s;return{rows(){return y()?(u||(u=_().finally(()=>{u=null})),u):Promise.resolve(c)},close(){c=null,u=null}}}export{G as a,X as b,Y as c,J as d,ne as e};
@@ -1,9 +1,9 @@
1
- import{a as Wn,c as Vn,d as Fe,e as Tt,f as re,g as zn,h as Kn,i as Xn,j as Yn,k as Qn,l as Zn,m as er,n as tr,r as nr,t as rr,u as sr,v as ir,w as or,x as ar}from"./chunk-X5BLQXHK.js";import{a as sn,e as on}from"./chunk-64VO62LW.js";import{a as Te,b as ye,v as Oe}from"./chunk-6WTMEJZS.js";import{a as Gn,e as lt,f as Jn,i as J,j as Q,k as an,l as un}from"./chunk-C452ZIU5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as qs}from"crypto";import{WebSocketServer as Us}from"ws";var Bs=256,Ot=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Bs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},js="local",dt=n=>n.slice(0,120),Pt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Vn,dt(e.message));return}if(e instanceof Q){this.ws.close(Tt,dt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,dt(e.message));return}this.ws.close(Fe,dt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=zn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=tr(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=rr(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:nr);return}this.transcript.push(...sr(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=Qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Tt);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Tt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Yn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Kn]=Xn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(or(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=qs();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Zn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(er(e.timeLeftMs)),this.ws.close(Fe,dt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=ir(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=ar(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Hs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new De(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ur(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Us({noServer:!0}),s=new Ot;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Wn&&(a.on("error",()=>{}),(async()=>{let d=Hs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:js}}r.handleUpgrade(o,a,u,p=>{new Pt(p,c,s)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
1
+ import{a as Wn,c as Vn,d as Fe,e as Tt,f as re,g as zn,h as Kn,i as Xn,j as Yn,k as Qn,l as Zn,m as er,n as tr,r as nr,t as rr,u as sr,v as ir,w as or,x as ar}from"./chunk-X5BLQXHK.js";import{a as sn,e as on}from"./chunk-64VO62LW.js";import{a as Te,b as ye,v as Oe}from"./chunk-H4KFMIEV.js";import{a as Gn,e as lt,f as Jn,i as J,j as Q,k as an,l as un}from"./chunk-C452ZIU5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as qs}from"crypto";import{WebSocketServer as Us}from"ws";var Bs=256,Ot=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Bs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},js="local",dt=n=>n.slice(0,120),Pt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Vn,dt(e.message));return}if(e instanceof Q){this.ws.close(Tt,dt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,dt(e.message));return}this.ws.close(Fe,dt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=zn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=tr(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=rr(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:nr);return}this.transcript.push(...sr(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=Qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Tt);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Tt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Yn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Kn]=Xn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(or(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=qs();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Zn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(er(e.timeLeftMs)),this.ws.close(Fe,dt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=ir(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=ar(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Hs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new De(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ur(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Us({noServer:!0}),s=new Ot;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Wn&&(a.on("error",()=>{}),(async()=>{let d=Hs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:js}}r.handleUpgrade(o,a,u,p=>{new Pt(p,c,s)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
2
2
  Connection: close\r
3
3
  \r
4
4
  ${m}\r
5
5
  `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of r.clients)o.close(1001,"server closing");await new Promise((o,a)=>r.close(u=>u===void 0?o():a(u)))})(),i)}function ka(n,e,t=new Ot){new Pt(n,e,t)}C();var Pe=class extends Error{code;status;retryAfterSeconds;constructor(e,t,r,s){super(s),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},ct=class extends Pe{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},ln=class extends Pe{constructor(e,t=!1){super("acquire_timeout",429,30,t?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},lr=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let t={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(t.min)||t.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(t.max)||t.max<t.min||t.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(t.inFlightCap)||t.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(t.warmWaitMs!==void 0&&(!Number.isInteger(t.warmWaitMs)||t.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=t.min,this.opts.max=t.max,this.opts.inFlightCap=t.inFlightCap,this.opts.warmWaitMs=t.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,t=0){let r=`decision:${this.opts.replicaId}:${e}`;return t===0?r:`${r}:${t}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let t=this.now(),r=this.slots.filter(s=>s.state==="paused"&&!s.opening&&(e||!s.dead)&&(!s.dead||t>=s.nextDialAt)).sort((s,i)=>s.slot.index-i.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let t=this.slots[e];t.dead&&!t.opening&&t.inFlight===0&&(t.backoffTimer&&(clearTimeout(t.backoffTimer),t.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(t)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${t instanceof Error?t.message:String(t)}`):(e.state="paused",this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new ct;this.lastDemandAt=this.now();let t=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let s=this.tryLease();if(s)return this.pump(),s;if(this.draining)throw new ct;let i=this.slots.some(c=>c.state==="queued"),o=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let u=r+t-Date.now();if(u<=0)throw new ln(t,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,u)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new ct}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let t=this.tryLease();if(t)return t;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(i=>i.state==="attached"),s=this.slots.some(i=>i.dead&&!i.opening&&this.now()>=i.nextDialAt);(r||s)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let i=s.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=r.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1,this.opts.onLease?.(t);let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.opening=null,this.rotate(t,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,t){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,t),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),t=this.slots.filter(i=>i.state==="attached"&&i.inFlight===0&&i.idleSince!==null&&e-i.idleSince>=this.idleGraceMs).sort((i,o)=>(i.idleSince??0)-(o.idleSince??0)||o.slot.index-i.slot.index),r=this.slots.filter(i=>i.state==="attached").length,s=Math.max(0,Math.min(t.length,r-this.opts.min));for(let i of t.slice(0,s))this.endSlot(i);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(t=>t.state==="attached"||t.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(s=>s.state==="attached").length,t=this.slots.filter(s=>s.state==="queued").length,r=this.slots.filter(s=>s.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:r,inFlight:this.slots.reduce((s,i)=>s+i.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,t)=>e+t.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let t of this.waiters.splice(0))t.settled||(t.settled=!0,t.resolve());if(this.slots.reduce((t,r)=>t+r.inFlight,0)>0){if(!this.drainComplete){let r,s=new Promise(i=>{r=i});this.drainComplete={promise:s,resolve:r}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let s of this.waiters.splice(0))s.settled||(s.settled=!0,s.resolve());let e=this.slots.map(s=>s.entry).filter(s=>s!==null);for(let s of this.slots)clearTimeout(s.backoffTimer),s.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(s=>this.opts.closeSlot(s)))).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};C();import{SessionFailedError as Qs}from"@urun-sh/core";C();C();import{SessionFailedError as dr}from"@urun-sh/core";var we=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},Gs=33e4;function Ta(n,e=Gs){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,i=new Promise((l,d)=>{s=d}),o=setTimeout(()=>s(new Mt),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof Q||l instanceof dr&&l.kind==="transport-failed"?l:l instanceof Mt?(await r.return?.(void 0),new we("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new we("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(o)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new we("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Mt=class extends Error{constructor(){super("stream idle timeout")}};function Oa(n){return n instanceof we?!1:n instanceof Q?!0:n instanceof dr?n.kind==="transport-failed":!1}var Js=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ve(n){return!Js.some(e=>e.test(n))}function be(n){return n==null||n===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${n} when reporting it`}function de(n,e){if(n instanceof Q)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let t=cr(n);return t||{message:be(e?.inferenceId??null),redacted:!0}}function cr(n){return n instanceof Jn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof Gn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof J?{message:n.message,redacted:!1}:n instanceof Te?{message:n.message,redacted:!1}:n instanceof Pe?{message:n.message,redacted:!1}:n instanceof we?ve(n.message)?{message:n.message,redacted:!1}:null:n instanceof _e?{message:n.message,redacted:!1}:n instanceof ye?{message:n.message,redacted:!1}:null}function ze(n,e,t){let r=t??(o=>console.error(o)),s=cr(e);if(s)return s.redacted&&r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed: ${s.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ve(i)?`the ${n} upstream failed: ${i}`:(r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed while serving this request`)}function Se(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ve(e)?e:null}function pe(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}C();import{randomUUID as Ws}from"crypto";function A(n){return`${n}_${Ws().replace(/-/g,"").slice(0,24)}`}var Ct=4*1024*1024,dn=8*1024*1024,cn=512,Lt=20*1024*1024;function X(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Re(n,e){return{type:"server_error",code:n,message:e}}function G(n){return{type:"error",event_id:A("event"),error:n}}function pn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},Vs={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},zs={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ks={format:!0,voice:!0,speed:!0};function Xs(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ke(n,e){if(!Array.isArray(n)||n.length===0)throw new E(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let r of n){if(r!=="text"&&r!=="audio")throw new E(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(r)||t.push(r)}return t}function pr(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new E(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Ys=10;function mn(n){if(n==null)return n;let e;try{e=JSON.parse(n)}catch{return n}if(e===null||typeof e!="object"||Array.isArray(e))return n;let t=e;return t.hz!==void 0||t.cadence_ms!==void 0||!("questions"in t)&&!("question"in t)?n:JSON.stringify({...t,hz:Ys})}function pt(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new E("session must be an object","session","invalid_request");let s=n,i=Object.keys(s).filter(a=>!(a in Vs));if(i.length>0)throw new E(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(s.modalities!==void 0&&s.output_modalities!==void 0){let a=Ke(s.modalities,"modalities"),u=Ke(s.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new E("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let o={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(s))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new E(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new E(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!t.turns)throw new E('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");o.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new E(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=Ke(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new E('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");o.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Xs(u))throw new E(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new E("model must be a string or null","model");o.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new E("instructions must be a string or null","instructions");o.instructions=mn(u??void 0)??void 0;break;case"voice":if(u===null){delete o.voice;break}if(typeof u!="string")throw new E("voice must be a string or null","voice");if(!t.voice)throw new E("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");o.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new E(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new E("temperature must be a finite number or null","temperature");o.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new E(`${a} must be a positive integer, "inf" or null`,a);o.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new E("tools must be an array","tools");o.tools=u;break;case"tool_choice":o.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new E("metadata must be an object or null","metadata");o.metadata=u??null;break;case"turn_detection":{if(u===null){o.turnDetection=null;break}if(!t.turns)throw new E("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new E(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new E(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new E(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}o.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){o.inputAudioTranscription=!1;break}if(!t.turns)throw new E("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new E("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new E(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==t.model)throw new E(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${t.model===void 0?"the unnamed default app":JSON.stringify(t.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}o.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new E("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in zs))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&pr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=pt({input_audio_transcription:d.transcription},o,t,r);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=pt({turn_detection:d.turn_detection},o,t,r);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new E("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ks))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&pr(d.format,"audio.output.format"),d.speed!==void 0)throw new E("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete o.voice;else{if(typeof d.voice!="string")throw new E("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new E("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");o.voice=d.voice}d.format!==void 0&&!o.outputModalities.includes("audio")&&(o.outputModalities=["text","audio"])}break}default:break}return o}function $t(n,e){return{id:e,object:"realtime.session",type:n.type??"realtime",model:n.model??null,instructions:n.instructions??"",modalities:[...n.outputModalities],voice:n.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:n.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:n.turnDetection?{type:"server_vad",create_response:n.turnDetection.createResponse,interrupt_response:n.turnDetection.interruptResponse}:null,temperature:n.temperature??null,max_response_output_tokens:n.maxOutputTokens??"inf",tool_choice:n.toolChoice??"auto",tools:n.tools??[],metadata:n.metadata??null}}function fn(n,e){let t=n;if(!t||typeof t!="object")throw new E("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new E("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:A("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let r=t.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new E("message item content must be an array","item.content","invalid_request");let s=[];for(let i of t.content){let o=i;if(!o||typeof o!="object")throw new E("content part must be an object","item.content","invalid_request");if(o.type==="input_text"||r==="assistant"&&o.type==="output_text"){if(typeof o.text!="string")throw new E(`${String(o.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){if(!e)throw new E("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof o.audio!="string")throw new E("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}if(o.type==="input_image"){if(r!=="user")throw new E("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof o.image_url=="string"?o.image_url:o.image_url?.url;if(typeof a!="string"||a.length===0)throw new E("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new E("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof o.detail=="string"?o.detail:void 0;s.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new E(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:A("item"),type:"message",role:r,content:s}}throw new E(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Ft(n){let e=[],t=!1;for(let r of n){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let s=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let o=i.transcript;if(typeof o=="string"&&o.trim().length>0){s.push({type:"input_text",text:o});continue}t=!0;continue}}e.push({role:r.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Zs=1001,ei=1011,ti=6e4,ni=3e5;var Dt=class extends Error{},Nt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ne=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},hn=n=>n.slice(0,120),ri=/^[A-Za-z0-9+/=]*$/,si=2;function ii(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>si)return!1;return!0}var mt=class{id=A("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=pn();sessionId=A("sess");conversationId=A("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(t=>console.error(t)),this.turnStallMs=e.turnStallMs??ti,this.responseDeadlineMs=e.responseDeadlineMs??ni,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(t=>{t.reason===an&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:A("event"),session:$t(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:A("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let t of e.replayFrames??[])this.onMessage(t)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let r=await t.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof Q&&this.binding.composite===!0)this.failSessionGone(r);else{let s=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,s):this.send(G(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${s}`)))}}finally{this.turnLaneIterator===t&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let t=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,t),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:e,content_index:0,transcript:t});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,t){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:A("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:t}}),this.emitItemDone(e)}writeItemTranscript(e,t){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:t},...(r.content??[]).slice(1)])}emitItemDone(e){let t=this.items.findIndex(r=>r.id===e);t<0||this.send({type:"conversation.item.done",event_id:A("event"),previous_item_id:t>0?this.items[t-1].id:null,item:this.itemToProtocol(this.items[t])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,t.length>0&&(this.turnTranscript.text+=t),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&t.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:A("event"),item_id:r??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:A("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let s=this.turnTranscript.text.trim(),i=s.length>0?s:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=A("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...i!==null?{transcript:i}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:A("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&i!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:o,content_index:0,transcript:i}),this.emitItemDone(o),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(X("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>Ct){this.fail(X("frame_too_large",`frame exceeds the ${Ct}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(X("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(X("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(s instanceof Dt){this.fail(Re(null,this.callerLine(s,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
6
- ${s?.stack??pe(s)}`),this.send(G(Re(null,this.callerLine(s,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let t=pt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(G(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=t,this.send({type:"session.updated",event_id:A("event"),session:$t(this.config,this.sessionId)});return}case"conversation.item.create":{let t=fn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,s=t.content??[];(s.length===0||s.some(i=>i.type!=="input_image"))&&this.pushItem(t),this.forwardImageFrames(t),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:r,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(r=>r.id===e.item_id);if(t<0){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:A("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(r=>r.id===e.item_id);if(!t){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:A("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(r=>r.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(G(X("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:A("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(G(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ri.test(e.audio)){this.send(G(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,t);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Lt){this.send(G(X("buffer_full",`uncommitted input audio exceeds the ${Lt}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:t}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:A("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(G(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=A("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(t!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:t}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(G(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(G(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:t==null?"none":t instanceof Error?`error: ${t.message}`:t}))}).catch(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${t instanceof Error?t.message:String(t)}`}))}).finally(()=>{try{this.ws.close(1e3,hn("session ended by client"))}catch{}});return}case"ping":return;default:this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(X("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new Dt("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(G({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let t=e[Symbol.asyncIterator](),r=this.turnCancelled,s=!0;try{for(;;){let i;if(s||this.turnStallMs<=0){s=!1;let o=t.next();o.catch(()=>{}),i=r?await Promise.race([o,r]):await o}else{let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Nt),this.turnStallMs)}),u=t.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(o))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(t.return?.()).catch(()=>{})}}async upstreamStream(e,t){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],t)}let s=this.binding.clients;if(s&&typeof s.createResponse=="function"){let{response:i,input:o,...a}=e;return await s.createResponse({...a,input:o})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(G(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{},r=t.modalities!==void 0?Ke(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?Ke(t.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&s!==void 0&&r.slice().sort().join(",")!==s.slice().sort().join(","))throw new E("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??r)?.includes("audio")&&!this.ensureVoice())return;if(t.input!==void 0){this.send(G(X("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let o=()=>{},a=new Promise((x,S)=>{o=()=>S(new Ne)});this.turnCancelled=a,this.wakeTurnCancelled=()=>o(),a.catch(()=>{});let u=()=>{},l=new Promise((x,S)=>{u=()=>S(new Ne)});this.turnDialGate=l,this.wakeTurnDialGate=()=>u(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=A("req"),p=`resp_${c}`;this.activeResponseId=p,this.activeRequestId=c;let m=this.binding.composite===!0,f=m?0:this.items.length,b=m?null:Ft(this.items),k=mn(typeof t.instructions=="string"?t.instructions:this.config.instructions),_=typeof t.temperature=="number"?t.temperature:this.config.temperature,y=t.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=t.tools!==void 0?t.tools:this.config.tools,$=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,P={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},..._!==void 0?{temperature:_}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...$!==void 0?{tool_choice:$}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:x,captureWallMs:S}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,S);this.inFlight=(async()=>{let x=[],S=M=>{this.responseFlushed?this.send(M):x.push(M)},I=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:A("event"),response:this.responseObject(p,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(p,"in_progress")});for(let M of x)this.send(M);x.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},v=null,R=()=>{this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.responseObject(p,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))throw new Ne;f=this.items.length,b=Ft(this.items)}let{input:M,sawAudioOnlyItem:j}=b??{input:[],sawAudioOnlyItem:!1},H={...P,input:M,...m?this.compositeTurnAsk(t):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let L;try{let O=this.upstreamStream(H,c);Promise.resolve(O).catch(D=>{D instanceof Q&&this.failSessionGone(D)}),L=await Promise.race([O,l])}catch(O){if(O instanceof Ne){this.deadlineFired&&!this.closed&&R();return}this.upstreamTurnFault(O,p);return}I();try{for await(let O of this.stallBoundedTurn(L)){if(this.cancelled)break;let D=O;if(D.type==="error"){let U=this.upstreamErrorBody(D);h.contentFlowed?this.send(G(U)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(p,U)});return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){I(),h.contentFlowed=!0,h.messageOpen||(this.beginMessageItem(p,h.nextOutputIndex++),h.messageOpen=!0),this.config.outputModalities.includes("text")&&S({type:"response.output_text.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta}),this.turnOutputIsAudio()&&(h.transcriptDelta=!0,S({type:"response.output_audio_transcript.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta})),h.messageText+=D.delta;continue}if(D.type==="response.function_call_arguments.delta"){I(),h.contentFlowed=!0;let U=typeof D.delta=="string"?D.delta:"",z=typeof D.call_id=="string"&&D.call_id.length>0?D.call_id:`${p}_fc_${h.nextOutputIndex}`,T=h.tools.get(z);if(!T){let q=typeof D.name=="string"&&D.name.length>0?D.name:void 0;T={outputIndex:h.nextOutputIndex++,name:q,args:""},h.tools.set(z,T);let W={id:z,object:"realtime.item",type:"function_call",call_id:z,name:q??"",arguments:"",status:"in_progress"};S({type:"response.output_item.added",event_id:A("event"),response_id:p,output_index:T.outputIndex,item:W}),this.emitAssistantItemAdded(W)}typeof D.name=="string"&&D.name.length>0&&(T.name=D.name),T.args+=U,S({type:"response.function_call_arguments.delta",event_id:A("event"),item_id:z,response_id:p,output_index:T.outputIndex,call_id:z,name:T.name??"",delta:U});continue}if(D.type==="response.completed"){v=D.response??null;continue}}}catch(O){if(this.closed)return;if(O instanceof Ne){this.deadlineFired&&R();return}if(this.cancelled)return;if(O instanceof Nt)this.operatorLog(`[realtime] turn ${p} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(O,p);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&R();return}this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.doneResponse(p,f,v)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){if(ii(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:A("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let t=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let s={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:r,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,r){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,i=this.messageItemOpenForAudio,o=this.config.outputModalities.includes("text"),a=t.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),t.messageText.length>0&&o&&this.send({type:"response.output_text.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:t.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),t.messageText.length>0&&u.push({type:"output_text",text:t.messageText});let l={id:s,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[s,i]of t.tools){let o=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:A("event"),item_id:s,response_id:e,output_index:i.outputIndex,call_id:s,name:i.name??"",arguments:o});let a={id:s,type:"function_call",callId:s,name:i.name,arguments:o};this.pushItem(a),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,r){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,r){let s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let o=t;o<this.items.length;o++)i.push(this.itemToProtocol(this.items[o]));return this.responseObject(e,"completed",{output:i,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let t=e.error,r=Se(t);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let s=r??be(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Re(un,"the organization is out of credits \u2014 top up to continue"),un))}failSessionGone(e){if(e instanceof Q&&e.reason===an){this.failInsufficientCredits();return}let t=e instanceof Error&&ve(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${pe(e)}`);let r=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(Re("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Qs&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Re(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(r)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(t,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let t=this.activeRequestId,r=this.binding.session;t!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(t),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let t=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:A("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cn&&this.items.shift()}forwardImageFrames(e){for(let t of e.content??[]){if(t.type!=="input_image")continue;let r=t.imageUrl.indexOf(","),s=r>=0?Buffer.from(t.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(s.byteLength===0){this.send(G(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(s.byteLength>on){this.send(G(X("frame_too_large",`input_image frame is ${s.byteLength} bytes \u2014 over the ${on}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(G(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(s))).catch(i=>this.send(G(Re(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:s.type==="input_image"?{type:"input_image",image_url:s.imageUrl,...s.detail?{detail:s.detail}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>dn){this.ws.close(Zs,hn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${pe(e)}`),r.message}fail(e,t){this.send(G(e)),this.ws.close(ei,hn(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let t=this.turnLaneIterator;if(this.turnLaneIterator=null,t!==null){let r=t.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>mr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),mr(this.id,e)}},gn=[];function mr(n,e){gn.push({id:n,reason:e}),gn.length>256&&gn.shift()}C();import{SessionFailedError as fr}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as oi}from"@urun-sh/core";var ai={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},ui={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function ft(n,e){let t=ui[n.code];return e?`${t} (${e})`:t}function qt(n){if(n==null)return null;let e=ai[n];return e===void 0?null:{status:e,code:n,retryable:e!==502,openaiType:n==="no_capacity"||n==="queue_full"?"capacity_error":n==="queue_timeout"||n==="cold_start_exceeded"||n==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Ut(n){if(n.kind==="create-failed")return qt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=oi;return qt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocket as hr,WebSocketServer as li}from"ws";var _n="/v1/realtime",gr="urun.admission",yr=n=>n.slice(0,120);function di(n,e,t){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
6
+ ${s?.stack??pe(s)}`),this.send(G(Re(null,this.callerLine(s,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let t=pt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(G(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=t,this.send({type:"session.updated",event_id:A("event"),session:$t(this.config,this.sessionId)});return}case"conversation.item.create":{let t=fn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,s=t.content??[];(s.length===0||s.some(i=>i.type!=="input_image"))&&this.pushItem(t),this.forwardImageFrames(t),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:r,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(r=>r.id===e.item_id);if(t<0){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:A("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(r=>r.id===e.item_id);if(!t){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:A("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(r=>r.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(G(X("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:A("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(G(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ri.test(e.audio)){this.send(G(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,t);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Lt){this.send(G(X("buffer_full",`uncommitted input audio exceeds the ${Lt}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:t}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:A("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(G(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=A("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:A("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(t!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:t}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:A("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(G(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(G(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:t==null?"none":t instanceof Error?`error: ${t.message}`:t}))}).catch(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${t instanceof Error?t.message:String(t)}`}))}).finally(()=>{try{this.ws.close(1e3,hn("session ended by client"))}catch{}});return}case"ping":return;default:this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(X("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new Dt("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(G({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let t=e[Symbol.asyncIterator](),r=this.turnCancelled,s=!0;try{for(;;){let i;if(s||this.turnStallMs<=0){s=!1;let o=t.next();o.catch(()=>{}),i=r?await Promise.race([o,r]):await o}else{let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Nt),this.turnStallMs)}),u=t.next();u.catch(()=>{}),i=await(r?Promise.race([u,a,r]):Promise.race([u,a])).finally(()=>clearTimeout(o))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(t.return?.()).catch(()=>{})}}async upstreamStream(e,t){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return this.config.model&&i.model===void 0&&(i.model=this.config.model),r.sendResponseCreate({type:"response.create",response:i},e.input??[],t)}let s=this.binding.clients;if(s&&typeof s.createResponse=="function"){let{response:i,input:o,...a}=e;return await s.createResponse({...a,input:o})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(G(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{},r=t.modalities!==void 0?Ke(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?Ke(t.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&s!==void 0&&r.slice().sort().join(",")!==s.slice().sort().join(","))throw new E("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??r)?.includes("audio")&&!this.ensureVoice())return;if(t.input!==void 0){this.send(G(X("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let o=()=>{},a=new Promise((x,S)=>{o=()=>S(new Ne)});this.turnCancelled=a,this.wakeTurnCancelled=()=>o(),a.catch(()=>{});let u=()=>{},l=new Promise((x,S)=>{u=()=>S(new Ne)});this.turnDialGate=l,this.wakeTurnDialGate=()=>u(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=A("req"),p=`resp_${c}`;this.activeResponseId=p,this.activeRequestId=c;let m=this.binding.composite===!0,f=m?0:this.items.length,b=m?null:Ft(this.items),k=mn(typeof t.instructions=="string"?t.instructions:this.config.instructions),_=typeof t.temperature=="number"?t.temperature:this.config.temperature,y=t.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=t.tools!==void 0?t.tools:this.config.tools,$=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,P={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},..._!==void 0?{temperature:_}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...$!==void 0?{tool_choice:$}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:x,captureWallMs:S}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,S);this.inFlight=(async()=>{let x=[],S=M=>{this.responseFlushed?this.send(M):x.push(M)},I=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:A("event"),response:this.responseObject(p,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(p,"in_progress")});for(let M of x)this.send(M);x.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},v=null,R=()=>{this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.responseObject(p,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))throw new Ne;f=this.items.length,b=Ft(this.items)}let{input:M,sawAudioOnlyItem:j}=b??{input:[],sawAudioOnlyItem:!1},H={...P,input:M,...m?this.compositeTurnAsk(t):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let L;try{let O=this.upstreamStream(H,c);Promise.resolve(O).catch(D=>{D instanceof Q&&this.failSessionGone(D)}),L=await Promise.race([O,l])}catch(O){if(O instanceof Ne){this.deadlineFired&&!this.closed&&R();return}this.upstreamTurnFault(O,p);return}I();try{for await(let O of this.stallBoundedTurn(L)){if(this.cancelled)break;let D=O;if(D.type==="error"){let U=this.upstreamErrorBody(D);h.contentFlowed?this.send(G(U)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(p,U)});return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){I(),h.contentFlowed=!0,h.messageOpen||(this.beginMessageItem(p,h.nextOutputIndex++),h.messageOpen=!0),this.config.outputModalities.includes("text")&&S({type:"response.output_text.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta}),this.turnOutputIsAudio()&&(h.transcriptDelta=!0,S({type:"response.output_audio_transcript.delta",event_id:A("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta})),h.messageText+=D.delta;continue}if(D.type==="response.function_call_arguments.delta"){I(),h.contentFlowed=!0;let U=typeof D.delta=="string"?D.delta:"",z=typeof D.call_id=="string"&&D.call_id.length>0?D.call_id:`${p}_fc_${h.nextOutputIndex}`,T=h.tools.get(z);if(!T){let q=typeof D.name=="string"&&D.name.length>0?D.name:void 0;T={outputIndex:h.nextOutputIndex++,name:q,args:""},h.tools.set(z,T);let W={id:z,object:"realtime.item",type:"function_call",call_id:z,name:q??"",arguments:"",status:"in_progress"};S({type:"response.output_item.added",event_id:A("event"),response_id:p,output_index:T.outputIndex,item:W}),this.emitAssistantItemAdded(W)}typeof D.name=="string"&&D.name.length>0&&(T.name=D.name),T.args+=U,S({type:"response.function_call_arguments.delta",event_id:A("event"),item_id:z,response_id:p,output_index:T.outputIndex,call_id:z,name:T.name??"",delta:U});continue}if(D.type==="response.completed"){v=D.response??null;continue}}}catch(O){if(this.closed)return;if(O instanceof Ne){this.deadlineFired&&R();return}if(this.cancelled)return;if(O instanceof Nt)this.operatorLog(`[realtime] turn ${p} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(O,p);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&R();return}this.closeOpenItems(p,h,f),I(),this.send({type:"response.done",event_id:A("event"),response:this.doneResponse(p,f,v)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){if(ii(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:A("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:A("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let t=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:A("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let s={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:r,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:A("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:A("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,r){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,i=this.messageItemOpenForAudio,o=this.config.outputModalities.includes("text"),a=t.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),t.messageText.length>0&&o&&this.send({type:"response.output_text.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:A("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:t.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),t.messageText.length>0&&u.push({type:"output_text",text:t.messageText});let l={id:s,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[s,i]of t.tools){let o=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:A("event"),item_id:s,response_id:e,output_index:i.outputIndex,call_id:s,name:i.name??"",arguments:o});let a={id:s,type:"function_call",callId:s,name:i.name,arguments:o};this.pushItem(a),this.send({type:"response.output_item.done",event_id:A("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,r){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,r){let s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let o=t;o<this.items.length;o++)i.push(this.itemToProtocol(this.items[o]));return this.responseObject(e,"completed",{output:i,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let t=e.error,r=Se(t);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let s=r??be(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Re(un,"the organization is out of credits \u2014 top up to continue"),un))}failSessionGone(e){if(e instanceof Q&&e.reason===an){this.failInsufficientCredits();return}let t=e instanceof Error&&ve(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${pe(e)}`);let r=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(Re("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Qs&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Re(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(r)):this.send({type:"response.failed",event_id:A("event"),response:this.failedResponse(t,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let t=this.activeRequestId,r=this.binding.session;t!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(t),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let t=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:A("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>cn&&this.items.shift()}forwardImageFrames(e){for(let t of e.content??[]){if(t.type!=="input_image")continue;let r=t.imageUrl.indexOf(","),s=r>=0?Buffer.from(t.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(s.byteLength===0){this.send(G(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(s.byteLength>on){this.send(G(X("frame_too_large",`input_image frame is ${s.byteLength} bytes \u2014 over the ${on}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(G(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(s))).catch(i=>this.send(G(Re(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:s.type==="input_image"?{type:"input_image",image_url:s.imageUrl,...s.detail?{detail:s.detail}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>dn){this.ws.close(Zs,hn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${pe(e)}`),r.message}fail(e,t){this.send(G(e)),this.ws.close(ei,hn(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let t=this.turnLaneIterator;if(this.turnLaneIterator=null,t!==null){let r=t.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>mr(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),mr(this.id,e)}},gn=[];function mr(n,e){gn.push({id:n,reason:e}),gn.length>256&&gn.shift()}C();import{SessionFailedError as fr}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as oi}from"@urun-sh/core";var ai={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},ui={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function ft(n,e){let t=ui[n.code];return e?`${t} (${e})`:t}function qt(n){if(n==null)return null;let e=ai[n];return e===void 0?null:{status:e,code:n,retryable:e!==502,openaiType:n==="no_capacity"||n==="queue_full"?"capacity_error":n==="queue_timeout"||n==="cold_start_exceeded"||n==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Ut(n){if(n.kind==="create-failed")return qt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=oi;return qt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocket as hr,WebSocketServer as li}from"ws";var _n="/v1/realtime",gr="urun.admission",yr=n=>n.slice(0,120);function di(n,e,t){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
7
7
  Connection: close\r
8
8
  Content-Type: text/plain\r
9
9
  \r
@@ -0,0 +1 @@
1
+ import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function f(e,t,o,n){let r=e.response??{},s={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(s.instructions=r.instructions),typeof r.model=="string"&&r.model&&(s.model=r.model),Array.isArray(r.modalities)&&(s.modalities=r.modalities),typeof r.temperature=="number"&&(s.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(s.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(s.tools=r.tools),s}function _(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,r=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();import{gcRequest as w}from"@urun-sh/core/internal";i();var v="llm-resp";async function*h(e,t){let o=`resp_${e}`,n=new Map;for await(let r of t){let s=r;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let p=typeof a.index=="number"?a.index:0,u=n.get(p)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(p,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${p}`,tool_index:p,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...s.body}};return}else if(s.t==="error"){yield y(s);return}}}async function*g(e,t){let o=`${v}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*h(t,e.stream(o).messages())}finally{try{w(e.doc("llm"),t)}catch{}}}i();import{gcRequest as E}from"@urun-sh/core/internal";var k=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=_(t,o,this.consumerId);return this.write(n),g(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let r=f(t,o,n,this.consumerId);return this.write(r),g(this.session,n)})}cancelTurn(t){try{E(this.session.doc("llm"),t)}catch{}}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{f as a,_ as b,y as c,h as d,g as e,k as f};
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-C452ZIU5.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.50";var y=4141,A=g,M={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
1
+ import{h as m}from"./chunk-C452ZIU5.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.51";var y=4141,A=g,M={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of h)n[i]=a[i]}}var D=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&D.has(t)}function se(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function ae(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
3
3
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ue(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
4
4
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}