@urun-sh/openai 0.6.32 → 0.6.33

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,15 +1,15 @@
1
- import{a as Mn,c as Ln,d as Ce,e as kt,f as ee,g as $n,h as Fn,i as Dn,j as Nn,k as qn,l as Un,m as Bn,n as jn,r as Hn,t as Gn,u as Jn,v as Wn,w as Vn,x as zn}from"./chunk-3JWYIKHM.js";import{a as Yt}from"./chunk-6M5JK4YC.js";import{s as Ae}from"./chunk-M3YMNU5P.js";import{a as Pn,d as st,e as Cn,h as q,i as Y}from"./chunk-OOCRI7ZM.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as _s}from"crypto";import{WebSocketServer as ws}from"ws";var vs=256,St=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>vs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},bs="local",it=n=>n.slice(0,120),Rt=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 q){this.ws.close(Ln,it(e.message));return}if(e instanceof Y){this.ws.close(kt,it(e.message));return}if(e instanceof ee){this.ws.close(e.closeCode,it(e.message));return}this.ws.close(Ce,it(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=$n(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 ee(`"${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}=jn(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Gn(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:Hn);return}this.transcript.push(...Jn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new ee("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 ee("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",kt);if(i.model!==t.model)throw new ee(`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 ee("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 ee(`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`,kt);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(Nn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Fn]=Dn(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 ee("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new ee("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ce);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Vn(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 ee("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new ee("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ce);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 ee(`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 ee("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 ee("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=_s();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Un(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(Bn(e.timeLeftMs)),this.ws.close(Ce,it(`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 ee(`upstream error: ${JSON.stringify(l)}`,Ce);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=Wn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new ee("upstream produced no response.completed event",Ce);let{messages:o,assistantItems:a}=zn(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Me=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function xs(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 Me(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 Me(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 Me(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Kn(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 ws({noServer:!0}),s=new St;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Mn&&(a.on("error",()=>{}),(async()=>{let d=xs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Me(401,"invalid local proxy api key");c={clients:e.clients,scope:bs}}r.handleUpgrade(o,a,u,p=>{new Rt(p,c,s)})})().catch(d=>{let c=502;(d instanceof Me||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",y=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
1
+ import{a as Mn,c as Ln,d as Ce,e as kt,f as ee,g as $n,h as Fn,i as Dn,j as Nn,k as qn,l as Un,m as Bn,n as jn,r as Hn,t as Gn,u as Jn,v as Wn,w as Vn,x as zn}from"./chunk-3JWYIKHM.js";import{a as Yt}from"./chunk-6M5JK4YC.js";import{s as Ae}from"./chunk-NL3UBLXV.js";import{a as Pn,d as st,e as Cn,h as q,i as Y}from"./chunk-OOCRI7ZM.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as _s}from"crypto";import{WebSocketServer as ws}from"ws";var vs=256,St=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>vs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},bs="local",it=n=>n.slice(0,120),Rt=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 q){this.ws.close(Ln,it(e.message));return}if(e instanceof Y){this.ws.close(kt,it(e.message));return}if(e instanceof ee){this.ws.close(e.closeCode,it(e.message));return}this.ws.close(Ce,it(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=$n(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 ee(`"${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}=jn(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Gn(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:Hn);return}this.transcript.push(...Jn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new ee("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 ee("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",kt);if(i.model!==t.model)throw new ee(`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 ee("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 ee(`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`,kt);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(Nn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Fn]=Dn(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 ee("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new ee("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ce);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Vn(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 ee("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new ee("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ce);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 ee(`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 ee("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 ee("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=_s();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Un(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(Bn(e.timeLeftMs)),this.ws.close(Ce,it(`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 ee(`upstream error: ${JSON.stringify(l)}`,Ce);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=Wn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new ee("upstream produced no response.completed event",Ce);let{messages:o,assistantItems:a}=zn(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Me=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function xs(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 Me(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 Me(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 Me(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Kn(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 ws({noServer:!0}),s=new St;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Mn&&(a.on("error",()=>{}),(async()=>{let d=xs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Me(401,"invalid local proxy api key");c={clients:e.clients,scope:bs}}r.handleUpgrade(o,a,u,p=>{new Rt(p,c,s)})})().catch(d=>{let c=502;(d instanceof Me||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",y=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
  ${y}\r
5
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of r.clients)o.close(1001,"server closing");await new Promise((o,a)=>r.close(u=>u===void 0?o():a(u)))})(),i)}function Vo(n,e,t=new St){new Rt(n,e,t)}C();var Ie=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)}},ot=class extends Ie{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Qt=class extends Ie{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")}},me=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Xn=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(){let e=this.slots.filter(t=>t.state==="paused"&&!t.opening).sort((t,r)=>t.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}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};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.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 ot;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 ot;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);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let u=r+t-Date.now();if(u<=0)throw new Qt(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 ot}}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);(r||s)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let i=s.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=r.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1;let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.signalDrain())}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)},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(),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,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);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 Ps}from"@urun-sh/core";C();C();var we=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ae=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};C();import{SessionFailedError as Yn}from"@urun-sh/core";var fe=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)}},ks=33e4;function na(n,e=ks){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,i=new Promise((l,d)=>{s=d}),o=setTimeout(()=>s(new At),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof Y||l instanceof Yn&&l.kind==="transport-failed"?l:l instanceof At?(await r.return?.(void 0),new fe("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 fe("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 fe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var At=class extends Error{constructor(){super("stream idle timeout")}};function ra(n){return n instanceof fe?!1:n instanceof Y?!0:n instanceof Yn?n.kind==="transport-failed":!1}var Ss=[/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 ge(n){return!Ss.some(e=>e.test(n))}function ye(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 ue(n,e){if(n instanceof Y)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=Qn(n);return t||{message:ye(e?.inferenceId??null),redacted:!0}}function Qn(n){return n instanceof Cn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof Pn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof q?{message:n.message,redacted:!1}:n instanceof we?{message:n.message,redacted:!1}:n instanceof Ie?{message:n.message,redacted:!1}:n instanceof fe?ge(n.message)?{message:n.message,redacted:!1}:null:n instanceof me?{message:n.message,redacted:!1}:n instanceof ae?{message:n.message,redacted:!1}:null}function He(n,e,t){let r=t??(o=>console.error(o)),s=Qn(e);if(s)return s.redacted&&r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${he(e)}`),`the ${n} upstream failed: ${s.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ge(i)?`the ${n} upstream failed: ${i}`:(r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${he(e)}`),`the ${n} upstream failed while serving this request`)}function ve(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ge(e)?e:null}function he(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}C();import{randomUUID as Rs}from"crypto";function I(n){return`${n}_${Rs().replace(/-/g,"").slice(0,24)}`}var It=4*1024*1024,Zt=8*1024*1024,Et=512,Tt=20*1024*1024;function Q(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Je(n,e){return{type:"server_error",code:n,message:e}}function H(n){return{type:"error",event_id:I("event"),error:n}}function en(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var T=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},As={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},Is={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Es={format:!0,voice:!0,speed:!0};function Ts(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ge(n,e){if(!Array.isArray(n)||n.length===0)throw new T(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let r of n){if(r!=="text"&&r!=="audio")throw new T(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(r)||t.push(r)}return t}function Zn(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new T(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Os=10;function tn(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:Os})}function at(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new T("session must be an object","session","invalid_request");let s=n,i=Object.keys(s).filter(a=>!(a in As));if(i.length>0)throw new T(`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=Ge(s.modalities,"modalities"),u=Ge(s.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new T("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 T(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new T(`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 T('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 T(`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=Ge(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new T('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(!Ts(u))throw new T(`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 T("model must be a string or null","model");o.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new T("instructions must be a string or null","instructions");o.instructions=tn(u??void 0)??void 0;break;case"voice":if(u===null){delete o.voice;break}if(typeof u!="string")throw new T("voice must be a string or null","voice");if(!t.voice)throw new T("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 T(`${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 T("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 T(`${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 T("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 T("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 T("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 T("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new T(`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,y]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new T(`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(y!=null&&y!==c[p])throw new T(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(y)}, 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 T("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 T("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 T(`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 T(`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 T("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 T("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 T("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Is))throw new T(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Zn(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=at({input_audio_transcription:d.transcription},o,t,r);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=at({turn_detection:d.turn_detection},o,t,r);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new T("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 T("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Es))throw new T(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Zn(d.format,"audio.output.format"),d.speed!==void 0)throw new T("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 T("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new T("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 Ot(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 nn(n,e){let t=n;if(!t||typeof t!="object")throw new T("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 T("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:I("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 T('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new T("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 T("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 T(`${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 T("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 T("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}throw new T(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:I("item"),type:"message",role:r,content:s}}throw new T(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Pt(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 Cs=1001,Ms=1011,er=n=>n.slice(0,120),Ls=/^[A-Za-z0-9+/=]*$/,$s=2;function Fs(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>$s)return!1;return!0}var ut=class{id=I("conn");ws;binding;onClosed;operatorLog;config=en();sessionId=I("sess");conversationId=I("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;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.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.send({type:"session.created",event_id:I("event"),session:Ot(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:I("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}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 Y&&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(H(Je("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:I("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:I("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:I("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:I("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:I("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:I("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:I("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:I("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=I("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:I("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:I("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:I("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:I("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(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>It){this.fail(Q("frame_too_large",`frame exceeds the ${It}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(H({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Je(null,this.callerLine(s,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let t=at(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(H(Q("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:I("event"),session:Ot(this.config,this.sessionId)});return}case"conversation.item.create":{let t=nn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(t),this.send({type:"conversation.item.added",event_id:I("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(H(Q("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:I("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(H(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:I("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(H(Q("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:I("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(H(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ls.test(e.audio)){this.send(H(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+t>Tt){this.send(H(Q("buffer_full",`uncommitted input audio exceeds the ${Tt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=t;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=t;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:I("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(H(Q("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=I("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:I("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:I("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:I("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:I("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(H(Q("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(H(Q("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;default:this.send(H(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(H(Q("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 Error("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(H({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 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(H(Q("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?Ge(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?Ge(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 T("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(H(Q("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.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let o=I("req"),a=`resp_${o}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:Pt(this.items),c=tn(typeof t.instructions=="string"?t.instructions:this.config.instructions),p=typeof t.temperature=="number"?t.temperature:this.config.temperature,y=t.max_output_tokens??this.config.maxOutputTokens,m=y==="inf"||y===void 0?void 0:y,x=t.tools!==void 0?t.tools:this.config.tools,O=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,k={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...m!==void 0?{max_output_tokens:m}:{},...x!==void 0?{tools:x}:{},...O!==void 0?{tool_choice:O}:{}};if(!(u&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],h=v=>{this.responseFlushed?this.send(v):f.push(v)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:I("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:I("event"),response:this.responseObject(a,"in_progress")});for(let v of f)this.send(v);f.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},A=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(R=>{this.pendingTranscriptSettled=R}),this.cancelled||this.closed))return;l=this.items.length,d=Pt(this.items)}let{input:v,sawAudioOnlyItem:S}=d??{input:[],sawAudioOnlyItem:!1},E={...k,input:v,...u?this.compositeTurnAsk(t):{}};S&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let b;try{b=await this.upstreamStream(E,o)}catch(R){this.upstreamTurnFault(R,a);return}try{for await(let R of b){if(this.cancelled)break;let _=R;if(_.type==="error"){let P=this.upstreamErrorBody(_);this.responseFlushed?this.send(H(P)):this.send({type:"response.failed",event_id:I("event"),response:this.failedResponse(a,P)});return}if(_.type==="response.output_text.delta"&&typeof _.delta=="string"){g(),w.messageOpen||(this.beginMessageItem(a,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&h({type:"response.output_text.delta",event_id:I("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,h({type:"response.output_audio_transcript.delta",event_id:I("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta})),w.messageText+=_.delta;continue}if(_.type==="response.function_call_arguments.delta"){g();let P=typeof _.delta=="string"?_.delta:"",D=typeof _.call_id=="string"&&_.call_id.length>0?_.call_id:`${a}_fc_${w.nextOutputIndex}`,F=w.tools.get(D);if(!F){let W=typeof _.name=="string"&&_.name.length>0?_.name:void 0;F={outputIndex:w.nextOutputIndex++,name:W,args:""},w.tools.set(D,F);let U={id:D,object:"realtime.item",type:"function_call",call_id:D,name:W??"",arguments:"",status:"in_progress"};h({type:"response.output_item.added",event_id:I("event"),response_id:a,output_index:F.outputIndex,item:U}),this.emitAssistantItemAdded(U)}typeof _.name=="string"&&_.name.length>0&&(F.name=_.name),F.args+=P,h({type:"response.function_call_arguments.delta",event_id:I("event"),item_id:D,response_id:a,output_index:F.outputIndex,call_id:D,name:F.name??"",delta:P});continue}if(_.type==="response.completed"){A=_.response??null;continue}}}catch(R){this.upstreamTurnFault(R,a);return}if(this.cancelled)return;this.closeOpenItems(a,w,l),g(),this.send({type:"response.done",event_id:I("event"),response:this.doneResponse(a,l,A)})}finally{this.inFlight=null,this.activeResponseId=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(Fs(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(H({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:I("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:I("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:I("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:I("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:I("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:I("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:I("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:I("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:I("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:I("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:I("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:I("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:I("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:I("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:I("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:I("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=ve(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??ye(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failSessionGone(e){let t=e instanceof Error&&ge(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: ${he(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(Je("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Y){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ps&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Je(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(H(r)):this.send({type:"response.failed",event_id:I("event"),response:this.failedResponse(t,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(H(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let t=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,t?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:I("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Et&&(this.items.shift(),this.send(H({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Et} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}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}:{}}:{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>Zt){this.ws.close(Cs,er("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${he(e)}`),r.message}fail(e,t){this.send(H(e)),this.ws.close(Ms,er(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.binding.composite===!0&&this.binding.cancelActiveTurn?.();let t=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,t?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let s=r.return?.();s&&s.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(s=>tr(this.id,`binding release failed: ${s instanceof Error?s.message:String(s)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),tr(this.id,e)}},rn=[];function tr(n,e){rn.push({id:n,reason:e}),rn.length>256&&rn.shift()}C();import{SessionFailedError as nr}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ds}from"@urun-sh/core";var Ns={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},qs={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 lt(n,e){let t=qs[n.code];return e?`${t} (${e})`:t}function Ct(n){if(n==null)return null;let e=Ns[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 Mt(n){if(n.kind==="create-failed")return Ct(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=Ds;return Ct(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as Us}from"ws";var on="/v1/realtime",Bs=n=>n.slice(0,120);function js(n,e,t){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
5
+ `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of r.clients)o.close(1001,"server closing");await new Promise((o,a)=>r.close(u=>u===void 0?o():a(u)))})(),i)}function Vo(n,e,t=new St){new Rt(n,e,t)}C();var Ie=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)}},ot=class extends Ie{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Qt=class extends Ie{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")}},me=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Xn=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(){let e=this.slots.filter(t=>t.state==="paused"&&!t.opening).sort((t,r)=>t.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}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};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.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 ot;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 ot;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);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let u=r+t-Date.now();if(u<=0)throw new Qt(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 ot}}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);(r||s)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let i=s.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=r.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1;let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.signalDrain())}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)},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(),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,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);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 Ps}from"@urun-sh/core";C();C();var we=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ae=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};C();import{SessionFailedError as Yn}from"@urun-sh/core";var fe=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)}},ks=33e4;function na(n,e=ks){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,i=new Promise((l,d)=>{s=d}),o=setTimeout(()=>s(new At),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof Y||l instanceof Yn&&l.kind==="transport-failed"?l:l instanceof At?(await r.return?.(void 0),new fe("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 fe("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 fe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var At=class extends Error{constructor(){super("stream idle timeout")}};function ra(n){return n instanceof fe?!1:n instanceof Y?!0:n instanceof Yn?n.kind==="transport-failed":!1}var Ss=[/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 ge(n){return!Ss.some(e=>e.test(n))}function ye(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 ue(n,e){if(n instanceof Y)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=Qn(n);return t||{message:ye(e?.inferenceId??null),redacted:!0}}function Qn(n){return n instanceof Cn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof Pn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof q?{message:n.message,redacted:!1}:n instanceof we?{message:n.message,redacted:!1}:n instanceof Ie?{message:n.message,redacted:!1}:n instanceof fe?ge(n.message)?{message:n.message,redacted:!1}:null:n instanceof me?{message:n.message,redacted:!1}:n instanceof ae?{message:n.message,redacted:!1}:null}function He(n,e,t){let r=t??(o=>console.error(o)),s=Qn(e);if(s)return s.redacted&&r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${he(e)}`),`the ${n} upstream failed: ${s.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ge(i)?`the ${n} upstream failed: ${i}`:(r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${he(e)}`),`the ${n} upstream failed while serving this request`)}function ve(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ge(e)?e:null}function he(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}C();import{randomUUID as Rs}from"crypto";function I(n){return`${n}_${Rs().replace(/-/g,"").slice(0,24)}`}var It=4*1024*1024,Zt=8*1024*1024,Et=512,Tt=20*1024*1024;function Q(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Je(n,e){return{type:"server_error",code:n,message:e}}function H(n){return{type:"error",event_id:I("event"),error:n}}function en(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var T=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},As={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},Is={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Es={format:!0,voice:!0,speed:!0};function Ts(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ge(n,e){if(!Array.isArray(n)||n.length===0)throw new T(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let r of n){if(r!=="text"&&r!=="audio")throw new T(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(r)||t.push(r)}return t}function Zn(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new T(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Os=10;function tn(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:Os})}function at(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new T("session must be an object","session","invalid_request");let s=n,i=Object.keys(s).filter(a=>!(a in As));if(i.length>0)throw new T(`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=Ge(s.modalities,"modalities"),u=Ge(s.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new T("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 T(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new T(`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 T('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 T(`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=Ge(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new T('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(!Ts(u))throw new T(`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 T("model must be a string or null","model");o.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new T("instructions must be a string or null","instructions");o.instructions=tn(u??void 0)??void 0;break;case"voice":if(u===null){delete o.voice;break}if(typeof u!="string")throw new T("voice must be a string or null","voice");if(!t.voice)throw new T("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 T(`${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 T("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 T(`${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 T("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 T("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 T("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 T("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new T(`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,y]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new T(`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(y!=null&&y!==c[p])throw new T(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(y)}, 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 T("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 T("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 T(`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 T(`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 T("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 T("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 T("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Is))throw new T(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Zn(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=at({input_audio_transcription:d.transcription},o,t,r);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=at({turn_detection:d.turn_detection},o,t,r);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new T("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 T("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Es))throw new T(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Zn(d.format,"audio.output.format"),d.speed!==void 0)throw new T("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 T("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new T("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 Ot(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 nn(n,e){let t=n;if(!t||typeof t!="object")throw new T("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 T("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:I("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 T('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new T("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 T("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 T(`${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 T("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 T("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}throw new T(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:I("item"),type:"message",role:r,content:s}}throw new T(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Pt(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 Cs=1001,Ms=1011,er=n=>n.slice(0,120),Ls=/^[A-Za-z0-9+/=]*$/,$s=2;function Fs(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>$s)return!1;return!0}var ut=class{id=I("conn");ws;binding;onClosed;operatorLog;config=en();sessionId=I("sess");conversationId=I("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;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.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.send({type:"session.created",event_id:I("event"),session:Ot(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:I("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}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 Y&&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(H(Je("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:I("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:I("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:I("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:I("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:I("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:I("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:I("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:I("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=I("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:I("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:I("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:I("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:I("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(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>It){this.fail(Q("frame_too_large",`frame exceeds the ${It}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(Q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Q("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(H({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}this.fail(Je(null,this.callerLine(s,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let t=at(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(H(Q("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:I("event"),session:Ot(this.config,this.sessionId)});return}case"conversation.item.create":{let t=nn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(t),this.send({type:"conversation.item.added",event_id:I("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(H(Q("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:I("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(H(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:I("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(H(Q("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:I("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(H(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ls.test(e.audio)){this.send(H(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+t>Tt){this.send(H(Q("buffer_full",`uncommitted input audio exceeds the ${Tt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=t;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=t;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:I("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(H(Q("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=I("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:I("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:I("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:I("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:I("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(H(Q("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(H(Q("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;default:this.send(H(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(H(Q("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 Error("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(H({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 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(H(Q("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?Ge(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?Ge(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 T("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(H(Q("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.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let o=I("req"),a=`resp_${o}`;this.activeResponseId=a;let u=this.binding.composite===!0,l=u?0:this.items.length,d=u?null:Pt(this.items),c=tn(typeof t.instructions=="string"?t.instructions:this.config.instructions),p=typeof t.temperature=="number"?t.temperature:this.config.temperature,y=t.max_output_tokens??this.config.maxOutputTokens,m=y==="inf"||y===void 0?void 0:y,x=t.tools!==void 0?t.tools:this.config.tools,O=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,k={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...m!==void 0?{max_output_tokens:m}:{},...x!==void 0?{tools:x}:{},...O!==void 0?{tool_choice:O}:{}};if(!(u&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],h=v=>{this.responseFlushed?this.send(v):f.push(v)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:I("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:I("event"),response:this.responseObject(a,"in_progress")});for(let v of f)this.send(v);f.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},A=null;try{if(u){if(this.pendingTranscriptItemId!==null&&(await new Promise(R=>{this.pendingTranscriptSettled=R}),this.cancelled||this.closed))return;l=this.items.length,d=Pt(this.items)}let{input:v,sawAudioOnlyItem:S}=d??{input:[],sawAudioOnlyItem:!1},E={...k,input:v,...u?this.compositeTurnAsk(t):{}};S&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let b;try{b=await this.upstreamStream(E,o)}catch(R){this.upstreamTurnFault(R,a);return}try{for await(let R of b){if(this.cancelled)break;let _=R;if(_.type==="error"){let P=this.upstreamErrorBody(_);this.responseFlushed?this.send(H(P)):this.send({type:"response.failed",event_id:I("event"),response:this.failedResponse(a,P)});return}if(_.type==="response.output_text.delta"&&typeof _.delta=="string"){g(),w.messageOpen||(this.beginMessageItem(a,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&h({type:"response.output_text.delta",event_id:I("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,h({type:"response.output_audio_transcript.delta",event_id:I("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:_.delta})),w.messageText+=_.delta;continue}if(_.type==="response.function_call_arguments.delta"){g();let P=typeof _.delta=="string"?_.delta:"",D=typeof _.call_id=="string"&&_.call_id.length>0?_.call_id:`${a}_fc_${w.nextOutputIndex}`,F=w.tools.get(D);if(!F){let W=typeof _.name=="string"&&_.name.length>0?_.name:void 0;F={outputIndex:w.nextOutputIndex++,name:W,args:""},w.tools.set(D,F);let U={id:D,object:"realtime.item",type:"function_call",call_id:D,name:W??"",arguments:"",status:"in_progress"};h({type:"response.output_item.added",event_id:I("event"),response_id:a,output_index:F.outputIndex,item:U}),this.emitAssistantItemAdded(U)}typeof _.name=="string"&&_.name.length>0&&(F.name=_.name),F.args+=P,h({type:"response.function_call_arguments.delta",event_id:I("event"),item_id:D,response_id:a,output_index:F.outputIndex,call_id:D,name:F.name??"",delta:P});continue}if(_.type==="response.completed"){A=_.response??null;continue}}}catch(R){this.upstreamTurnFault(R,a);return}if(this.cancelled)return;this.closeOpenItems(a,w,l),g(),this.send({type:"response.done",event_id:I("event"),response:this.doneResponse(a,l,A)})}finally{this.inFlight=null,this.activeResponseId=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(Fs(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(H({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:I("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:I("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:I("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:I("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:I("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:I("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:I("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:I("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:I("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:I("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:I("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:I("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:I("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:I("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:I("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:I("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=ve(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??ye(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failSessionGone(e){let t=e instanceof Error&&ge(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: ${he(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(Je("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Y){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ps&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Je(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(H(r)):this.send({type:"response.failed",event_id:I("event"),response:this.failedResponse(t,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(H(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let t=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,t?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:I("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Et&&(this.items.shift(),this.send(H({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Et} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}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}:{}}:{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>Zt){this.ws.close(Cs,er("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=ue(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${he(e)}`),r.message}fail(e,t){this.send(H(e)),this.ws.close(Ms,er(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.binding.composite===!0&&this.binding.cancelActiveTurn?.();let t=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,t?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let s=r.return?.();s&&s.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(s=>tr(this.id,`binding release failed: ${s instanceof Error?s.message:String(s)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),tr(this.id,e)}},rn=[];function tr(n,e){rn.push({id:n,reason:e}),rn.length>256&&rn.shift()}C();import{SessionFailedError as nr}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ds}from"@urun-sh/core";var Ns={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},qs={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 lt(n,e){let t=qs[n.code];return e?`${t} (${e})`:t}function Ct(n){if(n==null)return null;let e=Ns[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 Mt(n){if(n.kind==="create-failed")return Ct(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=Ds;return Ct(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as Us}from"ws";var on="/v1/realtime",Bs=n=>n.slice(0,120);function js(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
6
  Connection: close\r
7
7
  Content-Type: text/plain\r
8
8
  \r
9
9
  ${Bs(t)}\r
10
10
  `),n.destroy()}function Hs(n){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...n})}
11
11
  `}function Gs(n){Ae(process.stdout,n)}function Js(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function sn(n){return n.audioSession?.audio.sessionId??void 0}function an(n,e){let t=new Us({noServer:!0}),r=new Set;return n.on("upgrade",(s,i,o)=>{if(new URL(s.url??"/","http://localhost").pathname!==on)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=I("rtup"),l=Js(s),d=w=>{(e.log??Gs)(Hs(w))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,p=null,y=w=>{p??=w,c.abort(new Error(p))},m=()=>y("client socket closed"),x=()=>y("client socket closed (half-close)"),O=w=>y(`client socket error: ${w.message}`);i.once("close",m),i.once("end",x),i.once("error",O);let k=()=>{i.removeListener("close",m),i.removeListener("end",x),i.removeListener("error",O)},f=w=>{d({stage:"close",conn:u,model:l,...w})},h=w=>{let A=w,v=A.session!=null&&typeof A.session.sendResponseCreate=="function",S=A.clients!=null&&typeof A.clients.createResponse=="function";if(!v&&!S)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((E,b)=>{t.handleUpgrade(s,i,o,R=>{try{new ut({ws:R,binding:w,operatorLog:e.operatorLog,onClosed:(_,P)=>{f({while:"live",reason:P.reason})}}),d({stage:"admit",conn:u,model:l,...sn(w)===void 0?{}:{session:sn(w)}}),E()}catch(_){b(_)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(s,c.signal).then(async w=>{if(c.signal.aborted){k();let A=sn(w);try{await w.release?.()}catch(v){f({while:"queued",...A===void 0?{}:{session:A},reason:p??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}f({while:"queued",...A===void 0?{}:{session:A},reason:p??"client socket closed",released:!0}),i.destroy();return}k(),await h(w)}).catch(w=>{let A=w instanceof nr?Mt(w):null,v=null;if(w!==null&&typeof w=="object"&&"status"in w){let R=w.status;typeof R=="number"&&(v=R)}let S=v??A?.status??502,E=w instanceof Error?w.message:String(w),b=v!==null?E:A!==null?lt(A,w instanceof nr&&w.status.sessionId?`session ${w.status.sessionId}`:void 0):ue(w).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:E,status:S}}),i.destroyed||js(i,S,b)}).finally(()=>{r.delete(i)})}),async()=>{let s=Date.now()+5e3;for(;r.size>0&&Date.now()<s;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>t.close(()=>i()))}}C();C();import{randomUUID as No}from"crypto";C();import{createServer as co}from"http";C();import{WebSocketServer as si,WebSocket as ft}from"ws";C();C();import{randomUUID as Ws}from"crypto";var rr="Inference-Id";function dt(){return Ws()}function un(n){return n==="/v1"||n.startsWith("/v1/")}function sr(n,e){if(!un(n)||e===null)throw new Error(`no inference turn for ${n}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function ct(n){return`resp_${n}`}function ir(n){return`chatcmpl-${n}`}function or(n){return`msg_${n}`}function de(n){return e=>{n.sessionId=e.sessionId,n.catalog=e.identity}}function ar(n){let e=n.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:n.turn.id,method:n.method,path:n.path,status:n.res.headersSent?n.res.statusCode:null,delivered:n.res.writableFinished,stream_error:n.turn.streamError,model:n.turn.model,stream:n.turn.stream,org:n.turn.org,duration_ms:e()-n.turn.startedAt,ttft_ms:n.turn.stream===!0?n.turn.ttftMs:null,prompt_tokens:n.turn.promptTokens,completion_tokens:n.turn.completionTokens,output_units:n.turn.outputUnits,output_minutes:n.turn.outputMinutes,output_seconds:n.turn.outputSeconds??null,session_id:n.turn.sessionId,queue_ms:n.turn.timing?.queue_ms??null,prefill_ms:n.turn.timing?.prefill_ms??null,decode_ms:n.turn.timing?.decode_ms??null,total_ms:n.turn.timing?.total_ms??null,...n.turn.decision?{decision_resolve_ms:n.turn.decision.resolve_ms,decision_dial_ms:n.turn.decision.dial_ms,decision_first_event_ms:n.turn.decision.first_event_ms,decision_stream_ms:n.turn.decision.stream_ms,decision_question_fwd_ms:n.turn.decision.question_fwd_ms,decision_head_ms:n.turn.decision.head_ms}:{},catalog:n.turn.catalog}}function ur(n){return`${JSON.stringify(n)}
12
- `}var Vs=256,zs=128;function ie(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,zs)}var Le=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=r}modelEntry(e){let t=this.models[e];if(t)return t;let r=Object.keys(this.models).length>=Vs?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t,r){let s=this,i=performance.now(),o=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(o===null&&(o=performance.now(),s.ttftMs.push(o-i),s.ttftMs.length>512&&s.ttftMs.shift(),r!==void 0&&(r.ttftMs=o-r.startedAt)),a+=1,s.tokensOut+=1,s.charsOut+=l.delta.length,t!==void 0&&(s.modelEntry(t).tokens_out+=1)),yield l;let u=(performance.now()-(o??i))/1e3;a>0&&u>0&&(s.tokRates.push(a/u),s.tokRates.length>512&&s.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((r,s)=>r-s);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,r)=>t+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Ks=256;function Xs(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var $e=class extends Error{},We=class{conversations=new Map;thread(e,t){let r=Xs(t);if(e==null)return r;let s=this.conversations.get(String(e));if(!s)throw new $e(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...r]}remember(e,t,r,s=!0){this.conversations.set(e,[...t,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=Ks)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},lr=new WeakMap;function pt(n){let e=lr.get(n);return e||(e=new We,lr.set(n,e)),e}function Ve(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function be(n){return n.find(e=>e.type==="response.completed")?.response??null}function ze(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var Ee=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),r=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},Ys=["<tool_call>","<function="];function Qs(n){return Ys.find(e=>n.includes(e))}function Fe(n,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${n}" (see catalog parser_defaults)`}function De(n,e,t){if(!(!n||e>0))return Qs(t)}function Ke(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function xe(n){let e=n?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Zs(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s=r;s.type==="message"?t.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return t}function ln(n,e){let t=Zs(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var ce=class extends Error{constructor(t,r,s=400,i){super(t);this.code=r;this.status=s;this.param=i}code;status;param};function Xe(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof $e?new ce(t.message,"previous_response_not_found",400,"previous_response_id"):new ce(String(t instanceof Error?t.message:t),"invalid_input")}}function dr(n){let e=n.text;if(e!==null&&typeof e=="object"){let t=e.format;if(t!==void 0)return t}}async function dn(n,e,t,r,s){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ce("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...dr(e)!==void 0?{response_format:dr(e)}:{}},s)}async function mt(n){let{body:e,clients:t,store:r,stats:s}=n,i=Xe(r,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let o=n.responseId,a=n.remember??e.store!==!1,u=e.store!==!1,l=ie(e);s.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=n.turn,p=await dn(t,e,i,!0,c?de(c):void 0);return{responseId:o,events:ri({events:p,conversation:i,responseId:o,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:s,turn:n.turn})}}function ei(n,e){let t=[...n].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],s=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=t.filter(u=>u.type==="message").length===s.length,o=0;return[...t.map(u=>u.type==="message"&&i?ni(s[o++],u):u),...ti(r,t)]}function ti(n,e){let t=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),s=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),o=n.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===o,u=new Set(i.map(s));return n.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!t:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(s(d)):!0})}function ni(n,e){let t=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(n.content)?n.content:[];if(r.filter(t).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(t);if(i===void 0)return e;let o={...n};return o.id=e.id,n.role===void 0&&(o.role=e.role),n.status===void 0&&(o.status=e.status),o.content=r.map(a=>t(a)?{...a,text:i.text}:a),o}async function*ri(n){let{events:e,conversation:t,responseId:r,modelKey:s,requestHadTools:i,remember:o,persist:a,store:u,stats:l}=n,d=[],c=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,y=!1,m=!1,x=0;function*O(){y||(y=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let k=[],f=(M,N)=>{k.push({output_index:M,item:N})},h=!1,g=0,w="",A=0,v="";function*S(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:w,output_index:g,content_index:0,text:v};let M={id:w,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:M},f(g,M),v=""}let E=!1,b=0,R="",_=0,P="",D="";function*F(M){if(!E)return;E=!1,yield{type:"response.output_text.done",item_id:R,output_index:b,content_index:0,text:P},yield{type:"response.content_part.done",item_id:R,output_index:b,content_index:0,part:{type:"output_text",text:P}};let N={id:R,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:P}]};yield{type:"response.output_item.done",output_index:b,item:N},f(b,N),P=""}let W=new Ee,U=null,Re=-1;function*K(M){if(!U)return;let N=U;U=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let B={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:M};yield{type:"response.output_item.done",output_index:N.outputIndex,item:B},f(N.outputIndex,B)}let re=!1;for await(let M of l.track(e,s,n.turn)){d.push(M);let N=String(M.type??"");if(N==="response.created"||N==="response.in_progress"){y=!0,yield c(M);continue}if(N==="response.output_item.added"){m=!0,yield c(M);continue}if(N==="response.reasoning_text.delta"&&!m){yield*O(),h||(h=!0,g=x++,A+=1,w=A===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${A}`,yield{type:"response.output_item.added",output_index:g,item:{id:w,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:w,output_index:g,content_index:0,delta:M.delta};continue}if(N==="response.output_text.delta"&&!m){yield*O(),yield*S(),E||(E=!0,b=x++,_+=1,R=_===1?p:`${p}_${_}`,yield{type:"response.output_item.added",output_index:b,item:{id:R,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:R,output_index:b,content_index:0,part:{type:"output_text",text:""}}),P+=String(M.delta??""),D+=String(M.delta??""),yield{type:N,item_id:R,output_index:b,content_index:0,delta:M.delta};continue}let B=m?null:ze(M);if(B){if(yield*O(),yield*S(),yield*F("completed"),W.add(B),B.tool_index!==Re){yield*K("completed"),Re=B.tool_index;let Oe=x++;U={fcId:`fc_${r.slice(5)}_${B.tool_index}`,outputIndex:Oe,callId:B.call_id,name:B.name,args:""},yield{type:"response.output_item.added",output_index:Oe,item:{id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:"",status:"in_progress"}}}U&&(B.call_id&&(U.callId=B.call_id),B.name&&(U.name=B.name),U.args+=B.delta,yield{type:"response.function_call_arguments.delta",item_id:U.fcId,output_index:U.outputIndex,delta:B.delta});continue}if(N==="response.completed"&&!m){let Oe=Ve(M.response),je=De(i,W.size+Oe.length,D);if(je){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Fe(s,je)}};break}if(yield*S(),yield*F("completed"),yield*K("completed"),W.size===0)for(let X of Oe){let pe=x++,Pe=X.id??X.call_id??`fc_${pe}`,Xt=X.arguments??"",Tn={id:Pe,type:"function_call",call_id:X.call_id??Pe,name:X.name??""};yield{type:"response.output_item.added",output_index:pe,item:{...Tn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Pe,output_index:pe,delta:Xt},yield{type:"response.function_call_arguments.done",item_id:Pe,output_index:pe,arguments:Xt};let On={...Tn,arguments:Xt,status:"completed"};yield{type:"response.output_item.done",output_index:pe,item:On},f(pe,On)}let j=ei(k,M.response);yield j.length>0?c({...M,response:{...M.response,output:j}}):c(M);continue}yield c(M)}if(yield*S(),yield*F("incomplete"),yield*K("incomplete"),o&&!re){let M=be(d);u.remember(r,t,ln(M,Ke(d,M)),a)}}var ii="/v1/responses",oi=64*1024*1024,ai=8*1024*1024,ui=16,cr=32,pr=3600*1e3,li=/^[A-Za-z0-9._-]{1,256}$/;function se(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var di=se(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function mn(){let n,e;return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}async function ci(n){for(;n.bufferedAmount>ai&&n.readyState===ft.OPEN;){let{promise:e,resolve:t}=mn();setTimeout(t,5),await e}}var cn=class extends We{constructor(t){super();this.shared=t}shared;thread(t,r){if(t==null)return super.thread(t,r);try{return super.thread(t,r)}catch(s){if(!(s instanceof $e))throw s;return this.shared.thread(t,r)}}remember(t,r,s,i=!0){i?this.shared.remember(t,r,s):super.remember(t,r,s)}forget(t){super.forget(t),this.shared.forget(t)}},pn=class{constructor(e,t,r,s,i){this.ws=e;this.clients=t;this.stats=r;this.statusOf=s;this.operatorLog=i;this.store=new cn(pt(t)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${pr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},pr).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,t){if(this.closed)return;if(t){this.sendFrame(se(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(se(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(se(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let s=r;if(s.type!=="response.create"){this.sendFrame(se(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(s.type??null)}; only "response.create" is supported`}));return}if("stream"in s){this.sendFrame(se(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in s){this.sendFrame(se(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(s.stream_id!==void 0){if(typeof s.stream_id!="string"||!li.test(s.stream_id)){this.sendFrame(di);return}if(i=s.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=cr){this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${cr}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let o=s.generate===!1?()=>this.runWarmup(s,i):()=>this.runTurn(s,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(o).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,t){if(this.closed)return;await this.acquire();let r=dt();try{let s=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",s,s);let i;try{i=await mt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ct(r)})}catch(a){this.failTurn(a,t,e,r);return}this.laneOfResponse.set(i.responseId,t??null);let o=i.events;this.activeTurns.add(o);try{for await(let a of o){if(this.closed||this.ws.readyState!==ft.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,t,r));break}this.send(a,t),await ci(this.ws)}}finally{this.activeTurns.delete(o)}}catch(s){this.failTurn(s,t,e,r)}finally{this.release()}}runWarmup(e,t){if(this.closed)return;let r=dt(),s=ct(r);try{let i=Xe(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(s,i,[],e.store!==!1),this.laneOfResponse.set(s,t??null),this.send({type:"response.created",response:{id:s,object:"response",status:"in_progress"}},t)}catch(i){this.failTurn(i,t,e,r)}}failTurn(e,t,r,s){this.sendFrame(this.errorFrameOf(e,t,s));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(t??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,t,r){let s=e instanceof Error?e.message:he(e);if(e instanceof ce)return se(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof q)return se(404,{type:"invalid_request_error",code:"model_not_found",message:s},t);if(e instanceof Y){let a=ue(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),se(503,{type:"upstream_error",code:"session_gone",message:a.message},t)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),se(i.status,{type:i.openaiType,message:s},t);let o=ue(e,{inferenceId:r});return o.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),se(500,{type:"upstream_error",message:o.message},t)}upstreamErrorFrameOf(e,t,r){let s=e.error,i=s?.type??"upstream_error",o=ve(s),a=o??ye(r);return o===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),se(i==="invalid_request_error"?400:502,{type:i,...s&&typeof s.code=="string"?{code:s.code}:{},message:a},t)}async acquire(){for(;this.active>=ui;){let{promise:e,resolve:t}=mn();this.waiters.push(t),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,t){if(this.closed||this.ws.readyState!==ft.OPEN)return;let r=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==ft.OPEN||this.ws.send(JSON.stringify(e))}};function Lt(n,e,t){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",s=`${t}\r
12
+ `}var Vs=256,zs=128;function ie(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,zs)}var Le=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=r}modelEntry(e){let t=this.models[e];if(t)return t;let r=Object.keys(this.models).length>=Vs?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t,r){let s=this,i=performance.now(),o=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(o===null&&(o=performance.now(),s.ttftMs.push(o-i),s.ttftMs.length>512&&s.ttftMs.shift(),r!==void 0&&(r.ttftMs=o-r.startedAt)),a+=1,s.tokensOut+=1,s.charsOut+=l.delta.length,t!==void 0&&(s.modelEntry(t).tokens_out+=1)),yield l;let u=(performance.now()-(o??i))/1e3;a>0&&u>0&&(s.tokRates.push(a/u),s.tokRates.length>512&&s.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((r,s)=>r-s);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,r)=>t+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Ks=256;function Xs(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var $e=class extends Error{},We=class{conversations=new Map;thread(e,t){let r=Xs(t);if(e==null)return r;let s=this.conversations.get(String(e));if(!s)throw new $e(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...r]}remember(e,t,r,s=!0){this.conversations.set(e,[...t,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=Ks)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},lr=new WeakMap;function pt(n){let e=lr.get(n);return e||(e=new We,lr.set(n,e)),e}function Ve(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function be(n){return n.find(e=>e.type==="response.completed")?.response??null}function ze(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var Ee=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),r=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},Ys=["<tool_call>","<function="];function Qs(n){return Ys.find(e=>n.includes(e))}function Fe(n,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${n}" (see catalog parser_defaults)`}function De(n,e,t){if(!(!n||e>0))return Qs(t)}function Ke(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function xe(n){let e=n?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Zs(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s=r;s.type==="message"?t.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return t}function ln(n,e){let t=Zs(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var ce=class extends Error{constructor(t,r,s=400,i){super(t);this.code=r;this.status=s;this.param=i}code;status;param};function Xe(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof $e?new ce(t.message,"previous_response_not_found",400,"previous_response_id"):new ce(String(t instanceof Error?t.message:t),"invalid_input")}}function dr(n){let e=n.text;if(e!==null&&typeof e=="object"){let t=e.format;if(t!==void 0)return t}}async function dn(n,e,t,r,s){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ce("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...dr(e)!==void 0?{response_format:dr(e)}:{}},s)}async function mt(n){let{body:e,clients:t,store:r,stats:s}=n,i=Xe(r,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let o=n.responseId,a=n.remember??e.store!==!1,u=e.store!==!1,l=ie(e);s.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=n.turn,p=await dn(t,e,i,!0,c?de(c):void 0);return{responseId:o,events:ri({events:p,conversation:i,responseId:o,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:s,turn:n.turn})}}function ei(n,e){let t=[...n].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],s=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=t.filter(u=>u.type==="message").length===s.length,o=0;return[...t.map(u=>u.type==="message"&&i?ni(s[o++],u):u),...ti(r,t)]}function ti(n,e){let t=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),s=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),o=n.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===o,u=new Set(i.map(s));return n.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!t:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(s(d)):!0})}function ni(n,e){let t=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(n.content)?n.content:[];if(r.filter(t).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(t);if(i===void 0)return e;let o={...n};return o.id=e.id,n.role===void 0&&(o.role=e.role),n.status===void 0&&(o.status=e.status),o.content=r.map(a=>t(a)?{...a,text:i.text}:a),o}async function*ri(n){let{events:e,conversation:t,responseId:r,modelKey:s,requestHadTools:i,remember:o,persist:a,store:u,stats:l}=n,d=[],c=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,y=!1,m=!1,x=0;function*O(){y||(y=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let k=[],f=(M,N)=>{k.push({output_index:M,item:N})},h=!1,g=0,w="",A=0,v="";function*S(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:w,output_index:g,content_index:0,text:v};let M={id:w,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:M},f(g,M),v=""}let E=!1,b=0,R="",_=0,P="",D="";function*F(M){if(!E)return;E=!1,yield{type:"response.output_text.done",item_id:R,output_index:b,content_index:0,text:P},yield{type:"response.content_part.done",item_id:R,output_index:b,content_index:0,part:{type:"output_text",text:P}};let N={id:R,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:P}]};yield{type:"response.output_item.done",output_index:b,item:N},f(b,N),P=""}let W=new Ee,U=null,Re=-1;function*K(M){if(!U)return;let N=U;U=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let B={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:M};yield{type:"response.output_item.done",output_index:N.outputIndex,item:B},f(N.outputIndex,B)}let re=!1;for await(let M of l.track(e,s,n.turn)){d.push(M);let N=String(M.type??"");if(N==="response.created"||N==="response.in_progress"){y=!0,yield c(M);continue}if(N==="response.output_item.added"){m=!0,yield c(M);continue}if(N==="response.reasoning_text.delta"&&!m){yield*O(),h||(h=!0,g=x++,A+=1,w=A===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${A}`,yield{type:"response.output_item.added",output_index:g,item:{id:w,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:w,output_index:g,content_index:0,delta:M.delta};continue}if(N==="response.output_text.delta"&&!m){yield*O(),yield*S(),E||(E=!0,b=x++,_+=1,R=_===1?p:`${p}_${_}`,yield{type:"response.output_item.added",output_index:b,item:{id:R,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:R,output_index:b,content_index:0,part:{type:"output_text",text:""}}),P+=String(M.delta??""),D+=String(M.delta??""),yield{type:N,item_id:R,output_index:b,content_index:0,delta:M.delta};continue}let B=m?null:ze(M);if(B){if(yield*O(),yield*S(),yield*F("completed"),W.add(B),B.tool_index!==Re){yield*K("completed"),Re=B.tool_index;let Oe=x++;U={fcId:`fc_${r.slice(5)}_${B.tool_index}`,outputIndex:Oe,callId:B.call_id,name:B.name,args:""},yield{type:"response.output_item.added",output_index:Oe,item:{id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:"",status:"in_progress"}}}U&&(B.call_id&&(U.callId=B.call_id),B.name&&(U.name=B.name),U.args+=B.delta,yield{type:"response.function_call_arguments.delta",item_id:U.fcId,output_index:U.outputIndex,delta:B.delta});continue}if(N==="response.completed"&&!m){let Oe=Ve(M.response),je=De(i,W.size+Oe.length,D);if(je){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Fe(s,je)}};break}if(yield*S(),yield*F("completed"),yield*K("completed"),W.size===0)for(let X of Oe){let pe=x++,Pe=X.id??X.call_id??`fc_${pe}`,Xt=X.arguments??"",Tn={id:Pe,type:"function_call",call_id:X.call_id??Pe,name:X.name??""};yield{type:"response.output_item.added",output_index:pe,item:{...Tn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Pe,output_index:pe,delta:Xt},yield{type:"response.function_call_arguments.done",item_id:Pe,output_index:pe,arguments:Xt};let On={...Tn,arguments:Xt,status:"completed"};yield{type:"response.output_item.done",output_index:pe,item:On},f(pe,On)}let j=ei(k,M.response);yield j.length>0?c({...M,response:{...M.response,output:j}}):c(M);continue}yield c(M)}if(yield*S(),yield*F("incomplete"),yield*K("incomplete"),o&&!re){let M=be(d);u.remember(r,t,ln(M,Ke(d,M)),a)}}var ii="/v1/responses",oi=64*1024*1024,ai=8*1024*1024,ui=16,cr=32,pr=3600*1e3,li=/^[A-Za-z0-9._-]{1,256}$/;function se(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var di=se(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function mn(){let n,e;return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}async function ci(n){for(;n.bufferedAmount>ai&&n.readyState===ft.OPEN;){let{promise:e,resolve:t}=mn();setTimeout(t,5),await e}}var cn=class extends We{constructor(t){super();this.shared=t}shared;thread(t,r){if(t==null)return super.thread(t,r);try{return super.thread(t,r)}catch(s){if(!(s instanceof $e))throw s;return this.shared.thread(t,r)}}remember(t,r,s,i=!0){i?this.shared.remember(t,r,s):super.remember(t,r,s)}forget(t){super.forget(t),this.shared.forget(t)}},pn=class{constructor(e,t,r,s,i){this.ws=e;this.clients=t;this.stats=r;this.statusOf=s;this.operatorLog=i;this.store=new cn(pt(t)),e.on("message",(a,u)=>this.onMessage(a,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${pr/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},pr).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,t){if(this.closed)return;if(t){this.sendFrame(se(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(se(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(se(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let s=r;if(s.type!=="response.create"){this.sendFrame(se(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(s.type??null)}; only "response.create" is supported`}));return}if("stream"in s){this.sendFrame(se(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in s){this.sendFrame(se(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(s.stream_id!==void 0){if(typeof s.stream_id!="string"||!li.test(s.stream_id)){this.sendFrame(di);return}if(i=s.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=cr){this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${cr}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let o=s.generate===!1?()=>this.runWarmup(s,i):()=>this.runTurn(s,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(o).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,t){if(this.closed)return;await this.acquire();let r=dt();try{let s=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",s,s);let i;try{i=await mt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ct(r)})}catch(a){this.failTurn(a,t,e,r);return}this.laneOfResponse.set(i.responseId,t??null);let o=i.events;this.activeTurns.add(o);try{for await(let a of o){if(this.closed||this.ws.readyState!==ft.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,t,r));break}this.send(a,t),await ci(this.ws)}}finally{this.activeTurns.delete(o)}}catch(s){this.failTurn(s,t,e,r)}finally{this.release()}}runWarmup(e,t){if(this.closed)return;let r=dt(),s=ct(r);try{let i=Xe(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(s,i,[],e.store!==!1),this.laneOfResponse.set(s,t??null),this.send({type:"response.created",response:{id:s,object:"response",status:"in_progress"}},t)}catch(i){this.failTurn(i,t,e,r)}}failTurn(e,t,r,s){this.sendFrame(this.errorFrameOf(e,t,s));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(t??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,t,r){let s=e instanceof Error?e.message:he(e);if(e instanceof ce)return se(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof q)return se(404,{type:"invalid_request_error",code:"model_not_found",message:s},t);if(e instanceof Y){let a=ue(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),se(503,{type:"upstream_error",code:"session_gone",message:a.message},t)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),se(i.status,{type:i.openaiType,message:s},t);let o=ue(e,{inferenceId:r});return o.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),se(500,{type:"upstream_error",message:o.message},t)}upstreamErrorFrameOf(e,t,r){let s=e.error,i=s?.type??"upstream_error",o=ve(s),a=o??ye(r);return o===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),se(i==="invalid_request_error"?400:502,{type:i,...s&&typeof s.code=="string"?{code:s.code}:{},message:a},t)}async acquire(){for(;this.active>=ui;){let{promise:e,resolve:t}=mn();this.waiters.push(t),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,t){if(this.closed||this.ws.readyState!==ft.OPEN)return;let r=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==ft.OPEN||this.ws.send(JSON.stringify(e))}};function Lt(n,e,t){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",s=`${t}\r
13
13
  `;n.end(`HTTP/1.1 ${e} ${r}\r
14
14
  Connection: close\r
15
15
  Content-Type: text/plain; charset=utf-8\r
@@ -52,7 +52,7 @@ data: ${JSON.stringify(h)}
52
52
  `),t.end();return}finally{P?.flush(),P?.dispose()}}let x="",O="",k=[],f=new Ee;for await(let b of r.track(m,p,s)){k.push(b),b.type==="response.output_text.delta"&&typeof b.delta=="string"&&(x+=b.delta),b.type==="response.reasoning_text.delta"&&typeof b.delta=="string"&&(O+=b.delta);let R=ze(b);if(R&&f.add(R),b.type==="error"){An(t,b,{inferenceId:s.id,operatorError:o});return}}let h=be(k);Be(s,h);let g=kn(h),w=g.length>0?g:kn({output:f.items()}),A=De(y,w.length,x);if(A){J(t,502,Fe(p,A),"upstream_error");return}let v=w.map(({index:b,...R})=>R),S={role:"assistant",content:x||null},E=O||hs(h);E&&(S.reasoning_content=E),v.length>0&&(S.tool_calls=v),ne(t,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:S,finish_reason:v.length>0?"tool_calls":"stop"}],usage:ps(h)})}var So="sense-latest";async function Ro(n,e,t,r,s,i){if(n===null||typeof n!="object"||Array.isArray(n)){J(t,400,"systemone requires a JSON object body");return}delete n.key;let o=typeof n.model=="string"&&n.model?n.model:So,a=ie({model:o});if(s.model=a,s.stream=!1,n.state===void 0||n.state===null){J(t,400,"systemone requires a state (string or JSON structure)");return}let u=n.questions;if(u===null||typeof u!="object"||Array.isArray(u)||Object.keys(u).length===0){J(t,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(n.media!==void 0&&!Array.isArray(n.media)){J(t,400,"systemone media, when present, must be an array");return}let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};s.decision=l;let d=performance.now();r.model(a),await zt(s,e,o),l.resolve_ms=Math.round(performance.now()-d);let c,p=performance.now();try{c=await e.createResponse({model:o,input:[{role:"user",content:JSON.stringify(n)}],stream:!0},de(s))}catch(f){if(f instanceof q){rt(t,"openai",f);return}if(f instanceof me){t.setHeader("retry-after","2"),J(t,503,f.message,"capacity_error");return}if(f instanceof ae){t.setHeader("retry-after","2"),J(t,503,f.message,"capacity_error");return}throw f}l.dial_ms=Math.round(performance.now()-p);let y=[],m=null;try{for await(let f of r.track(c,a,s))if(m===null&&(m=performance.now(),l.first_event_ms=Math.round(m-p)),y.push(f),f.type==="error"){An(t,f,{inferenceId:s.id,operatorError:i});return}}catch(f){if(f instanceof q){m!==null&&(l.stream_ms=Math.round(performance.now()-m)),rt(t,"openai",f);return}if(f instanceof me){m!==null&&(l.stream_ms=Math.round(performance.now()-m)),t.setHeader("retry-after","2"),J(t,503,f.message,"capacity_error");return}if(f instanceof ae){m!==null&&(l.stream_ms=Math.round(performance.now()-m)),t.setHeader("retry-after","2"),J(t,503,f.message,"capacity_error");return}throw m!==null&&(l.stream_ms=Math.round(performance.now()-m)),f}m!==null&&(l.stream_ms=Math.round(performance.now()-m));let x=be(y);if(x==null){J(t,502,"upstream produced no response.completed event","upstream_error");return}Be(s,x);let O=Ke(y,x),k;try{k=JSON.parse(O)}catch{J(t,502,"systemone answer was not valid JSON","upstream_error");return}if(k===null||typeof k!="object"||Array.isArray(k)){J(t,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"timing"in k){let f=k.timing;if(typeof f=="object"&&f!==null&&!Array.isArray(f)&&"question_fwd_ms"in f&&"head_ms"in f){let h=g=>typeof g=="number"&&Number.isFinite(g)&&g>=0?Math.round(g):null;l.question_fwd_ms=h(f.question_fwd_ms),l.head_ms=h(f.head_ms)}}ne(t,200,k)}function Ao(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var bt=class extends Error{};function Vt(n){return new bt(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Io(n){if(Array.isArray(n))return n.map(e=>{let t=e;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function Eo(n){if(n==null)return;let e=n.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:n.name};throw new bt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function To(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw Vt(typeof n);let e="";for(let t of n){let r=String(t.type??"");if(r!=="text")throw Vt(`tool_result > ${r}`);e+=String(t.text??"")}return e}function Oo(n){let{role:e,content:t}=n;if(typeof t=="string")return[{role:e,content:t}];if(t==null)return[];if(!Array.isArray(t))throw Vt(typeof t);let r=[],s="",i=()=>{s&&(r.push({role:e,content:s}),s="")};for(let o of t){let a=String(o.type??"");if(a==="text")s+=String(o.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:o.tool_use_id,output:To(o.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Vt(a)}}return i(),r}function Sn(n){return Ve(n).map((e,t)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${t}`,name:e.name??"",input:r}})}async function Po(n,e,t,r,s,i){let o=n.messages;if(!Array.isArray(o)){_e(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof n.max_tokens!="number"||!Number.isInteger(n.max_tokens)||n.max_tokens<1){_e(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){_e(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(n.stop_sequences!==void 0&&(!Array.isArray(n.stop_sequences)||n.stop_sequences.some(S=>typeof S!="string"))){_e(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(n.model??"urun"),u=or(s.id),l=[],d;try{n.system&&l.push({role:"system",content:Ao(n.system)});for(let S of o)l.push(...Oo(S));d=Eo(n.tool_choice)}catch(S){if(S instanceof bt){_e(t,400,"invalid_request_error",S.message);return}throw S}let c=ie(n);r.model(c),s.model=c,s.stream=n.stream===!0,await zt(s,e,typeof n.model=="string"?n.model:void 0);let p=Array.isArray(n.tools)&&n.tools.length>0,y;try{y=await e.createResponse({model:n.model,input:l,stream:!0,tools:Io(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences},de(s))}catch(S){if(S instanceof q){rt(t,"anthropic",S);return}if(S instanceof me||S instanceof ae){t.setHeader("retry-after","2"),_e(t,503,"capacity_error",S.message);return}throw S}let m=(S,E)=>{t.destroyed||t.write(`event: ${S}
53
53
  data: ${JSON.stringify({type:S,...E})}
54
54
 
55
- `)};if(n.stream===!0){let S=r.track(y,c,s);Rn(t),m("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let E=0,b="",R=0,_="none",P=()=>_,D=-1,F=-1,W=new Ee,U=[],Re=()=>{_!=="none"&&(_="none",m("content_block_stop",{index:D}))},K=(j,X)=>{Re(),_=j,D=R++,m("content_block_start",{index:D,content_block:X})};for await(let j of S){if(t.destroyed)break;U.push(j);let X=ze(j);if(j.type==="response.reasoning_text.delta"&&typeof j.delta=="string")P()!=="thinking"&&K("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:D,delta:{type:"thinking_delta",thinking:j.delta}});else if(j.type==="response.output_text.delta"&&typeof j.delta=="string")P()!=="text"&&K("text",{type:"text",text:""}),E+=1,b+=j.delta,m("content_block_delta",{index:D,delta:{type:"text_delta",text:j.delta}});else if(X){let{call:pe}=W.add(X);(P()!=="tool"||X.tool_index!==F)&&(F=X.tool_index,K("tool",{type:"tool_use",id:pe.id??`call_${X.tool_index}`,name:pe.name??"",input:{}})),X.delta&&m("content_block_delta",{index:D,delta:{type:"input_json_delta",partial_json:X.delta}})}else if(j.type==="error"){s.streamError=!0;let pe=j.error,Pe=ve(pe);Pe===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(j)}`),m("error",{error:{type:"api_error",message:Pe??ye(s.id)}}),t.end();return}}if(t.destroyed)return;let re=be(U),M=Ve(re),N=De(p,W.size+M.length,b);if(N){s.streamError=!0,m("error",{error:{type:"api_error",message:Fe(c,N)}}),t.end();return}Re();let B=[];if(W.size===0)try{B=Sn(re)}catch(j){s.streamError=!0;let X=ue(j,{inferenceId:s.id});X.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(j instanceof Error?j.message:j)}`),m("error",{error:{type:"api_error",message:X.message}}),t.end();return}R===0&&B.length===0&&(K("text",{type:"text",text:""}),Re()),B.forEach(j=>{let X=R++;m("content_block_start",{index:X,content_block:{...j,input:{}}}),m("content_block_delta",{index:X,delta:{type:"input_json_delta",partial_json:JSON.stringify(j.input??{})}}),m("content_block_stop",{index:X})});let Oe=W.size>0||B.length>0,je=Jt(re);Be(s,re),m("message_delta",{delta:{stop_reason:Oe?"tool_use":"end_turn"},usage:je?{input_tokens:je.input_tokens,output_tokens:je.output_tokens}:{output_tokens:E}}),m("message_stop",{}),t.end();return}let x="",O="",k=[],f=new Ee;for await(let S of r.track(y,c,s)){k.push(S),S.type==="response.output_text.delta"&&typeof S.delta=="string"&&(x+=S.delta),S.type==="response.reasoning_text.delta"&&typeof S.delta=="string"&&(O+=S.delta);let E=ze(S);if(E&&f.add(E),S.type==="error"){let b=S.error,R=b?.type==="invalid_request_error",_=ve(b);_===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(S)}`),_e(t,R?400:502,R?"invalid_request_error":"api_error",_??ye(s.id));return}if(t.destroyed)break}if(t.destroyed)return;let h=be(k);Be(s,h);let g;try{g=Sn(h),g.length===0&&f.size>0&&(g=Sn({output:f.items()}))}catch(S){let E=ue(S,{inferenceId:s.id});E.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(S instanceof Error?S.message:S)}`),_e(t,502,"api_error",E.message);return}let w=De(p,g.length,x);if(w){_e(t,502,"api_error",Fe(c,w));return}let A=[],v=O||hs(h);v&&A.push({type:"thinking",thinking:v}),(x||g.length===0)&&A.push({type:"text",text:x}),A.push(...g),ne(t,200,{id:u,type:"message",role:"assistant",content:A,model:a,stop_reason:g.length>0?"tool_use":"end_turn",usage:Jt(h)??{input_tokens:0,output_tokens:0}})}function Co(n){Ae(process.stdout,n)}function Mo(n){let{clients:e,apiKey:t,identity:r,statusOf:s}=n,i=typeof e=="function"?e:()=>e,o=n.requestLog??Co,a=n.operatorLog??(d=>console.error(d)),u=n.observe,l=new Le;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),y=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(h,g,w,A,v)=>y?_e(c,h,A,g):J(c,h,g,w,v),x=un(p.pathname),O=p.pathname.startsWith("/partners/"),k=x||O?{id:dt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;k&&(c.setHeader(rr,k.id),c.once("close",()=>{let h=ar({turn:k,method:d.method??"",path:p.pathname,res:c});o(ur(h)),u?.(h),us({record:h,ledger:n.ledger??null,req:d})}));let f=()=>sr(p.pathname,k);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ne(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ne(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===Kr?"canonical":p.pathname===wn?"huggingface":null;if(h){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=n.usage;if(!v){m(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let S=v.authorize(d),E;try{E=await cs(d,Xr)}catch(_){if(_ instanceof vt){m(413,_.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=_=>v.lookup(S,_),R;try{if(h==="canonical"){let _=Yr(E),P=await b(_);Ht(P,_),R={requests:P}}else R=await Zr(E,b)}catch(_){if(_ instanceof Te){m(_.status,_.message,"invalid_request_error","invalid_request_error");return}throw _}ne(c,200,R);return}if(d.method==="GET"&&p.pathname===st){let v=await i(d);if(k&&(k.org=v.tenant??null),!v.openRouterModels){m(501,`GET ${st} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ne(c,200,await v.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${wn} and GET ${st}`,"invalid_request_error","not_found_error");return}let g=await i(d);if(k&&(k.org=g.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:st}),c.end();return}ne(c,200,await g.listModels());return}if(d.method==="GET"&&p.pathname===gr){if(!g.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ne(c,200,await g.listImageModels());return}if(hr(p.pathname)){if(!g.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let v={clients:g,imageModels:g.supportsImages,stats:l,turn:f(),operatorLog:a};p.pathname===Dt?await Ar(d,c,v):await Rr(d,c,v);return}if(d.method==="GET"&&p.pathname===Br){if(!g.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ne(c,200,await g.listSpeechToTextModels());return}if(Ur(p.pathname)){if(!g.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Bt}`,"not_implemented","not_implemented_error");return}let v={clients:g,transcriptionModels:g.supportsTranscription,stats:l,turn:f(),operatorLog:a};await Gr(d,c,v);return}if($r(p.pathname)){if(!g.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${gt}`,"not_implemented","not_implemented_error");return}let v={clients:g,speechModels:g.supportsSpeech,stats:l,turn:f(),operatorLog:a};await qr(d,c,v);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let w;try{w=await cs(d)}catch(v){if(v instanceof vt){m(413,v.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let A=Buffer.byteLength(JSON.stringify(w));if(p.pathname==="/v1/responses"){l.request("responses",A,A),await xo(w,g,pt(g),c,l,f(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",A,A),await ko(w,g,c,l,f(),d.headers[xn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",A,A),await Ro(w,g,c,l,f(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",A,A),await Po(w,g,c,l,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",A,A),_e(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let g=String(h instanceof Error?h.message:h);if(!c.headersSent){let v=s?.(h)??null;if(v){v.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),m(v.status,g,v.openaiType,v.anthropicType);return}if(h instanceof po){let E=Ct(h.code);if(E){let b=h.retryAfterSeconds??(E.status===429?30:void 0);b!==void 0&&c.setHeader("Retry-After",String(b)),m(E.status,lt(E,h.code??void 0),E.openaiType,E.anthropicType,E.code);return}}if(h instanceof mo){let E=Mt(h);if(E){let b=E.status===429?30:void 0;b!==void 0&&c.setHeader("Retry-After",String(b)),m(E.status,lt(E,h.status.sessionId?`session ${h.status.sessionId}`:void 0),E.openaiType,E.anthropicType,E.code);return}}if(h instanceof Z){m(502,g,"upstream_error","api_error");return}if(h instanceof fe){h.retryable&&c.setHeader("Retry-After","1");let E=ue(h,{inferenceId:k?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),m(502,E.message,"upstream_error","api_error",h.code);return}if(h instanceof Ie){c.setHeader("Retry-After",String(h.retryAfterSeconds)),m(h.status,g,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let S=ue(h,{inferenceId:k?.id??null});S.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),m(500,S.message,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0);let w=h instanceof fe?h.code:null,A=ue(h,{inferenceId:k?.id??null});A.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),c.destroyed||(y?c.write(`event: error
55
+ `)};if(n.stream===!0){let S=r.track(y,c,s);Rn(t),m("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let E=0,b="",R=0,_="none",P=()=>_,D=-1,F=-1,W=new Ee,U=[],Re=()=>{_!=="none"&&(_="none",m("content_block_stop",{index:D}))},K=(j,X)=>{Re(),_=j,D=R++,m("content_block_start",{index:D,content_block:X})};for await(let j of S){if(t.destroyed)break;U.push(j);let X=ze(j);if(j.type==="response.reasoning_text.delta"&&typeof j.delta=="string")P()!=="thinking"&&K("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:D,delta:{type:"thinking_delta",thinking:j.delta}});else if(j.type==="response.output_text.delta"&&typeof j.delta=="string")P()!=="text"&&K("text",{type:"text",text:""}),E+=1,b+=j.delta,m("content_block_delta",{index:D,delta:{type:"text_delta",text:j.delta}});else if(X){let{call:pe}=W.add(X);(P()!=="tool"||X.tool_index!==F)&&(F=X.tool_index,K("tool",{type:"tool_use",id:pe.id??`call_${X.tool_index}`,name:pe.name??"",input:{}})),X.delta&&m("content_block_delta",{index:D,delta:{type:"input_json_delta",partial_json:X.delta}})}else if(j.type==="error"){s.streamError=!0;let pe=j.error,Pe=ve(pe);Pe===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(j)}`),m("error",{error:{type:"api_error",message:Pe??ye(s.id)}}),t.end();return}}if(t.destroyed)return;let re=be(U),M=Ve(re),N=De(p,W.size+M.length,b);if(N){s.streamError=!0,m("error",{error:{type:"api_error",message:Fe(c,N)}}),t.end();return}Re();let B=[];if(W.size===0)try{B=Sn(re)}catch(j){s.streamError=!0;let X=ue(j,{inferenceId:s.id});X.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(j instanceof Error?j.message:j)}`),m("error",{error:{type:"api_error",message:X.message}}),t.end();return}R===0&&B.length===0&&(K("text",{type:"text",text:""}),Re()),B.forEach(j=>{let X=R++;m("content_block_start",{index:X,content_block:{...j,input:{}}}),m("content_block_delta",{index:X,delta:{type:"input_json_delta",partial_json:JSON.stringify(j.input??{})}}),m("content_block_stop",{index:X})});let Oe=W.size>0||B.length>0,je=Jt(re);Be(s,re),m("message_delta",{delta:{stop_reason:Oe?"tool_use":"end_turn"},usage:je?{input_tokens:je.input_tokens,output_tokens:je.output_tokens}:{output_tokens:E}}),m("message_stop",{}),t.end();return}let x="",O="",k=[],f=new Ee;for await(let S of r.track(y,c,s)){k.push(S),S.type==="response.output_text.delta"&&typeof S.delta=="string"&&(x+=S.delta),S.type==="response.reasoning_text.delta"&&typeof S.delta=="string"&&(O+=S.delta);let E=ze(S);if(E&&f.add(E),S.type==="error"){let b=S.error,R=b?.type==="invalid_request_error",_=ve(b);_===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(S)}`),_e(t,R?400:502,R?"invalid_request_error":"api_error",_??ye(s.id));return}if(t.destroyed)break}if(t.destroyed)return;let h=be(k);Be(s,h);let g;try{g=Sn(h),g.length===0&&f.size>0&&(g=Sn({output:f.items()}))}catch(S){let E=ue(S,{inferenceId:s.id});E.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(S instanceof Error?S.message:S)}`),_e(t,502,"api_error",E.message);return}let w=De(p,g.length,x);if(w){_e(t,502,"api_error",Fe(c,w));return}let A=[],v=O||hs(h);v&&A.push({type:"thinking",thinking:v}),(x||g.length===0)&&A.push({type:"text",text:x}),A.push(...g),ne(t,200,{id:u,type:"message",role:"assistant",content:A,model:a,stop_reason:g.length>0?"tool_use":"end_turn",usage:Jt(h)??{input_tokens:0,output_tokens:0}})}function Co(n){Ae(process.stdout,n)}function Mo(n){let{clients:e,apiKey:t,identity:r,statusOf:s}=n,i=typeof e=="function"?e:()=>e,o=n.requestLog??Co,a=n.operatorLog??(d=>console.error(d)),u=n.observe,l=new Le;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),y=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),m=(h,g,w,A,v)=>y?_e(c,h,A,g):J(c,h,g,w,v),x=un(p.pathname),O=p.pathname.startsWith("/partners/"),k=x||O?{id:dt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;k&&(c.setHeader(rr,k.id),c.once("close",()=>{let h=ar({turn:k,method:d.method??"",path:p.pathname,res:c});o(ur(h)),u?.(h),us({record:h,ledger:n.ledger??null,req:d})}));let f=()=>sr(p.pathname,k);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ne(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ne(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===Kr?"canonical":p.pathname===wn?"huggingface":null;if(h){if(d.method!=="POST"){m(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=n.usage;if(!v){m(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let S=v.authorize(d),E;try{E=await cs(d,Xr)}catch(_){if(_ instanceof vt){m(413,_.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=_=>v.lookup(S,_),R;try{if(h==="canonical"){let _=Yr(E),P=await b(_);Ht(P,_),R={requests:P}}else R=await Zr(E,b)}catch(_){if(_ instanceof Te){m(_.status,_.message,"invalid_request_error","invalid_request_error");return}throw _}ne(c,200,R);return}if(d.method==="GET"&&p.pathname===st){let v=await i(d);if(k&&(k.org=v.tenant??null),!v.openRouterModels){m(501,`GET ${st} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ne(c,200,await v.openRouterModels());return}if(p.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${wn} and GET ${st}`,"invalid_request_error","not_found_error");return}let g=await i(d);if(k&&(k.org=g.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:st}),c.end();return}ne(c,200,await g.listModels());return}if(d.method==="GET"&&p.pathname===gr){if(!g.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ne(c,200,await g.listImageModels());return}if(hr(p.pathname)){if(!g.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let v={clients:g,imageModels:g.supportsImages,stats:l,turn:f(),operatorLog:a};p.pathname===Dt?await Ar(d,c,v):await Rr(d,c,v);return}if(d.method==="GET"&&p.pathname===Br){if(!g.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ne(c,200,await g.listSpeechToTextModels());return}if(Ur(p.pathname)){if(!g.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Bt}`,"not_implemented","not_implemented_error");return}let v={clients:g,transcriptionModels:g.supportsTranscription,stats:l,turn:f(),operatorLog:a};await Gr(d,c,v);return}if($r(p.pathname)){if(!g.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${gt}`,"not_implemented","not_implemented_error");return}let v={clients:g,speechModels:g.supportsSpeech,stats:l,turn:f(),operatorLog:a};await qr(d,c,v);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let w;try{w=await cs(d)}catch(v){if(v instanceof vt){m(413,v.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let A=Buffer.byteLength(JSON.stringify(w));if(p.pathname==="/v1/responses"){l.request("responses",A,A),await xo(w,g,pt(g),c,l,f(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",A,A),await ko(w,g,c,l,f(),d.headers[xn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",A,A),await Ro(w,g,c,l,f(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",A,A),await Po(w,g,c,l,f(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",A,A),_e(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let g=String(h instanceof Error?h.message:h);if(!c.headersSent){let v=s?.(h)??null;if(v){v.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),m(v.status,g,v.openaiType,v.anthropicType,v.code);return}if(h instanceof po){let E=Ct(h.code);if(E){let b=h.retryAfterSeconds??(E.status===429?30:void 0);b!==void 0&&c.setHeader("Retry-After",String(b)),m(E.status,lt(E,h.code??void 0),E.openaiType,E.anthropicType,E.code);return}}if(h instanceof mo){let E=Mt(h);if(E){let b=E.status===429?30:void 0;b!==void 0&&c.setHeader("Retry-After",String(b)),m(E.status,lt(E,h.status.sessionId?`session ${h.status.sessionId}`:void 0),E.openaiType,E.anthropicType,E.code);return}}if(h instanceof Z){m(502,g,"upstream_error","api_error");return}if(h instanceof fe){h.retryable&&c.setHeader("Retry-After","1");let E=ue(h,{inferenceId:k?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),m(502,E.message,"upstream_error","api_error",h.code);return}if(h instanceof Ie){c.setHeader("Retry-After",String(h.retryAfterSeconds)),m(h.status,g,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let S=ue(h,{inferenceId:k?.id??null});S.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),m(500,S.message,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0);let w=h instanceof fe?h.code:null,A=ue(h,{inferenceId:k?.id??null});A.redacted&&a(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:he(h)}`),c.destroyed||(y?c.write(`event: error
56
56
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:A.message}})}
57
57
 
58
58
  `):c.write(`data: ${JSON.stringify({error:{message:A.message,type:"upstream_error",code:w}})}