@urun-sh/openai 0.6.54 → 0.6.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
- import{a as Kn,c as Xn,d as Fe,e as Mt,f as re,g as Yn,h as Qn,i as Zn,j as es,k as ts,l as ns,m as ss,n as rs,r as is,t as os,u as as,v as us,w as ls,x as ds}from"./chunk-X5BLQXHK.js";import{a as on,e as an}from"./chunk-64VO62LW.js";import{a as Oe,b as ye,v as Pe}from"./chunk-S32BCZSV.js";import{a as Vn,e as ct,f as zn,i as J,j as Q,k as un,l as ln}from"./chunk-N3Y2GDQK.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as Hr}from"crypto";import{WebSocketServer as Gr}from"ws";var Jr=256,Ct=class{snapshots=new Map;store(e,t,s){for(this.snapshots.set(`${e}\0${t}`,s);this.snapshots.size>Jr;){let r=this.snapshots.keys().next().value;this.snapshots.delete(r)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Wr="local",pt=n=>n.slice(0,120),Lt=class{constructor(e,t,s){this.ws=e;this.call=t;this.registry=s;this.clients=t.clients,this.scope=t.scope,e.on("message",r=>this.onMessage(r)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Xn,pt(e.message));return}if(e instanceof Q){this.ws.close(Mt,pt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,pt(e.message));return}this.ws.close(Fe,pt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Yn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let s=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:i}=rs(t.clientContent);this.transcript.push(...r),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=os(t.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,s);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:is);return}this.transcript.push(...as(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=ts(e),s=t.sessionResumption.handle;if(s!==null){let i=this.registry.get(this.scope,s);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Mt);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(s)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Mt);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 r={};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(es(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},r[Qn]=Zn(o.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let s=await t.call(this.clients,e.model);return this.detachAudio=s.onOutputAudio(r=>this.send(ls(r))),s})(),this.audio.catch(s=>this.fail(s)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(s=>this.fail(s)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let s=Hr();this.registry.store(this.scope,s,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(s),this.send(ns(s))}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,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(ss(e.timeLeftMs)),this.ws.close(Fe,pt(`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 s=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),r,i=!1;for await(let u of s){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){r=l.response,i=!0;continue}let d=us(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=ds(r);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,s){super(s);this.status=t;this.name="UpgradeAuthError"}status};function Vr(n,e,t){let s=new Set;(u=>{if(typeof u=="string")u!==""&&s.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&s.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&s.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&s.add(o),s.size>1)throw new De(401,`contradictory credentials: ${s.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of s)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function cs(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 s=new Gr({noServer:!0}),r=new Ct;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Kn&&(a.on("error",()=>{}),(async()=>{let d=Vr(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:Wr}}s.handleUpgrade(o,a,u,p=>{new Lt(p,c,r)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
1
+ import{a as Xn,c as Yn,d as Fe,e as Ct,f as re,g as Qn,h as Zn,i as es,j as ts,k as ns,l as ss,m as rs,n as is,r as os,t as as,u as us,v as ls,w as ds,x as cs}from"./chunk-KV3UXLNF.js";import{a as an,b as Mt,f as un}from"./chunk-MYNG74AX.js";import{a as Oe,b as ye,v as Pe}from"./chunk-6R3TCKOH.js";import{a as zn,e as ct,f as Kn,i as J,j as Q,k as ln,l as dn}from"./chunk-N3Y2GDQK.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as Gr}from"crypto";import{WebSocketServer as Jr}from"ws";var Wr=256,Lt=class{snapshots=new Map;store(e,t,s){for(this.snapshots.set(`${e}\0${t}`,s);this.snapshots.size>Wr;){let r=this.snapshots.keys().next().value;this.snapshots.delete(r)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Vr="local",pt=n=>n.slice(0,120),$t=class{constructor(e,t,s){this.ws=e;this.call=t;this.registry=s;this.clients=t.clients,this.scope=t.scope,e.on("message",r=>this.onMessage(r)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Yn,pt(e.message));return}if(e instanceof Q){this.ws.close(Ct,pt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,pt(e.message));return}this.ws.close(Fe,pt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Qn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let s=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:i}=is(t.clientContent);this.transcript.push(...r),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=as(t.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,s);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:os);return}this.transcript.push(...us(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=ns(e),s=t.sessionResumption.handle;if(s!==null){let i=this.registry.get(this.scope,s);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Ct);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(s)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Ct);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 r={};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(ts(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},r[Zn]=es(o.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let s=await t.call(this.clients,e.model);return this.detachAudio=s.onOutputAudio(r=>this.send(ds(r))),s})(),this.audio.catch(s=>this.fail(s)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(s=>this.fail(s)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let s=Gr();this.registry.store(this.scope,s,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(s),this.send(ss(s))}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,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(rs(e.timeLeftMs)),this.ws.close(Fe,pt(`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 s=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),r,i=!1;for await(let u of s){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){r=l.response,i=!0;continue}let d=ls(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=cs(r);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,s){super(s);this.status=t;this.name="UpgradeAuthError"}status};function zr(n,e,t){let s=new Set;(u=>{if(typeof u=="string")u!==""&&s.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&s.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&s.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&s.add(o),s.size>1)throw new De(401,`contradictory credentials: ${s.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of s)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ps(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 s=new Jr({noServer:!0}),r=new Lt;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Xn&&(a.on("error",()=>{}),(async()=>{let d=zr(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:Vr}}s.handleUpgrade(o,a,u,p=>{new $t(p,c,r)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
2
2
  Connection: close\r
3
3
  \r
4
4
  ${m}\r
5
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of s.clients)o.close(1001,"server closing");await new Promise((o,a)=>s.close(u=>u===void 0?o():a(u)))})(),i)}function Ia(n,e,t=new Ct){new Lt(n,e,t)}C();var Me=class extends Error{code;status;retryAfterSeconds;constructor(e,t,s,r){super(r),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=s,Object.setPrototypeOf(this,new.target.prototype)}},mt=class extends Me{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},dn=class extends Me{constructor(e,t=!1){super("acquire_timeout",429,30,t?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},ps=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},s=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(s<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=s,this.reap()}slotKey(e,t=0){let s=`decision:${this.opts.replicaId}:${e}`;return t===0?s:`${s}:${t}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let t=this.now(),s=this.slots.filter(r=>r.state==="paused"&&!r.opening&&(e||!r.dead)&&(!r.dead||t>=r.nextDialAt)).sort((r,i)=>r.slot.index-i.slot.index);return s.length>0?(this.openRuntime(s[0]),s[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let t=this.slots[e];t.dead&&!t.opening&&t.inFlight===0&&(t.backoffTimer&&(clearTimeout(t.backoffTimer),t.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,s={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(s),this.openRuntime(s),s}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(t)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${t instanceof Error?t.message:String(t)}`):(e.state="paused",this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new mt;this.lastDemandAt=this.now();let t=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,s=Date.now();for(;;){let r=this.tryLease();if(r)return this.pump(),r;if(this.draining)throw new mt;let i=this.slots.some(c=>c.state==="queued"),o=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let u=s+t-Date.now();if(u<=0)throw new dn(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 mt}}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(s=>s.state==="queued")&&this.slots.length<this.opts.max){let s=!this.slots.some(i=>i.state==="attached"),r=this.slots.some(i=>i.dead&&!i.opening&&this.now()>=i.nextDialAt);(s||r)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let s=this.slots[t];if(s.state!=="attached"||s.entry===null)continue;let r=s.entry;if(r===null||typeof r!="object"||!("session"in r))return!1;let i=r.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=s.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),s.entry!==null&&s.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 s=e;s.inFlight+=1,this.opts.onLease?.(t);let r=!1;return{slot:s.slot,entry:t,release:()=>{r||(r=!0,s.inFlight=Math.max(0,s.inFlight-1),s.inFlight===0&&(s.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(s=>s.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let t=this.slots.find(s=>s.entry===e);t&&(t.entry=null,t.opening=null,this.rotate(t,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,t){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let s=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+s,s>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},s)),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),s=this.slots.filter(i=>i.state==="attached").length,r=Math.max(0,Math.min(t.length,s-this.opts.min));for(let i of t.slice(0,r))this.endSlot(i);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(t=>t.state==="attached"||t.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(r=>r.state==="attached").length,t=this.slots.filter(r=>r.state==="queued").length,s=this.slots.filter(r=>r.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:s,inFlight:this.slots.reduce((r,i)=>r+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,s)=>t+s.inFlight,0)>0){if(!this.drainComplete){let s,r=new Promise(i=>{s=i});this.drainComplete={promise:r,resolve:s}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(s=>setTimeout(s,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let r of this.waiters.splice(0))r.settled||(r.settled=!0,r.resolve());let e=this.slots.map(r=>r.entry).filter(r=>r!==null);for(let r of this.slots)clearTimeout(r.backoffTimer),r.backoffTimer=void 0;this.slots.length=0;let s=(await Promise.allSettled(e.map(r=>this.opts.closeSlot(r)))).filter(r=>r.status==="rejected");if(s.length>0)throw new Error(`failed to end ${s.length} decision pool session(s)`)}};C();import{SessionFailedError as ni}from"@urun-sh/core";C();C();import{SessionFailedError as ms}from"@urun-sh/core";var we=class extends Error{kind;code;retryable;constructor(e,t,s,r){super(t),this.name="DecisionStreamError",this.kind=e,this.code=s,this.retryable=r,Object.setPrototypeOf(this,new.target.prototype)}},zr=33e4;function La(n,e=zr){return(async function*(){let s=n[Symbol.asyncIterator]();for(;;){let r,i=new Promise((l,d)=>{r=d}),o=setTimeout(()=>r(new $t),e),a;try{a=await Promise.race([s.next(),i])}catch(l){throw l instanceof Q||l instanceof ms&&l.kind==="transport-failed"?l:l instanceof $t?(await s.return?.(void 0),new we("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new we("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(o)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new we("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var $t=class extends Error{constructor(){super("stream idle timeout")}};function $a(n){return n instanceof we?!1:n instanceof Q?!0:n instanceof ms?n.kind==="transport-failed":!1}var Kr=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ve(n){return!Kr.some(e=>e.test(n))}function be(n){return n==null||n===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${n} when reporting it`}function ce(n,e){if(n instanceof Q)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let t=fs(n);return t||{message:be(e?.inferenceId??null),redacted:!0}}function fs(n){return n instanceof zn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof Vn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof J?{message:n.message,redacted:!1}:n instanceof Oe?{message:n.message,redacted:!1}:n instanceof Me?{message:n.message,redacted:!1}:n instanceof we?ve(n.message)?{message:n.message,redacted:!1}:null:n instanceof _e?{message:n.message,redacted:!1}:n instanceof ye?{message:n.message,redacted:!1}:null}function ze(n,e,t){let s=t??(o=>console.error(o)),r=fs(e);if(r)return r.redacted&&s(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${me(e)}`),`the ${n} upstream failed: ${r.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ve(i)?`the ${n} upstream failed: ${i}`:(s(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${me(e)}`),`the ${n} upstream failed while serving this request`)}function xe(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ve(e)?e:null}function me(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}C();import{randomUUID as Xr}from"crypto";function x(n){return`${n}_${Xr().replace(/-/g,"").slice(0,24)}`}var Ft=4*1024*1024,cn=8*1024*1024,pn=512,Xe=20*1024*1024;function X(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Re(n,e){return{type:"server_error",code:n,message:e}}function G(n){return{type:"error",event_id:x("event"),error:n}}function mn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(t,s,r="invalid_value"){super(t);this.param=s;this.code=r;this.name="SessionUpdateError"}param;code},Yr={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},Qr={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Zr={format:!0,voice:!0,speed:!0};function ei(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ke(n,e){if(!Array.isArray(n)||n.length===0)throw new E(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let s of n){if(s!=="text"&&s!=="audio")throw new E(`modality ${JSON.stringify(s)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(s)||t.push(s)}return t}function hs(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new E(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var ti=10;function fn(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:ti})}function ft(n,e,t,s){if(!n||typeof n!="object"||Array.isArray(n))throw new E("session must be an object","session","invalid_request");let r=n,i=Object.keys(r).filter(a=>!(a in Yr));if(i.length>0)throw new E(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(r.modalities!==void 0&&r.output_modalities!==void 0){let a=Ke(r.modalities,"modalities"),u=Ke(r.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new E("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let o={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(r))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new E(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new E(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!t.turns)throw new E('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");o.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?s:null;if(u!==l)throw new E(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=Ke(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new E('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");o.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!ei(u))throw new E(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new E("model must be a string or null","model");o.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new E("instructions must be a string or null","instructions");o.instructions=fn(u??void 0)??void 0;break;case"voice":if(u===null){delete o.voice;break}if(typeof u!="string")throw new E("voice must be a string or null","voice");if(!t.voice)throw new E("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");o.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new E(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new E("temperature must be a finite number or null","temperature");o.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new E(`${a} must be a positive integer, "inf" or null`,a);o.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new E("tools must be an array","tools");o.tools=u;break;case"tool_choice":o.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new E("metadata must be an object or null","metadata");o.metadata=u??null;break;case"turn_detection":{if(u===null){o.turnDetection=null;break}if(!t.turns)throw new E("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new E(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new E(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new E(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}o.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){o.inputAudioTranscription=!1;break}if(!t.turns)throw new E("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new E("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new E(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==t.model)throw new E(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${t.model===void 0?"the unnamed default app":JSON.stringify(t.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}o.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new E("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Qr))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&hs(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ft({input_audio_transcription:d.transcription},o,t,s);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=ft({turn_detection:d.turn_detection},o,t,s);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new E("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Zr))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&hs(d.format,"audio.output.format"),d.speed!==void 0)throw new E("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete o.voice;else{if(typeof d.voice!="string")throw new E("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new E("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");o.voice=d.voice}d.format!==void 0&&!o.outputModalities.includes("audio")&&(o.outputModalities=["text","audio"])}break}default:break}return o}function Dt(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 hn(n,e){let t=n;if(!t||typeof t!="object")throw new E("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new E("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:x("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let s=t.role;if(s!=="user"&&s!=="assistant"&&s!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new E("message item content must be an array","item.content","invalid_request");let r=[];for(let i of t.content){let o=i;if(!o||typeof o!="object")throw new E("content part must be an object","item.content","invalid_request");if(o.type==="input_text"||s==="assistant"&&o.type==="output_text"){if(typeof o.text!="string")throw new E(`${String(o.type)} part requires string text`,"item.content.text","invalid_request");r.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){if(!e)throw new E("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof o.audio!="string")throw new E("input_audio part requires base64 audio","item.content.audio","invalid_request");r.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}if(o.type==="input_image"){if(s!=="user")throw new E("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof o.image_url=="string"?o.image_url:o.image_url?.url;if(typeof a!="string"||a.length===0)throw new E("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new E("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof o.detail=="string"?o.detail:void 0;r.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new E(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:x("item"),type:"message",role:s,content:r}}throw new E(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Nt(n){let e=[],t=!1;for(let s of n){if(s.type==="function_call"){e.push({type:"function_call",call_id:s.callId,name:s.name,arguments:s.arguments??"{}"});continue}if(s.type==="function_call_output"){e.push({type:"function_call_output",call_id:s.callId,output:s.output});continue}let r=[];for(let i of s.content??[]){if(i.type==="input_text"||i.type==="output_text"){r.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){r.push({type:"input_text",text:o});continue}t=!0;continue}}e.push({role:s.role,content:r})}return{input:e,sawAudioOnlyItem:t}}var si=1001,ri=1011,ii=6e4,oi=3e5,gn=3;var qt=class extends Error{},Ut=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ne=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},yn=n=>n.slice(0,120),ai=/^[A-Za-z0-9+/=]*$/,ui=2,li=600;function _n(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>ui)return!1;return!0}var ht=class{id=x("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=mn();sessionId=x("sess");conversationId=x("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(t=>console.error(t)),this.turnStallMs=e.turnStallMs??ii,this.responseDeadlineMs=e.responseDeadlineMs??oi,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(t=>{t.reason===un&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:x("event"),session:Dt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:x("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let t of e.replayFrames??[])this.onMessage(t)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let s=await t.next();if(s.done||this.closed||e.signal.aborted)return;this.onTurnEvent(s.value)}}catch(s){if(!this.closed&&!e.signal.aborted)if(s instanceof Q&&this.binding.composite===!0)this.failSessionGone(s);else{let r=this.callerLine(s,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,r):this.send(G(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${r}`)))}}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:x("event"),item_id:e,content_index:0,transcript:t});let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.(),this.emitItemDone(e)}failPendingTranscription(e,t){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:x("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:t}}),this.emitItemDone(e)}writeItemTranscript(e,t){let s=this.items.find(i=>i.id===e);!s||s.type!=="message"||(s.content??[])[0]?.type!=="input_audio"||(s.content=[{type:"input_audio",transcript:t},...(s.content??[]).slice(1)])}emitItemDone(e){let t=this.items.findIndex(s=>s.id===e);t<0||this.send({type:"conversation.item.done",event_id:x("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:"",s=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:x("event"),item_id:s??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&s!==null&&(this.completePendingTranscription(s),this.manuallyDischargedTurnItem=s);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:x("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:x("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let s=this.manuallyDischargedTurnItem;if(s!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:x("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let r=this.turnTranscript.text.trim(),i=r.length>0?r: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:x("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=x("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:x("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:x("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:x("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:x("event"),item_id:o,content_index:0,transcript:i}),this.emitItemDone(o),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(X("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>Ft){this.fail(X("frame_too_large",`frame exceeds the ${Ft}-byte limit`),"invalid_frame");return}let s;try{s=JSON.parse(t)}catch{this.fail(X("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof s.type!="string"||s.type.length===0){this.fail(X("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(s)}catch(r){let i=r;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(r instanceof qt){this.fail(Re(null,this.callerLine(r,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${s.type}):
6
- ${r?.stack??me(r)}`),this.send(G(Re(null,this.callerLine(r,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let t=ft(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(G(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=t,this.send({type:"session.updated",event_id:x("event"),session:Dt(this.config,this.sessionId)});return}case"conversation.item.create":{let t=hn(e.item,this.binding.voice),s=this.items.length>0?this.items[this.items.length-1].id:null,r=t.content??[];(r.length===0||r.some(i=>i.type!=="input_image"))&&this.pushItem(t),this.forwardImageFrames(t),this.send({type:"conversation.item.added",event_id:x("event"),previous_item_id:s,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(s=>s.id===e.item_id);if(t<0){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:x("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(s=>s.id===e.item_id);if(!t){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:x("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(s=>s.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(G(X("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:x("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(G(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ai.test(e.audio)){this.send(G(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,s=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,t);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=s;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=s;return}this.pendingAudioTotalBytes+s>Xe&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${Xe}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${Xe} bytes`));let r=this.pendingAudioTotalBytes+s;for(;r>Xe&&this.pendingAudioBytes.length>0;){let i=this.pendingAudioBytes.shift();r-=Buffer.byteLength(i.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:t}),this.pendingAudioTotalBytes=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:x("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(G(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let s=x("item"),r=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:x("event"),previous_item_id:r,item_id:s}),this.send({type:"conversation.item.added",event_id:x("event"),previous_item_id:r,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:x("event"),item_id:s,content_index:0,transcript:t}),this.emitItemDone(s);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(s,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.manuallyDischargedTurnItem=s}else this.pendingTranscriptItemId=s;else this.emitItemDone(s);return}case"output_audio_buffer.clear":{this.send(G(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(G(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}if(this.binding.duplex){this.send(G(X("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:t==null?"none":t instanceof Error?`error: ${t.message}`:t}))}).catch(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${t instanceof Error?t.message:String(t)}`}))}).finally(()=>{try{this.ws.close(1e3,yn("session ended by client"))}catch{}});return}case"ping":return;default:this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(X("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new qt("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(G({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let t=e[Symbol.asyncIterator](),s=this.turnCancelled,r=!0;try{for(;;){let i;if(r||this.turnStallMs<=0){r=!1;let o=t.next();o.catch(()=>{}),i=s?await Promise.race([o,s]):await o}else{let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Ut),this.turnStallMs)}),u=t.next();u.catch(()=>{}),i=await(s?Promise.race([u,a,s]):Promise.race([u,a])).finally(()=>clearTimeout(o))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(t.return?.()).catch(()=>{})}}async upstreamStream(e,t){let s=this.binding.session;if(s&&typeof s.sendResponseCreate=="function"){let i=e.response??e;return this.config.model&&i.model===void 0&&(i.model=this.config.model),s.sendResponseCreate({type:"response.create",response:i},e.input??[],t)}let r=this.binding.clients;if(r&&typeof r.createResponse=="function"){let{response:i,input:o,...a}=e;return await r.createResponse({...a,input:o})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,t=!1){if(this.inFlight){this.send(G(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=t,this.turnOutputFlowed=!1;let s=e??{},r=s.modalities!==void 0?Ke(s.modalities,"response.modalities"):void 0,i=s.output_modalities!==void 0?Ke(s.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&i!==void 0&&r.slice().sort().join(",")!==i.slice().sort().join(","))throw new E("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((i??r)?.includes("audio")&&!this.ensureVoice())return;if(s.input!==void 0){this.send(G(X("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},u=new Promise((S,A)=>{a=()=>A(new Ne)});this.turnCancelled=u,this.wakeTurnCancelled=()=>a(),u.catch(()=>{});let l=()=>{},d=new Promise((S,A)=>{l=()=>A(new Ne)});this.turnDialGate=d,this.wakeTurnDialGate=()=>l(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let p=x("req"),m=`resp_${p}`;this.activeResponseId=m,this.activeRequestId=p;let f=this.binding.composite===!0,b=f?0:this.items.length,k=f?null:Nt(this.items),_=fn(typeof s.instructions=="string"?s.instructions:this.config.instructions),y=typeof s.temperature=="number"?s.temperature:this.config.temperature,h=s.max_output_tokens??this.config.maxOutputTokens,v=h==="inf"||h===void 0?void 0:h,L=s.tools!==void 0?s.tools:this.config.tools,O=s.tool_choice!==void 0?s.tool_choice:this.config.toolChoice,I={stream:!0,...this.config.model?{model:this.config.model}:{},..._!==void 0?{instructions:_}:{},...y!==void 0?{temperature:y}:{},...v!==void 0?{max_output_tokens:v}:{},...L!==void 0?{tools:L}:{},...O!==void 0?{tool_choice:O}:{}};if(!(f&&!this.ensureVoice())){for(let{audio:S,captureWallMs:A}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(S,A);this.inFlight=(async()=>{let S=[],A=q=>{this.responseFlushed?this.send(q):S.push(q)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:x("event"),response:this.responseObject(m,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(m,"in_progress")});for(let q of S)this.send(q);S.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},R=null,M=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(m,w,b),g(),this.send({type:"response.done",event_id:x("event"),response:this.responseObject(m,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(f){if(this.pendingTranscriptItemId!==null&&(await new Promise(H=>{this.pendingTranscriptSettled=H}),this.cancelled||this.closed))throw new Ne;b=this.items.length,k=Nt(this.items)}let{input:q,sawAudioOnlyItem:j}=k??{input:[],sawAudioOnlyItem:!1},$={...I,input:q,...f?this.compositeTurnAsk(s):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let N;try{let H=this.upstreamStream($,p);Promise.resolve(H).catch(T=>{T instanceof Q&&this.failSessionGone(T)}),N=await Promise.race([H,d])}catch(H){if(H instanceof Ne){this.deadlineFired&&!this.closed&&M();return}this.upstreamTurnFault(H,m);return}g();try{for await(let H of this.stallBoundedTurn(N)){if(this.cancelled)break;let T=H;if(T.type==="error"){let z=this.upstreamErrorBody(T);w.contentFlowed?this.send(G(z)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(m,z)});return}if(T.type==="response.output_text.delta"&&typeof T.delta=="string"){g(),w.contentFlowed=!0,w.messageOpen||(this.beginMessageItem(m,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&A({type:"response.output_text.delta",event_id:x("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:T.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,A({type:"response.output_audio_transcript.delta",event_id:x("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:T.delta})),w.messageText+=T.delta;continue}if(T.type==="response.function_call_arguments.delta"){g(),w.contentFlowed=!0;let z=typeof T.delta=="string"?T.delta:"",P=typeof T.call_id=="string"&&T.call_id.length>0?T.call_id:`${m}_fc_${w.nextOutputIndex}`,F=w.tools.get(P);if(!F){let W=typeof T.name=="string"&&T.name.length>0?T.name:void 0;F={outputIndex:w.nextOutputIndex++,name:W,args:""},w.tools.set(P,F);let Se={id:P,object:"realtime.item",type:"function_call",call_id:P,name:W??"",arguments:"",status:"in_progress"};A({type:"response.output_item.added",event_id:x("event"),response_id:m,output_index:F.outputIndex,item:Se}),this.emitAssistantItemAdded(Se)}typeof T.name=="string"&&T.name.length>0&&(F.name=T.name),F.args+=z,A({type:"response.function_call_arguments.delta",event_id:x("event"),item_id:P,response_id:m,output_index:F.outputIndex,call_id:P,name:F.name??"",delta:z});continue}if(T.type==="response.completed"){R=T.response??null;continue}}}catch(H){if(this.closed)return;if(H instanceof Ne){this.deadlineFired&&M();return}if(this.cancelled)return;if(H instanceof Ut)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${m} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(H,m);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&M();return}this.closeOpenItems(m,w,b),g(),this.send({type:"response.done",event_id:x("event"),response:this.doneResponse(m,b,R)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(w.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let t=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),t===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=gn){this.seamEmptyStreak=0,this.failMemberUnresponsive(t);return}let s=t;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${s} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${gn} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(G(Re("member_unresponsive",`the member served no content for ${gn} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)||t.hz===void 0&&t.cadence_ms===void 0?!1:"questions"in t||"question"in t}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(_n(t))return;this.openDuplexResponse()}else if(_n(t)){if(this.duplexSilenceMs+=Buffer.byteLength(t,"base64")/2/24,this.duplexSilenceMs>=li){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(_n(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:x("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let s=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:x("event"),item_id:s,response_id:e,output_index:0,content_index:0,delta:t})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${x("req")}`}closeDuplexResponse(e){let t=this.activeResponseId;this.closeOpenItems(t,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let s=this.doneResponse(t,this.duplexInputCount,null);this.send({type:"response.done",event_id:x("event"),response:e==="cancelled"?{...s,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:s}),this.activeResponseId=null}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:x("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let s=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:s,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:t,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:x("event"),item_id:s,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 s={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:0,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:x("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,s){if(t.messageOpen||this.messageItemOpenForAudio){let r=`${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:x("event"),item_id:r,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:x("event"),item_id:r,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:x("event"),item_id:r,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:x("event"),item_id:r,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:x("event"),item_id:r,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:r,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[r,i]of t.tools){let o=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:x("event"),item_id:r,response_id:e,output_index:i.outputIndex,call_id:r,name:i.name??"",arguments:o});let a={id:r,type:"function_call",callId:r,name:i.name,arguments:o};this.pushItem(a),this.send({type:"response.output_item.done",event_id:x("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,s){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...s??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,s){let r=s&&typeof s.usage=="object"&&s.usage!==null?s.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:r?{input_tokens:typeof r.input_tokens=="number"&&Number.isFinite(r.input_tokens)?r.input_tokens:0,output_tokens:typeof r.output_tokens=="number"&&Number.isFinite(r.output_tokens)?r.output_tokens:0,total_tokens:typeof r.total_tokens=="number"&&Number.isFinite(r.total_tokens)?r.total_tokens:(typeof r.input_tokens=="number"&&Number.isFinite(r.input_tokens)?r.input_tokens:0)+(typeof r.output_tokens=="number"&&Number.isFinite(r.output_tokens)?r.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,s=xe(t);s===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 r=s??be(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:r}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Re(ln,"the organization is out of credits \u2014 top up to continue"),ln))}failSessionGone(e){if(e instanceof Q&&e.reason===un){this.failInsufficientCredits();return}let t=e instanceof Error&&ve(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${me(e)}`);let s=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(Re("session_gone",s),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof ni&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let s=Re(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(s)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(t,s)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let t=this.activeRequestId,s=this.binding.session;t!==null&&typeof s=="object"&&s!==null&&"cancelTurn"in s&&typeof s.cancelTurn=="function"&&s.cancelTurn(t),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let t=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:x("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>pn&&this.items.shift()}forwardImageFrames(e){for(let t of e.content??[]){if(t.type!=="input_image")continue;let s=t.imageUrl.indexOf(","),r=s>=0?Buffer.from(t.imageUrl.slice(s+1),"base64"):Buffer.alloc(0);if(r.byteLength===0){this.send(G(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(r.byteLength>an){this.send(G(X("frame_too_large",`input_image frame is ${r.byteLength} bytes \u2014 over the ${an}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(G(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(r))).catch(i=>this.send(G(Re(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let s=(e.content??[]).map(r=>r.type==="input_text"||r.type==="output_text"?{type:r.type,text:r.text}:r.type==="input_audio"?{type:"input_audio",...r.transcript?{transcript:r.transcript}:{}}:r.type==="input_image"?{type:"input_image",image_url:r.imageUrl,...r.detail?{detail:r.detail}:{}}:{type:"output_audio",transcript:r.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:s}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>cn){this.ws.close(si,yn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let s=ce(e);return s.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${me(e)}`),s.message}fail(e,t){this.send(G(e)),this.ws.close(ri,yn(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let t=this.turnLaneIterator;if(this.turnLaneIterator=null,t!==null){let s=t.return?.();s&&s.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(s=>gs(this.id,`binding release failed: ${s instanceof Error?s.message:String(s)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),gs(this.id,e)}},wn=[];function gs(n,e){wn.push({id:n,reason:e}),wn.length>256&&wn.shift()}C();import{SessionFailedError as ys}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as di}from"@urun-sh/core";var ci={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},pi={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 gt(n,e){let t=pi[n.code];return e?`${t} (${e})`:t}function Bt(n){if(n==null)return null;let e=ci[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 jt(n){if(n.kind==="create-failed")return Bt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=di;return Bt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocket as _s,WebSocketServer as mi}from"ws";var bn="/v1/realtime",ws="urun.admission",vs=n=>n.slice(0,120);function fi(n,e,t){let s=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${s}\r
5
+ `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of s.clients)o.close(1001,"server closing");await new Promise((o,a)=>s.close(u=>u===void 0?o():a(u)))})(),i)}function Ra(n,e,t=new Lt){new $t(n,e,t)}C();var Me=class extends Error{code;status;retryAfterSeconds;constructor(e,t,s,r){super(r),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=s,Object.setPrototypeOf(this,new.target.prototype)}},mt=class extends Me{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},cn=class extends Me{constructor(e,t=!1){super("acquire_timeout",429,30,t?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},ms=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},s=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(s<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=s,this.reap()}slotKey(e,t=0){let s=`decision:${this.opts.replicaId}:${e}`;return t===0?s:`${s}:${t}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let t=this.now(),s=this.slots.filter(r=>r.state==="paused"&&!r.opening&&(e||!r.dead)&&(!r.dead||t>=r.nextDialAt)).sort((r,i)=>r.slot.index-i.slot.index);return s.length>0?(this.openRuntime(s[0]),s[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let t=this.slots[e];t.dead&&!t.opening&&t.inFlight===0&&(t.backoffTimer&&(clearTimeout(t.backoffTimer),t.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,s={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(s),this.openRuntime(s),s}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(t)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${t instanceof Error?t.message:String(t)}`):(e.state="paused",this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new mt;this.lastDemandAt=this.now();let t=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,s=Date.now();for(;;){let r=this.tryLease();if(r)return this.pump(),r;if(this.draining)throw new mt;let i=this.slots.some(c=>c.state==="queued"),o=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let u=s+t-Date.now();if(u<=0)throw new cn(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 mt}}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(s=>s.state==="queued")&&this.slots.length<this.opts.max){let s=!this.slots.some(i=>i.state==="attached"),r=this.slots.some(i=>i.dead&&!i.opening&&this.now()>=i.nextDialAt);(s||r)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let s=this.slots[t];if(s.state!=="attached"||s.entry===null)continue;let r=s.entry;if(r===null||typeof r!="object"||!("session"in r))return!1;let i=r.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=s.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),s.entry!==null&&s.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 s=e;s.inFlight+=1,this.opts.onLease?.(t);let r=!1;return{slot:s.slot,entry:t,release:()=>{r||(r=!0,s.inFlight=Math.max(0,s.inFlight-1),s.inFlight===0&&(s.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(s=>s.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let t=this.slots.find(s=>s.entry===e);t&&(t.entry=null,t.opening=null,this.rotate(t,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,t){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let s=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+s,s>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},s)),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),s=this.slots.filter(i=>i.state==="attached").length,r=Math.max(0,Math.min(t.length,s-this.opts.min));for(let i of t.slice(0,r))this.endSlot(i);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(t=>t.state==="attached"||t.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(r=>r.state==="attached").length,t=this.slots.filter(r=>r.state==="queued").length,s=this.slots.filter(r=>r.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:s,inFlight:this.slots.reduce((r,i)=>r+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,s)=>t+s.inFlight,0)>0){if(!this.drainComplete){let s,r=new Promise(i=>{s=i});this.drainComplete={promise:r,resolve:s}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(s=>setTimeout(s,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let r of this.waiters.splice(0))r.settled||(r.settled=!0,r.resolve());let e=this.slots.map(r=>r.entry).filter(r=>r!==null);for(let r of this.slots)clearTimeout(r.backoffTimer),r.backoffTimer=void 0;this.slots.length=0;let s=(await Promise.allSettled(e.map(r=>this.opts.closeSlot(r)))).filter(r=>r.status==="rejected");if(s.length>0)throw new Error(`failed to end ${s.length} decision pool session(s)`)}};C();import{SessionFailedError as si}from"@urun-sh/core";C();C();import{SessionFailedError as fs}from"@urun-sh/core";var we=class extends Error{kind;code;retryable;constructor(e,t,s,r){super(t),this.name="DecisionStreamError",this.kind=e,this.code=s,this.retryable=r,Object.setPrototypeOf(this,new.target.prototype)}},Kr=33e4;function Ma(n,e=Kr){return(async function*(){let s=n[Symbol.asyncIterator]();for(;;){let r,i=new Promise((l,d)=>{r=d}),o=setTimeout(()=>r(new Ft),e),a;try{a=await Promise.race([s.next(),i])}catch(l){throw l instanceof Q||l instanceof fs&&l.kind==="transport-failed"?l:l instanceof Ft?(await s.return?.(void 0),new we("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new we("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(o)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new we("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Ft=class extends Error{constructor(){super("stream idle timeout")}};function Ca(n){return n instanceof we?!1:n instanceof Q?!0:n instanceof fs?n.kind==="transport-failed":!1}var Xr=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ve(n){return!Xr.some(e=>e.test(n))}function be(n){return n==null||n===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${n} when reporting it`}function ce(n,e){if(n instanceof Q)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let t=hs(n);return t||{message:be(e?.inferenceId??null),redacted:!0}}function hs(n){return n instanceof Kn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof zn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof J?{message:n.message,redacted:!1}:n instanceof Oe?{message:n.message,redacted:!1}:n instanceof Me?{message:n.message,redacted:!1}:n instanceof we?ve(n.message)?{message:n.message,redacted:!1}:null:n instanceof _e?{message:n.message,redacted:!1}:n instanceof ye?{message:n.message,redacted:!1}:null}function ze(n,e,t){let s=t??(o=>console.error(o)),r=hs(e);if(r)return r.redacted&&s(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${me(e)}`),`the ${n} upstream failed: ${r.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ve(i)?`the ${n} upstream failed: ${i}`:(s(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${me(e)}`),`the ${n} upstream failed while serving this request`)}function xe(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ve(e)?e:null}function me(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}C();import{randomUUID as Yr}from"crypto";function S(n){return`${n}_${Yr().replace(/-/g,"").slice(0,24)}`}var Dt=4*1024*1024,pn=8*1024*1024,mn=512,Xe=20*1024*1024;function X(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Re(n,e){return{type:"server_error",code:n,message:e}}function G(n){return{type:"error",event_id:S("event"),error:n}}function fn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(t,s,r="invalid_value"){super(t);this.param=s;this.code=r;this.name="SessionUpdateError"}param;code},Qr={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},Zr={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},ei={format:!0,voice:!0,speed:!0};function ti(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function Ke(n,e){if(!Array.isArray(n)||n.length===0)throw new E(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let s of n){if(s!=="text"&&s!=="audio")throw new E(`modality ${JSON.stringify(s)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(s)||t.push(s)}return t}function gs(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new E(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var ni=10;function hn(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:ni})}function ft(n,e,t,s){if(!n||typeof n!="object"||Array.isArray(n))throw new E("session must be an object","session","invalid_request");let r=n,i=Object.keys(r).filter(a=>!(a in Qr));if(i.length>0)throw new E(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(r.modalities!==void 0&&r.output_modalities!==void 0){let a=Ke(r.modalities,"modalities"),u=Ke(r.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new E("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let o={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(r))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new E(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new E(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!t.turns)throw new E('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");o.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?s:null;if(u!==l)throw new E(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=Ke(u,a);for(let d of l)if(d==="audio"&&!t.voice)throw new E('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");o.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!ti(u))throw new E(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(u!==null&&typeof u!="string")throw new E("model must be a string or null","model");o.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new E("instructions must be a string or null","instructions");o.instructions=hn(u??void 0)??void 0;break;case"voice":if(u===null){delete o.voice;break}if(typeof u!="string")throw new E("voice must be a string or null","voice");if(!t.voice)throw new E("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");o.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new E(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new E("temperature must be a finite number or null","temperature");o.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new E(`${a} must be a positive integer, "inf" or null`,a);o.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new E("tools must be an array","tools");o.tools=u;break;case"tool_choice":o.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new E("metadata must be an object or null","metadata");o.metadata=u??null;break;case"turn_detection":{if(u===null){o.turnDetection=null;break}if(!t.turns)throw new E("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new E(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new E(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new E(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}o.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){o.inputAudioTranscription=!1;break}if(!t.turns)throw new E("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!u||typeof u!="object"||Array.isArray(u))throw new E("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new E(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=u.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==t.model)throw new E(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${t.model===void 0?"the unnamed default app":JSON.stringify(t.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}o.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new E("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(u===null)break;let l=u;if(!l||typeof l!="object"||Array.isArray(l))throw new E("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Zr))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&gs(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ft({input_audio_transcription:d.transcription},o,t,s);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=ft({turn_detection:d.turn_detection},o,t,s);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new E("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in ei))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&gs(d.format,"audio.output.format"),d.speed!==void 0)throw new E("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete o.voice;else{if(typeof d.voice!="string")throw new E("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new E("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");o.voice=d.voice}d.format!==void 0&&!o.outputModalities.includes("audio")&&(o.outputModalities=["text","audio"])}break}default:break}return o}function Nt(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 gn(n,e){let t=n;if(!t||typeof t!="object")throw new E("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new E("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:S("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let s=t.role;if(s!=="user"&&s!=="assistant"&&s!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new E("message item content must be an array","item.content","invalid_request");let r=[];for(let i of t.content){let o=i;if(!o||typeof o!="object")throw new E("content part must be an object","item.content","invalid_request");if(o.type==="input_text"||s==="assistant"&&o.type==="output_text"){if(typeof o.text!="string")throw new E(`${String(o.type)} part requires string text`,"item.content.text","invalid_request");r.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){if(!e)throw new E("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof o.audio!="string")throw new E("input_audio part requires base64 audio","item.content.audio","invalid_request");r.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}if(o.type==="input_image"){if(s!=="user")throw new E("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof o.image_url=="string"?o.image_url:o.image_url?.url;if(typeof a!="string"||a.length===0)throw new E("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new E("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof o.detail=="string"?o.detail:void 0;r.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new E(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:S("item"),type:"message",role:s,content:r}}throw new E(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function qt(n){let e=[],t=!1;for(let s of n){if(s.type==="function_call"){e.push({type:"function_call",call_id:s.callId,name:s.name,arguments:s.arguments??"{}"});continue}if(s.type==="function_call_output"){e.push({type:"function_call_output",call_id:s.callId,output:s.output});continue}let r=[];for(let i of s.content??[]){if(i.type==="input_text"||i.type==="output_text"){r.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){r.push({type:"input_text",text:o});continue}t=!0;continue}}e.push({role:s.role,content:r})}return{input:e,sawAudioOnlyItem:t}}var ri=1001,ii=1011,oi=6e4,ai=3e5,yn=3;var Ut=class extends Error{},Bt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ne=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},_n=n=>n.slice(0,120),ui=/^[A-Za-z0-9+/=]*$/,li=600;function wn(n){return Mt(Buffer.from(n,"base64"))}var ht=class{id=S("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=fn();sessionId=S("sess");conversationId=S("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;userTurnOpen=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(t=>console.error(t)),this.turnStallMs=e.turnStallMs??oi,this.responseDeadlineMs=e.responseDeadlineMs??ai,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(t=>{t.reason===ln&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:S("event"),session:Nt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:S("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane(),this.binding.duplex&&this.ensureVoice();for(let t of e.replayFrames??[])this.onMessage(t)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let s=await t.next();if(s.done||this.closed||e.signal.aborted)return;this.onTurnEvent(s.value)}}catch(s){if(!this.closed&&!e.signal.aborted)if(s instanceof Q&&this.binding.composite===!0)this.failSessionGone(s);else{let r=this.callerLine(s,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,r):this.send(G(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${r}`)))}}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:S("event"),item_id:e,content_index:0,transcript:t});let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.(),this.emitItemDone(e)}failPendingTranscription(e,t){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:S("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:t}}),this.emitItemDone(e)}writeItemTranscript(e,t){let s=this.items.find(i=>i.id===e);!s||s.type!=="message"||(s.content??[])[0]?.type!=="input_audio"||(s.content=[{type:"input_audio",transcript:t},...(s.content??[]).slice(1)])}emitItemDone(e){let t=this.items.findIndex(s=>s.id===e);t<0||this.send({type:"conversation.item.done",event_id:S("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:"",s=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:S("event"),item_id:s??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&s!==null&&(this.completePendingTranscription(s),this.manuallyDischargedTurnItem=s);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:S("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.userTurnOpen=!0,this.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{this.userTurnOpen=!1;let t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:S("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let s=this.manuallyDischargedTurnItem;if(s!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:S("event"),item_id:s,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let r=this.turnTranscript.text.trim(),i=r.length>0?r: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:S("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=S("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:S("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:S("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:S("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:S("event"),item_id:o,content_index:0,transcript:i}),this.emitItemDone(o),this.config.turnDetection?.createResponse&&!this.binding.duplex&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_dropped":{this.userTurnOpen=!1,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:S("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(X("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>Dt){this.fail(X("frame_too_large",`frame exceeds the ${Dt}-byte limit`),"invalid_frame");return}let s;try{s=JSON.parse(t)}catch{this.fail(X("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof s.type!="string"||s.type.length===0){this.fail(X("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(s)}catch(r){let i=r;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(G({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(r instanceof Ut){this.fail(Re(null,this.callerLine(r,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${s.type}):
6
+ ${r?.stack??me(r)}`),this.send(G(Re(null,this.callerLine(r,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let t=ft(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(G(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=t,this.send({type:"session.updated",event_id:S("event"),session:Nt(this.config,this.sessionId)});return}case"conversation.item.create":{let t=gn(e.item,this.binding.voice),s=this.items.length>0?this.items[this.items.length-1].id:null,r=t.content??[];(r.length===0||r.some(i=>i.type!=="input_image"))&&this.pushItem(t),this.forwardImageFrames(t),this.send({type:"conversation.item.added",event_id:S("event"),previous_item_id:s,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(s=>s.id===e.item_id);if(t<0){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:S("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(s=>s.id===e.item_id);if(!t){this.send(G(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:S("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(s=>s.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(G(X("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:S("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(G(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ui.test(e.audio)){this.send(G(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,s=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,t);return}if(this.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=s;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=s;return}this.pendingAudioTotalBytes+s>Xe&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${Xe}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${Xe} bytes`));let r=this.pendingAudioTotalBytes+s;for(;r>Xe&&this.pendingAudioBytes.length>0;){let i=this.pendingAudioBytes.shift();r-=Buffer.byteLength(i.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:t}),this.pendingAudioTotalBytes=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:S("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(G(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let s=S("item"),r=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:s,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:S("event"),previous_item_id:r,item_id:s}),this.send({type:"conversation.item.added",event_id:S("event"),previous_item_id:r,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:S("event"),item_id:s,content_index:0,transcript:t}),this.emitItemDone(s);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(s,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:S("event"),item_id:s,content_index:0,transcript:i}),this.emitItemDone(s),this.manuallyDischargedTurnItem=s}else this.pendingTranscriptItemId=s;else this.emitItemDone(s);return}case"output_audio_buffer.clear":{this.send(G(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(G(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}if(this.binding.duplex){this.send(G(X("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:t==null?"none":t instanceof Error?`error: ${t.message}`:t}))}).catch(t=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${t instanceof Error?t.message:String(t)}`}))}).finally(()=>{try{this.ws.close(1e3,_n("session ended by client"))}catch{}});return}case"ping":return;default:this.send(G(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(G(X("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new Ut("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(G({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let t=e[Symbol.asyncIterator](),s=this.turnCancelled,r=!0;try{for(;;){let i;if(r||this.turnStallMs<=0){r=!1;let o=t.next();o.catch(()=>{}),i=s?await Promise.race([o,s]):await o}else{let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Bt),this.turnStallMs)}),u=t.next();u.catch(()=>{}),i=await(s?Promise.race([u,a,s]):Promise.race([u,a])).finally(()=>clearTimeout(o))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(t.return?.()).catch(()=>{})}}async upstreamStream(e,t){let s=this.binding.session;if(s&&typeof s.sendResponseCreate=="function"){let i=e.response??e;return this.config.model&&i.model===void 0&&(i.model=this.config.model),s.sendResponseCreate({type:"response.create",response:i},e.input??[],t)}let r=this.binding.clients;if(r&&typeof r.createResponse=="function"){let{response:i,input:o,...a}=e;return await r.createResponse({...a,input:o})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e,t=!1){if(this.inFlight){this.send(G(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=t,this.turnOutputFlowed=!1;let s=e??{},r=s.modalities!==void 0?Ke(s.modalities,"response.modalities"):void 0,i=s.output_modalities!==void 0?Ke(s.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&i!==void 0&&r.slice().sort().join(",")!==i.slice().sort().join(","))throw new E("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((i??r)?.includes("audio")&&!this.ensureVoice())return;if(s.input!==void 0){this.send(G(X("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1,this.seamEndedTurn=null,this.clientCancel=!1;let a=()=>{},u=new Promise((x,A)=>{a=()=>A(new Ne)});this.turnCancelled=u,this.wakeTurnCancelled=()=>a(),u.catch(()=>{});let l=()=>{},d=new Promise((x,A)=>{l=()=>A(new Ne)});this.turnDialGate=d,this.wakeTurnDialGate=()=>l(),d.catch(()=>{});let c=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let p=S("req"),m=`resp_${p}`;this.activeResponseId=m,this.activeRequestId=p;let f=this.binding.composite===!0,b=f?0:this.items.length,k=f?null:qt(this.items),_=hn(typeof s.instructions=="string"?s.instructions:this.config.instructions),y=typeof s.temperature=="number"?s.temperature:this.config.temperature,h=s.max_output_tokens??this.config.maxOutputTokens,v=h==="inf"||h===void 0?void 0:h,L=s.tools!==void 0?s.tools:this.config.tools,O=s.tool_choice!==void 0?s.tool_choice:this.config.toolChoice,I={stream:!0,...this.config.model?{model:this.config.model}:{},..._!==void 0?{instructions:_}:{},...y!==void 0?{temperature:y}:{},...v!==void 0?{max_output_tokens:v}:{},...L!==void 0?{tools:L}:{},...O!==void 0?{tool_choice:O}:{}};if(!(f&&!this.ensureVoice())){for(let{audio:x,captureWallMs:A}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(x,A);this.inFlight=(async()=>{let x=[],A=q=>{this.responseFlushed?this.send(q):x.push(q)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:S("event"),response:this.responseObject(m,"in_progress")}),this.send({type:"response.in_progress",event_id:S("event"),response:this.responseObject(m,"in_progress")});for(let q of x)this.send(q);x.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},R=null,M=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(m,w,b),g(),this.send({type:"response.done",event_id:S("event"),response:this.responseObject(m,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(f){if(this.pendingTranscriptItemId!==null&&(await new Promise(H=>{this.pendingTranscriptSettled=H}),this.cancelled||this.closed))throw new Ne;b=this.items.length,k=qt(this.items)}let{input:q,sawAudioOnlyItem:j}=k??{input:[],sawAudioOnlyItem:!1},$={...I,input:q,...f?this.compositeTurnAsk(s):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let N;try{let H=this.upstreamStream($,p);Promise.resolve(H).catch(T=>{T instanceof Q&&this.failSessionGone(T)}),N=await Promise.race([H,d])}catch(H){if(H instanceof Ne){this.deadlineFired&&!this.closed&&M();return}this.upstreamTurnFault(H,m);return}g();try{for await(let H of this.stallBoundedTurn(N)){if(this.cancelled)break;let T=H;if(T.type==="error"){let z=this.upstreamErrorBody(T);w.contentFlowed?this.send(G(z)):this.send({type:"response.failed",event_id:S("event"),response:this.failedResponse(m,z)});return}if(T.type==="response.output_text.delta"&&typeof T.delta=="string"){g(),w.contentFlowed=!0,w.messageOpen||(this.beginMessageItem(m,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&A({type:"response.output_text.delta",event_id:S("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:T.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,A({type:"response.output_audio_transcript.delta",event_id:S("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:T.delta})),w.messageText+=T.delta;continue}if(T.type==="response.function_call_arguments.delta"){g(),w.contentFlowed=!0;let z=typeof T.delta=="string"?T.delta:"",P=typeof T.call_id=="string"&&T.call_id.length>0?T.call_id:`${m}_fc_${w.nextOutputIndex}`,F=w.tools.get(P);if(!F){let W=typeof T.name=="string"&&T.name.length>0?T.name:void 0;F={outputIndex:w.nextOutputIndex++,name:W,args:""},w.tools.set(P,F);let Se={id:P,object:"realtime.item",type:"function_call",call_id:P,name:W??"",arguments:"",status:"in_progress"};A({type:"response.output_item.added",event_id:S("event"),response_id:m,output_index:F.outputIndex,item:Se}),this.emitAssistantItemAdded(Se)}typeof T.name=="string"&&T.name.length>0&&(F.name=T.name),F.args+=z,A({type:"response.function_call_arguments.delta",event_id:S("event"),item_id:P,response_id:m,output_index:F.outputIndex,call_id:P,name:F.name??"",delta:z});continue}if(T.type==="response.completed"){R=T.response??null;continue}}}catch(H){if(this.closed)return;if(H instanceof Ne){this.deadlineFired&&M();return}if(this.cancelled)return;if(H instanceof Bt)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${m} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(H,m);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&M();return}this.closeOpenItems(m,w,b),g(),this.send({type:"response.done",event_id:S("event"),response:this.doneResponse(m,b,R)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(w.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let t=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),t===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=yn){this.seamEmptyStreak=0,this.failMemberUnresponsive(t);return}let s=t;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${s} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${yn} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(G(Re("member_unresponsive",`the member served no content for ${yn} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)||t.hz===void 0&&t.cadence_ms===void 0?!1:"questions"in t||"question"in t}catch{return!1}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.binding.duplex){if(this.activeResponseId===null){if(wn(t)||this.userTurnOpen)return;this.openDuplexResponse()}else if(wn(t)){if(this.duplexSilenceMs+=Buffer.byteLength(t,"base64")/2/24,this.duplexSilenceMs>=li){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(wn(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(G({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:S("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:S("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let s=`${e}_msg_0`;this.turnOutputFlowed=!0,this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:S("event"),item_id:s,response_id:e,output_index:0,content_index:0,delta:t})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${S("req")}`}closeDuplexResponse(e){let t=this.activeResponseId;this.closeOpenItems(t,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let s=this.doneResponse(t,this.duplexInputCount,null);this.send({type:"response.done",event_id:S("event"),response:e==="cancelled"?{...s,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:s}),this.activeResponseId=null}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:S("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let s=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:s,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:S("event"),response_id:e,output_index:t,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:S("event"),item_id:s,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 s={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:S("event"),response_id:e,output_index:0,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:S("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,s){if(t.messageOpen||this.messageItemOpenForAudio){let r=`${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:S("event"),item_id:r,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:S("event"),item_id:r,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:S("event"),item_id:r,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:S("event"),item_id:r,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:S("event"),item_id:r,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:r,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:S("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[r,i]of t.tools){let o=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:S("event"),item_id:r,response_id:e,output_index:i.outputIndex,call_id:r,name:i.name??"",arguments:o});let a={id:r,type:"function_call",callId:r,name:i.name,arguments:o};this.pushItem(a),this.send({type:"response.output_item.done",event_id:S("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,s){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...s??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,s){let r=s&&typeof s.usage=="object"&&s.usage!==null?s.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:r?{input_tokens:typeof r.input_tokens=="number"&&Number.isFinite(r.input_tokens)?r.input_tokens:0,output_tokens:typeof r.output_tokens=="number"&&Number.isFinite(r.output_tokens)?r.output_tokens:0,total_tokens:typeof r.total_tokens=="number"&&Number.isFinite(r.total_tokens)?r.total_tokens:(typeof r.input_tokens=="number"&&Number.isFinite(r.input_tokens)?r.input_tokens:0)+(typeof r.output_tokens=="number"&&Number.isFinite(r.output_tokens)?r.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,s=xe(t);s===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 r=s??be(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:r}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Re(dn,"the organization is out of credits \u2014 top up to continue"),dn))}failSessionGone(e){if(e instanceof Q&&e.reason===ln){this.failInsufficientCredits();return}let t=e instanceof Error&&ve(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${me(e)}`);let s=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(Re("session_gone",s),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof si&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let s=Re(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(G(s)):this.send({type:"response.failed",event_id:S("event"),response:this.failedResponse(t,s)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let t=this.activeRequestId,s=this.binding.session;t!==null&&typeof s=="object"&&s!==null&&"cancelTurn"in s&&typeof s.cancelTurn=="function"&&s.cancelTurn(t),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(G(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!0,this.cutThroughTurnWaits(!1);let t=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:S("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>mn&&this.items.shift()}forwardImageFrames(e){for(let t of e.content??[]){if(t.type!=="input_image")continue;let s=t.imageUrl.indexOf(","),r=s>=0?Buffer.from(t.imageUrl.slice(s+1),"base64"):Buffer.alloc(0);if(r.byteLength===0){this.send(G(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(r.byteLength>un){this.send(G(X("frame_too_large",`input_image frame is ${r.byteLength} bytes \u2014 over the ${un}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(G(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(r))).catch(i=>this.send(G(Re(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let s=(e.content??[]).map(r=>r.type==="input_text"||r.type==="output_text"?{type:r.type,text:r.text}:r.type==="input_audio"?{type:"input_audio",...r.transcript?{transcript:r.transcript}:{}}:r.type==="input_image"?{type:"input_image",image_url:r.imageUrl,...r.detail?{detail:r.detail}:{}}:{type:"output_audio",transcript:r.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:s}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>pn){this.ws.close(ri,_n("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let s=ce(e);return s.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${me(e)}`),s.message}fail(e,t){this.send(G(e)),this.ws.close(ii,_n(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let t=this.turnLaneIterator;if(this.turnLaneIterator=null,t!==null){let s=t.return?.();s&&s.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(s=>ys(this.id,`binding release failed: ${s instanceof Error?s.message:String(s)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ys(this.id,e)}},vn=[];function ys(n,e){vn.push({id:n,reason:e}),vn.length>256&&vn.shift()}C();import{SessionFailedError as _s}from"@urun-sh/core";C();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as di}from"@urun-sh/core";var ci={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},pi={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 gt(n,e){let t=pi[n.code];return e?`${t} (${e})`:t}function jt(n){if(n==null)return null;let e=ci[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 Ht(n){if(n.kind==="create-failed")return jt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=di;return jt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocket as ws,WebSocketServer as mi}from"ws";var kn="/v1/realtime",vs="urun.admission",bs=n=>n.slice(0,120);function fi(n,e,t){let s=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${s}\r
7
7
  Connection: close\r
8
8
  Content-Type: text/plain\r
9
9
  \r
10
- ${vs(t)}\r
10
+ ${bs(t)}\r
11
11
  `),n.destroy()}function hi(n){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...n})}
12
- `}function gi(n){Pe(process.stdout,n)}function yi(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function vn(n){return n.audioSession?.audio.sessionId??void 0}function kn(n,e){let t=new mi({noServer:!0}),s=new Set;return n.on("upgrade",(r,i,o)=>{if(new URL(r.url??"/","http://localhost").pathname!==bn)return;s.add(i),i.on("close",()=>{s.delete(i)});let u=x("rtup"),l=yi(r),d=g=>{(e.log??gi)(hi(g))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,p=null,m=g=>{p??=g,c.abort(new Error(p))},f=()=>m("client socket closed"),b=()=>m("client socket closed (half-close)"),k=g=>m(`client socket error: ${g.message}`);i.once("close",f),i.once("end",b),i.once("error",k);let _=()=>{i.removeListener("close",f),i.removeListener("end",b),i.removeListener("error",k)},y=g=>{d({stage:"close",conn:u,model:l,...g})},h=null,v=!1,L=null,O=g=>JSON.stringify({type:ws,event_id:x("event"),...g}),I=g=>{if(h!==null){h.readyState===_s.OPEN&&h.send(O(g));return}v||(v=!0,t.handleUpgrade(r,i,o,w=>{h=w,L=[],w.on("message",R=>{L?.push(String(R))}),d({stage:"waiting",conn:u,model:l,status:g.status}),w.send(O(g))}))},S=g=>{let w=g,R=w.session!=null&&typeof w.session.sendResponseCreate=="function",M=w.clients!=null&&typeof w.clients.createResponse=="function";if(!R&&!M)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((q,j)=>{let $=(N,H)=>{try{let T=Date.now();new ht({ws:N,binding:g,operatorLog:e.operatorLog,...H.length>0?{replayFrames:H}:{},onClosed:(z,P)=>{y({while:"live",reason:P.reason});try{e.onSessionEnded?.({req:r,binding:g,connected_ms:Math.max(0,Date.now()-T),reason:P.reason})}catch(F){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${F instanceof Error?F.message:String(F)}
13
- `)}}}),d({stage:"admit",conn:u,model:l,...vn(g)===void 0?{}:{session:vn(g)}}),q()}catch(T){j(T)}};if(h!==null){let N=L??[];L=null,$(h,N);return}t.handleUpgrade(r,i,o,N=>$(N,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(r,c.signal,I).then(async g=>{if(c.signal.aborted){_();let w=vn(g);try{await g.release?.()}catch(R){y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",release_failed:R instanceof Error?R.message:String(R)});return}y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",released:!0}),i.destroy();return}_(),await S(g)}).catch(g=>{let w=g instanceof ys?jt(g):null,R=null;if(g!==null&&typeof g=="object"&&"status"in g){let $=g.status;typeof $=="number"&&(R=$)}let M=R??w?.status??502,q=g instanceof Error?g.message:String(g),j=R!==null?q:w!==null?gt(w,g instanceof ys&&g.status.sessionId?`session ${g.status.sessionId}`:void 0):ce(g).message;if(y({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:q,status:M}}),h!==null&&!c.signal.aborted){let $=JSON.stringify({type:ws,event_id:x("event"),status:M<500?"rejected":"failed",reason:j});h.readyState===_s.OPEN&&h.send($),h.close(1011,vs(j));return}i.destroyed||fi(i,M,j)}).finally(()=>{s.delete(i)})}),async()=>{let r=Date.now()+5e3;for(;s.size>0&&Date.now()<r;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>t.close(()=>i()))}}C();C();import{randomUUID as _a}from"crypto";C();import{createServer as Go}from"http";C();import{WebSocketServer as Oi,WebSocket as bt}from"ws";C();C();import{randomUUID as _i}from"crypto";var bs="Inference-Id";function yt(){return _i()}function Sn(n){return n==="/v1"||n.startsWith("/v1/")}function ks(n,e){if(!Sn(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 _t(n){return`resp_${n}`}function Ss(n){return`chatcmpl-${n}`}function xs(n){return`msg_${n}`}function fe(n){return e=>{n.sessionId=e.sessionId,n.catalog=e.identity}}function Rs(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_seconds: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 As(n){return`${JSON.stringify(n)}
14
- `}var wi=256,vi=128;function ue(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,vi)}var qe=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,s){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=s}modelEntry(e){let t=this.models[e];if(t)return t;let s=Object.keys(this.models).length>=wi?"(other)":e;return this.models[s]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t,s){let r=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(),r.ttftMs.push(o-i),r.ttftMs.length>512&&r.ttftMs.shift(),s!==void 0&&(s.ttftMs=o-s.startedAt)),a+=1,r.tokensOut+=1,r.charsOut+=l.delta.length,t!==void 0&&(r.modelEntry(t).tokens_out+=1)),yield l;let u=(performance.now()-(o??i))/1e3;a>0&&u>0&&(r.tokRates.push(a/u),r.tokRates.length>512&&r.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((s,r)=>s-r);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,s)=>t+s,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}}}},bi=256;function ki(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 Ue=class extends Error{},Ye=class{conversations=new Map;thread(e,t){let s=ki(t);if(e==null)return s;let r=this.conversations.get(String(e));if(!r)throw new Ue(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...r,...s]}remember(e,t,s,r=!0){this.conversations.set(e,[...t,...s]);for(let i of this.conversations.keys()){if(this.conversations.size<=bi)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},Is=new WeakMap;function wt(n){let e=Is.get(n);return e||(e=new Ye,Is.set(n,e)),e}function Qe(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function Ae(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 Ce=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),s=!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:s}}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}))}},Si=["<tool_call>","<function="];function xi(n){return Si.find(e=>n.includes(e))}function Be(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 je(n,e,t){if(!(!n||e>0))return xi(t)}function et(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(s=>s.type==="response.output_text.delta"&&typeof s.delta=="string").map(s=>s.delta).join("")}function Ie(n){let e=n?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ri(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let s of e){if(s===null||typeof s!="object")continue;let r=s;r.type==="message"?t.push({role:"assistant",content:r.content??""}):r.type==="function_call"&&t.push({type:"function_call",call_id:r.call_id,name:r.name,arguments:r.arguments})}return t}function xn(n,e){let t=Ri(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var he=class extends Error{constructor(t,s,r=400,i){super(t);this.code=s;this.status=r;this.param=i}code;status;param};function tt(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof Ue?new he(t.message,"previous_response_not_found",400,"previous_response_id"):new he(String(t instanceof Error?t.message:t),"invalid_input")}}function Es(n){let e=n.text;if(e!==null&&typeof e=="object"){let t=e.format;if(t!==void 0)return t}}async function Rn(n,e,t,s,r){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new he("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:s,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}:{},...Es(e)!==void 0?{response_format:Es(e)}:{}},r)}async function vt(n){let{body:e,clients:t,store:s,stats:r}=n,i=tt(s,e);e.previous_response_id!=null&&(r.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=ue(e);r.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=n.turn,p=await Rn(t,e,i,!0,c?fe(c):void 0);return{responseId:o,events:Ti({events:p,conversation:i,responseId:o,modelKey:l,requestHadTools:d,remember:a,persist:u,store:s,stats:r,turn:n.turn})}}function Ai(n,e){let t=[...n].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),s=Array.isArray(e?.output)?e.output:[],r=s.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=t.filter(u=>u.type==="message").length===r.length,o=0;return[...t.map(u=>u.type==="message"&&i?Ei(r[o++],u):u),...Ii(s,t)]}function Ii(n,e){let t=e.some(l=>l.type==="message"),s=e.some(l=>l.type==="reasoning"),r=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(r));return n.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!t:d.type==="reasoning"?!s:d.type==="function_call"?!a&&!u.has(r(d)):!0})}function Ei(n,e){let t=a=>a!==null&&typeof a=="object"&&a.type==="output_text",s=Array.isArray(n.content)?n.content:[];if(s.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=s.map(a=>t(a)?{...a,text:i.text}:a),o}async function*Ti(n){let{events:e,conversation:t,responseId:s,modelKey:r,requestHadTools:i,remember:o,persist:a,store:u,stats:l}=n,d=[],c=P=>P.response&&typeof P.response=="object"?{...P,response:{...P.response,id:s}}:P,p=`item_${s.slice(5)}`,m=!1,f=!1,b=0;function*k(){m||(m=!0,yield{type:"response.created",response:{id:s,object:"response",status:"in_progress"}})}let _=[],y=(P,F)=>{_.push({output_index:P,item:F})},h=!1,v=0,L="",O=0,I="";function*S(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:L,output_index:v,content_index:0,text:I};let P={id:L,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:I}],status:"completed"};yield{type:"response.output_item.done",output_index:v,item:P},y(v,P),I=""}let A=!1,g=0,w="",R=0,M="",q="";function*j(P){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:w,output_index:g,content_index:0,text:M},yield{type:"response.content_part.done",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:M}};let F={id:w,type:"message",role:"assistant",status:P,content:[{type:"output_text",text:M}]};yield{type:"response.output_item.done",output_index:g,item:F},y(g,F),M=""}let $=new Ce,N=null,H=-1;function*T(P){if(!N)return;let F=N;N=null,yield{type:"response.function_call_arguments.done",item_id:F.fcId,output_index:F.outputIndex,arguments:F.args};let W={id:F.fcId,type:"function_call",call_id:F.callId??F.fcId,name:F.name??"",arguments:F.args,status:P};yield{type:"response.output_item.done",output_index:F.outputIndex,item:W},y(F.outputIndex,W)}let z=!1;for await(let P of l.track(e,r,n.turn)){d.push(P);let F=String(P.type??"");if(F==="response.created"||F==="response.in_progress"){m=!0,yield c(P);continue}if(F==="response.output_item.added"){f=!0,yield c(P);continue}if(F==="response.reasoning_text.delta"&&!f){yield*k(),h||(h=!0,v=b++,O+=1,L=O===1?`rs_${s.slice(5)}`:`rs_${s.slice(5)}_${O}`,yield{type:"response.output_item.added",output_index:v,item:{id:L,type:"reasoning",summary:[],content:[],status:"in_progress"}}),I+=String(P.delta??""),yield{type:"response.reasoning_text.delta",item_id:L,output_index:v,content_index:0,delta:P.delta};continue}if(F==="response.output_text.delta"&&!f){yield*k(),yield*S(),A||(A=!0,g=b++,R+=1,w=R===1?p:`${p}_${R}`,yield{type:"response.output_item.added",output_index:g,item:{id:w,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:""}}),M+=String(P.delta??""),q+=String(P.delta??""),yield{type:F,item_id:w,output_index:g,content_index:0,delta:P.delta};continue}let W=f?null:Ze(P);if(W){if(yield*k(),yield*S(),yield*j("completed"),$.add(W),W.tool_index!==H){yield*T("completed"),H=W.tool_index;let Se=b++;N={fcId:`fc_${s.slice(5)}_${W.tool_index}`,outputIndex:Se,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:Se,item:{id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:"",status:"in_progress"}}}N&&(W.call_id&&(N.callId=W.call_id),W.name&&(N.name=W.name),N.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:N.fcId,output_index:N.outputIndex,delta:W.delta});continue}if(F==="response.completed"&&!f){let Se=Qe(P.response),Ve=je(i,$.size+Se.length,q);if(Ve){z=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Be(r,Ve)}};break}if(yield*S(),yield*j("completed"),yield*T("completed"),$.size===0)for(let te of Se){let ge=b++,$e=te.id??te.call_id??`fc_${ge}`,rn=te.arguments??"",Jn={id:$e,type:"function_call",call_id:te.call_id??$e,name:te.name??""};yield{type:"response.output_item.added",output_index:ge,item:{...Jn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:$e,output_index:ge,delta:rn},yield{type:"response.function_call_arguments.done",item_id:$e,output_index:ge,arguments:rn};let Wn={...Jn,arguments:rn,status:"completed"};yield{type:"response.output_item.done",output_index:ge,item:Wn},y(ge,Wn)}let K=Ai(_,P.response);yield K.length>0?c({...P,response:{...P.response,output:K}}):c(P);continue}yield c(P)}if(yield*S(),yield*j("incomplete"),yield*T("incomplete"),o&&!z){let P=Ae(d);u.remember(s,t,xn(P,et(d,P)),a)}}var Pi="/v1/responses",Mi=64*1024*1024,Ci=8*1024*1024,Li=16,Ts=32,Os=3600*1e3,$i=/^[A-Za-z0-9._-]{1,256}$/;function le(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Fi=le(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 En(){let n,e;return{promise:new Promise((s,r)=>{n=s,e=r}),resolve:n,reject:e}}async function Di(n){for(;n.bufferedAmount>Ci&&n.readyState===bt.OPEN;){let{promise:e,resolve:t}=En();setTimeout(t,5),await e}}var An=class extends Ye{constructor(t){super();this.shared=t}shared;thread(t,s){if(t==null)return super.thread(t,s);try{return super.thread(t,s)}catch(r){if(!(r instanceof Ue))throw r;return this.shared.thread(t,s)}}remember(t,s,r,i=!0){i?this.shared.remember(t,s,r):super.remember(t,s,r)}forget(t){super.forget(t),this.shared.forget(t)}},In=class{constructor(e,t,s,r,i){this.ws=e;this.clients=t;this.stats=s;this.statusOf=r;this.operatorLog=i;this.store=new An(wt(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(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Os/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Os).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(le(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 s;try{s=JSON.parse(e.toString())}catch{this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(s===null||typeof s!="object"||Array.isArray(s)){this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let r=s;if(r.type!=="response.create"){this.sendFrame(le(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(r.type??null)}; only "response.create" is supported`}));return}if("stream"in r){this.sendFrame(le(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 r){this.sendFrame(le(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(r.stream_id!==void 0){if(typeof r.stream_id!="string"||!$i.test(r.stream_id)){this.sendFrame(Fi);return}if(i=r.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Ts){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Ts}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let o=r.generate===!1?()=>this.runWarmup(r,i):()=>this.runTurn(r,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 s=yt();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let i;try{i=await vt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:_t(s)})}catch(a){this.failTurn(a,t,e,s);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!==bt.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,t,s));break}this.send(a,t),await Di(this.ws)}}finally{this.activeTurns.delete(o)}}catch(r){this.failTurn(r,t,e,s)}finally{this.release()}}runWarmup(e,t){if(this.closed)return;let s=yt(),r=_t(s);try{let i=tt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,i,[],e.store!==!1),this.laneOfResponse.set(r,t??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},t)}catch(i){this.failTurn(i,t,e,s)}}failTurn(e,t,s,r){this.sendFrame(this.errorFrameOf(e,t,r));let i=s.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(t??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,t,s){let r=e instanceof Error?e.message:me(e);if(e instanceof he)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof J)return le(404,{type:"invalid_request_error",code:"model_not_found",message:r},t);if(e instanceof Q){let a=ce(e,{inferenceId:s});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${s??"none"}); raw error withheld from the caller: ${r}`),le(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 ${s??"none"}); detail withheld from the caller: ${i.operatorDetail}`),le(i.status,{type:i.openaiType,message:r},t);let o=ce(e,{inferenceId:s});return o.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${s??"none"}); raw error withheld from the caller: ${r}`),le(500,{type:"upstream_error",message:o.message},t)}upstreamErrorFrameOf(e,t,s){let r=e.error,i=r?.type??"upstream_error",o=xe(r),a=o??be(s);return o===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${s}); full event withheld from the caller: ${JSON.stringify(e)}`),le(i==="invalid_request_error"?400:502,{type:i,...r&&typeof r.code=="string"?{code:r.code}:{},message:a},t)}async acquire(){for(;this.active>=Li;){let{promise:e,resolve:t}=En();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!==bt.OPEN)return;let s=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(s))}sendFrame(e){this.closed||this.ws.readyState!==bt.OPEN||this.ws.send(JSON.stringify(e))}};function Ht(n,e,t){let s=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",r=`${t}\r
12
+ `}function gi(n){Pe(process.stdout,n)}function yi(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function bn(n){return n.audioSession?.audio.sessionId??void 0}function Sn(n,e){let t=new mi({noServer:!0}),s=new Set;return n.on("upgrade",(r,i,o)=>{if(new URL(r.url??"/","http://localhost").pathname!==kn)return;s.add(i),i.on("close",()=>{s.delete(i)});let u=S("rtup"),l=yi(r),d=g=>{(e.log??gi)(hi(g))};d({stage:"accept",conn:u,model:l}),i.resume();let c=new AbortController,p=null,m=g=>{p??=g,c.abort(new Error(p))},f=()=>m("client socket closed"),b=()=>m("client socket closed (half-close)"),k=g=>m(`client socket error: ${g.message}`);i.once("close",f),i.once("end",b),i.once("error",k);let _=()=>{i.removeListener("close",f),i.removeListener("end",b),i.removeListener("error",k)},y=g=>{d({stage:"close",conn:u,model:l,...g})},h=null,v=!1,L=null,O=g=>JSON.stringify({type:vs,event_id:S("event"),...g}),I=g=>{if(h!==null){h.readyState===ws.OPEN&&h.send(O(g));return}v||(v=!0,t.handleUpgrade(r,i,o,w=>{h=w,L=[],w.on("message",R=>{L?.push(String(R))}),d({stage:"waiting",conn:u,model:l,status:g.status}),w.send(O(g))}))},x=g=>{let w=g,R=w.session!=null&&typeof w.session.sendResponseCreate=="function",M=w.clients!=null&&typeof w.clients.createResponse=="function";if(!R&&!M)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((q,j)=>{let $=(N,H)=>{try{let T=Date.now();new ht({ws:N,binding:g,operatorLog:e.operatorLog,...H.length>0?{replayFrames:H}:{},onClosed:(z,P)=>{y({while:"live",reason:P.reason});try{e.onSessionEnded?.({req:r,binding:g,connected_ms:Math.max(0,Date.now()-T),reason:P.reason})}catch(F){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${F instanceof Error?F.message:String(F)}
13
+ `)}}}),d({stage:"admit",conn:u,model:l,...bn(g)===void 0?{}:{session:bn(g)}}),q()}catch(T){j(T)}};if(h!==null){let N=L??[];L=null,$(h,N);return}t.handleUpgrade(r,i,o,N=>$(N,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(r,c.signal,I).then(async g=>{if(c.signal.aborted){_();let w=bn(g);try{await g.release?.()}catch(R){y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",release_failed:R instanceof Error?R.message:String(R)});return}y({while:"queued",...w===void 0?{}:{session:w},reason:p??"client socket closed",released:!0}),i.destroy();return}_(),await x(g)}).catch(g=>{let w=g instanceof _s?Ht(g):null,R=null;if(g!==null&&typeof g=="object"&&"status"in g){let $=g.status;typeof $=="number"&&(R=$)}let M=R??w?.status??502,q=g instanceof Error?g.message:String(g),j=R!==null?q:w!==null?gt(w,g instanceof _s&&g.status.sessionId?`session ${g.status.sessionId}`:void 0):ce(g).message;if(y({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:q,status:M}}),h!==null&&!c.signal.aborted){let $=JSON.stringify({type:vs,event_id:S("event"),status:M<500?"rejected":"failed",reason:j});h.readyState===ws.OPEN&&h.send($),h.close(1011,bs(j));return}i.destroyed||fi(i,M,j)}).finally(()=>{s.delete(i)})}),async()=>{let r=Date.now()+5e3;for(;s.size>0&&Date.now()<r;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>t.close(()=>i()))}}C();C();import{randomUUID as ga}from"crypto";C();import{createServer as jo}from"http";C();import{WebSocketServer as Oi,WebSocket as bt}from"ws";C();C();import{randomUUID as _i}from"crypto";var ks="Inference-Id";function yt(){return _i()}function xn(n){return n==="/v1"||n.startsWith("/v1/")}function Ss(n,e){if(!xn(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 _t(n){return`resp_${n}`}function xs(n){return`chatcmpl-${n}`}function Rs(n){return`msg_${n}`}function fe(n){return e=>{n.sessionId=e.sessionId,n.catalog=e.identity}}function As(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_seconds: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 Is(n){return`${JSON.stringify(n)}
14
+ `}var wi=256,vi=128;function ue(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,vi)}var qe=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,s){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=s}modelEntry(e){let t=this.models[e];if(t)return t;let s=Object.keys(this.models).length>=wi?"(other)":e;return this.models[s]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t,s){let r=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(),r.ttftMs.push(o-i),r.ttftMs.length>512&&r.ttftMs.shift(),s!==void 0&&(s.ttftMs=o-s.startedAt)),a+=1,r.tokensOut+=1,r.charsOut+=l.delta.length,t!==void 0&&(r.modelEntry(t).tokens_out+=1)),yield l;let u=(performance.now()-(o??i))/1e3;a>0&&u>0&&(r.tokRates.push(a/u),r.tokRates.length>512&&r.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((s,r)=>s-r);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,s)=>t+s,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}}}},bi=256;function ki(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 Ue=class extends Error{},Ye=class{conversations=new Map;thread(e,t){let s=ki(t);if(e==null)return s;let r=this.conversations.get(String(e));if(!r)throw new Ue(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...r,...s]}remember(e,t,s,r=!0){this.conversations.set(e,[...t,...s]);for(let i of this.conversations.keys()){if(this.conversations.size<=bi)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},Es=new WeakMap;function wt(n){let e=Es.get(n);return e||(e=new Ye,Es.set(n,e)),e}function Qe(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function Ae(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 Ce=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),s=!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:s}}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}))}},Si=["<tool_call>","<function="];function xi(n){return Si.find(e=>n.includes(e))}function Be(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 je(n,e,t){if(!(!n||e>0))return xi(t)}function et(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(s=>s.type==="response.output_text.delta"&&typeof s.delta=="string").map(s=>s.delta).join("")}function Ie(n){let e=n?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ri(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let s of e){if(s===null||typeof s!="object")continue;let r=s;r.type==="message"?t.push({role:"assistant",content:r.content??""}):r.type==="function_call"&&t.push({type:"function_call",call_id:r.call_id,name:r.name,arguments:r.arguments})}return t}function Rn(n,e){let t=Ri(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var he=class extends Error{constructor(t,s,r=400,i){super(t);this.code=s;this.status=r;this.param=i}code;status;param};function tt(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof Ue?new he(t.message,"previous_response_not_found",400,"previous_response_id"):new he(String(t instanceof Error?t.message:t),"invalid_input")}}function Ts(n){let e=n.text;if(e!==null&&typeof e=="object"){let t=e.format;if(t!==void 0)return t}}async function An(n,e,t,s,r){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new he("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:s,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}:{},...Ts(e)!==void 0?{response_format:Ts(e)}:{}},r)}async function vt(n){let{body:e,clients:t,store:s,stats:r}=n,i=tt(s,e);e.previous_response_id!=null&&(r.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=ue(e);r.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=n.turn,p=await An(t,e,i,!0,c?fe(c):void 0);return{responseId:o,events:Ti({events:p,conversation:i,responseId:o,modelKey:l,requestHadTools:d,remember:a,persist:u,store:s,stats:r,turn:n.turn})}}function Ai(n,e){let t=[...n].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),s=Array.isArray(e?.output)?e.output:[],r=s.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=t.filter(u=>u.type==="message").length===r.length,o=0;return[...t.map(u=>u.type==="message"&&i?Ei(r[o++],u):u),...Ii(s,t)]}function Ii(n,e){let t=e.some(l=>l.type==="message"),s=e.some(l=>l.type==="reasoning"),r=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(r));return n.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!t:d.type==="reasoning"?!s:d.type==="function_call"?!a&&!u.has(r(d)):!0})}function Ei(n,e){let t=a=>a!==null&&typeof a=="object"&&a.type==="output_text",s=Array.isArray(n.content)?n.content:[];if(s.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=s.map(a=>t(a)?{...a,text:i.text}:a),o}async function*Ti(n){let{events:e,conversation:t,responseId:s,modelKey:r,requestHadTools:i,remember:o,persist:a,store:u,stats:l}=n,d=[],c=P=>P.response&&typeof P.response=="object"?{...P,response:{...P.response,id:s}}:P,p=`item_${s.slice(5)}`,m=!1,f=!1,b=0;function*k(){m||(m=!0,yield{type:"response.created",response:{id:s,object:"response",status:"in_progress"}})}let _=[],y=(P,F)=>{_.push({output_index:P,item:F})},h=!1,v=0,L="",O=0,I="";function*x(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:L,output_index:v,content_index:0,text:I};let P={id:L,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:I}],status:"completed"};yield{type:"response.output_item.done",output_index:v,item:P},y(v,P),I=""}let A=!1,g=0,w="",R=0,M="",q="";function*j(P){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:w,output_index:g,content_index:0,text:M},yield{type:"response.content_part.done",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:M}};let F={id:w,type:"message",role:"assistant",status:P,content:[{type:"output_text",text:M}]};yield{type:"response.output_item.done",output_index:g,item:F},y(g,F),M=""}let $=new Ce,N=null,H=-1;function*T(P){if(!N)return;let F=N;N=null,yield{type:"response.function_call_arguments.done",item_id:F.fcId,output_index:F.outputIndex,arguments:F.args};let W={id:F.fcId,type:"function_call",call_id:F.callId??F.fcId,name:F.name??"",arguments:F.args,status:P};yield{type:"response.output_item.done",output_index:F.outputIndex,item:W},y(F.outputIndex,W)}let z=!1;for await(let P of l.track(e,r,n.turn)){d.push(P);let F=String(P.type??"");if(F==="response.created"||F==="response.in_progress"){m=!0,yield c(P);continue}if(F==="response.output_item.added"){f=!0,yield c(P);continue}if(F==="response.reasoning_text.delta"&&!f){yield*k(),h||(h=!0,v=b++,O+=1,L=O===1?`rs_${s.slice(5)}`:`rs_${s.slice(5)}_${O}`,yield{type:"response.output_item.added",output_index:v,item:{id:L,type:"reasoning",summary:[],content:[],status:"in_progress"}}),I+=String(P.delta??""),yield{type:"response.reasoning_text.delta",item_id:L,output_index:v,content_index:0,delta:P.delta};continue}if(F==="response.output_text.delta"&&!f){yield*k(),yield*x(),A||(A=!0,g=b++,R+=1,w=R===1?p:`${p}_${R}`,yield{type:"response.output_item.added",output_index:g,item:{id:w,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:w,output_index:g,content_index:0,part:{type:"output_text",text:""}}),M+=String(P.delta??""),q+=String(P.delta??""),yield{type:F,item_id:w,output_index:g,content_index:0,delta:P.delta};continue}let W=f?null:Ze(P);if(W){if(yield*k(),yield*x(),yield*j("completed"),$.add(W),W.tool_index!==H){yield*T("completed"),H=W.tool_index;let Se=b++;N={fcId:`fc_${s.slice(5)}_${W.tool_index}`,outputIndex:Se,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:Se,item:{id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:"",status:"in_progress"}}}N&&(W.call_id&&(N.callId=W.call_id),W.name&&(N.name=W.name),N.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:N.fcId,output_index:N.outputIndex,delta:W.delta});continue}if(F==="response.completed"&&!f){let Se=Qe(P.response),Ve=je(i,$.size+Se.length,q);if(Ve){z=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Be(r,Ve)}};break}if(yield*x(),yield*j("completed"),yield*T("completed"),$.size===0)for(let te of Se){let ge=b++,$e=te.id??te.call_id??`fc_${ge}`,on=te.arguments??"",Wn={id:$e,type:"function_call",call_id:te.call_id??$e,name:te.name??""};yield{type:"response.output_item.added",output_index:ge,item:{...Wn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:$e,output_index:ge,delta:on},yield{type:"response.function_call_arguments.done",item_id:$e,output_index:ge,arguments:on};let Vn={...Wn,arguments:on,status:"completed"};yield{type:"response.output_item.done",output_index:ge,item:Vn},y(ge,Vn)}let K=Ai(_,P.response);yield K.length>0?c({...P,response:{...P.response,output:K}}):c(P);continue}yield c(P)}if(yield*x(),yield*j("incomplete"),yield*T("incomplete"),o&&!z){let P=Ae(d);u.remember(s,t,Rn(P,et(d,P)),a)}}var Pi="/v1/responses",Mi=64*1024*1024,Ci=8*1024*1024,Li=16,Os=32,Ps=3600*1e3,$i=/^[A-Za-z0-9._-]{1,256}$/;function le(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Fi=le(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 Tn(){let n,e;return{promise:new Promise((s,r)=>{n=s,e=r}),resolve:n,reject:e}}async function Di(n){for(;n.bufferedAmount>Ci&&n.readyState===bt.OPEN;){let{promise:e,resolve:t}=Tn();setTimeout(t,5),await e}}var In=class extends Ye{constructor(t){super();this.shared=t}shared;thread(t,s){if(t==null)return super.thread(t,s);try{return super.thread(t,s)}catch(r){if(!(r instanceof Ue))throw r;return this.shared.thread(t,s)}}remember(t,s,r,i=!0){i?this.shared.remember(t,s,r):super.remember(t,s,r)}forget(t){super.forget(t),this.shared.forget(t)}},En=class{constructor(e,t,s,r,i){this.ws=e;this.clients=t;this.stats=s;this.statusOf=r;this.operatorLog=i;this.store=new In(wt(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(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ps/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ps).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(le(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 s;try{s=JSON.parse(e.toString())}catch{this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(s===null||typeof s!="object"||Array.isArray(s)){this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let r=s;if(r.type!=="response.create"){this.sendFrame(le(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(r.type??null)}; only "response.create" is supported`}));return}if("stream"in r){this.sendFrame(le(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 r){this.sendFrame(le(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(r.stream_id!==void 0){if(typeof r.stream_id!="string"||!$i.test(r.stream_id)){this.sendFrame(Fi);return}if(i=r.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Os){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Os}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let o=r.generate===!1?()=>this.runWarmup(r,i):()=>this.runTurn(r,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 s=yt();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let i;try{i=await vt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:_t(s)})}catch(a){this.failTurn(a,t,e,s);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!==bt.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,t,s));break}this.send(a,t),await Di(this.ws)}}finally{this.activeTurns.delete(o)}}catch(r){this.failTurn(r,t,e,s)}finally{this.release()}}runWarmup(e,t){if(this.closed)return;let s=yt(),r=_t(s);try{let i=tt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,i,[],e.store!==!1),this.laneOfResponse.set(r,t??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},t)}catch(i){this.failTurn(i,t,e,s)}}failTurn(e,t,s,r){this.sendFrame(this.errorFrameOf(e,t,r));let i=s.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(t??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,t,s){let r=e instanceof Error?e.message:me(e);if(e instanceof he)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof J)return le(404,{type:"invalid_request_error",code:"model_not_found",message:r},t);if(e instanceof Q){let a=ce(e,{inferenceId:s});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${s??"none"}); raw error withheld from the caller: ${r}`),le(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 ${s??"none"}); detail withheld from the caller: ${i.operatorDetail}`),le(i.status,{type:i.openaiType,message:r},t);let o=ce(e,{inferenceId:s});return o.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${s??"none"}); raw error withheld from the caller: ${r}`),le(500,{type:"upstream_error",message:o.message},t)}upstreamErrorFrameOf(e,t,s){let r=e.error,i=r?.type??"upstream_error",o=xe(r),a=o??be(s);return o===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${s}); full event withheld from the caller: ${JSON.stringify(e)}`),le(i==="invalid_request_error"?400:502,{type:i,...r&&typeof r.code=="string"?{code:r.code}:{},message:a},t)}async acquire(){for(;this.active>=Li;){let{promise:e,resolve:t}=Tn();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!==bt.OPEN)return;let s=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(s))}sendFrame(e){this.closed||this.ws.readyState!==bt.OPEN||this.ws.send(JSON.stringify(e))}};function Gt(n,e,t){let s=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",r=`${t}\r
15
15
  `;n.end(`HTTP/1.1 ${e} ${s}\r
16
16
  Connection: close\r
17
17
  Content-Type: text/plain; charset=utf-8\r
18
18
  Content-Length: ${Buffer.byteLength(r)}\r
19
19
  \r
20
- ${r}`)}function Ps(n,e){let t=new Oi({noServer:!0,maxPayload:Mi}),s=new qe,r=new Set,i=new Set,o=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{Ht(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>o.delete(c)),m.pathname!==Pi){o.add(c);return}i.add(c);let f=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ht(c,401,"invalid local proxy api key");return}let b;try{b=await a(d)}catch(k){let _=e.statusOf?.(k)??null;Ht(c,_?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(f=!0,t.handleUpgrade(d,c,p,k=>{i.delete(c),r.add(k),k.on("close",()=>r.delete(k));try{new In(k,b,s,e.statusOf,e.operatorLog??(_=>console.error(_)))}catch{r.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!f&&!c.destroyed&&Ht(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return n.on("upgrade",l),{stats:s,close:()=>{let{promise:d,resolve:c}=En();if(u)return c(),d;u=!0,n.off("upgrade",l);for(let m of i)m.destroy();i.clear();for(let m of o)m.destroy();o.clear();for(let m of r)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of r)m.readyState!==bt.CLOSED&&m.terminate()},2e3);return p.unref?.(),t.close(()=>{clearTimeout(p),c()}),d}}}C();var D=class extends Error{},ae=class extends Error{};function ne(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function kt(n){return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:null}function st(n,e){if(n!=null)throw new D(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Tn(n){let e=kt(n);return e!==null&&e<=1?e:null}function Ms(n,e){if(!ne(n))throw new D("decisions requires a JSON object body");st(n.prompt_cache_key,"prompt_cache_key"),st(n.prompt_cache_options,"prompt_cache_options"),st(n.safety_identifier,"safety_identifier");let t=[],s=Ni(n.input,t),r=n.questions;if(!Array.isArray(r)||r.length<1||r.length>400)throw new D("decisions requires a questions array of 1 to 400 questions");let i={},o=[],a=new Set;for(let l=0;l<r.length;l++){let{entry:d,spec:c}=ji(r[l],l,r.length,t);if(a.has(c.key))throw new D(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),i[c.key]=d,o.push(c)}let u={model:e,state:s,questions:i};return t.length>0&&(u.media=t),{systemone:u,specs:o}}function Ni(n,e){if(typeof n=="string")return n;if(!ne(n)&&!Array.isArray(n))throw new D("decisions input must be a string or an array of messages");let t=Array.isArray(n)?n:[n],s=[];for(let r of t)Ui(r,s,e);return qi(s)}function qi(n){return n.length===0?"":n.some(e=>e.role!==void 0)?n:n.flatMap(e=>"text"in e?[e.text]:[]).join(`
20
+ ${r}`)}function Ms(n,e){let t=new Oi({noServer:!0,maxPayload:Mi}),s=new qe,r=new Set,i=new Set,o=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{Gt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>o.delete(c)),m.pathname!==Pi){o.add(c);return}i.add(c);let f=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Gt(c,401,"invalid local proxy api key");return}let b;try{b=await a(d)}catch(k){let _=e.statusOf?.(k)??null;Gt(c,_?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(f=!0,t.handleUpgrade(d,c,p,k=>{i.delete(c),r.add(k),k.on("close",()=>r.delete(k));try{new En(k,b,s,e.statusOf,e.operatorLog??(_=>console.error(_)))}catch{r.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!f&&!c.destroyed&&Gt(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return n.on("upgrade",l),{stats:s,close:()=>{let{promise:d,resolve:c}=Tn();if(u)return c(),d;u=!0,n.off("upgrade",l);for(let m of i)m.destroy();i.clear();for(let m of o)m.destroy();o.clear();for(let m of r)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of r)m.readyState!==bt.CLOSED&&m.terminate()},2e3);return p.unref?.(),t.close(()=>{clearTimeout(p),c()}),d}}}C();var D=class extends Error{},ae=class extends Error{};function ne(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function kt(n){return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:null}function st(n,e){if(n!=null)throw new D(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function On(n){let e=kt(n);return e!==null&&e<=1?e:null}function Cs(n,e){if(!ne(n))throw new D("decisions requires a JSON object body");st(n.prompt_cache_key,"prompt_cache_key"),st(n.prompt_cache_options,"prompt_cache_options"),st(n.safety_identifier,"safety_identifier");let t=[],s=Ni(n.input,t),r=n.questions;if(!Array.isArray(r)||r.length<1||r.length>400)throw new D("decisions requires a questions array of 1 to 400 questions");let i={},o=[],a=new Set;for(let l=0;l<r.length;l++){let{entry:d,spec:c}=ji(r[l],l,r.length,t);if(a.has(c.key))throw new D(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),i[c.key]=d,o.push(c)}let u={model:e,state:s,questions:i};return t.length>0&&(u.media=t),{systemone:u,specs:o}}function Ni(n,e){if(typeof n=="string")return n;if(!ne(n)&&!Array.isArray(n))throw new D("decisions input must be a string or an array of messages");let t=Array.isArray(n)?n:[n],s=[];for(let r of t)Ui(r,s,e);return qi(s)}function qi(n){return n.length===0?"":n.some(e=>e.role!==void 0)?n:n.flatMap(e=>"text"in e?[e.text]:[]).join(`
21
21
 
22
- `)}function Ui(n,e,t){if(!ne(n))throw new D("decisions input items must be JSON objects");let s=n.role,r=n.type;if(s==="user"||s==="developer"||s==="system"||s==="assistant"){Bi(n,s,e,t);return}switch(r){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:r,name:n.name,call_id:n.call_id,arguments:n.arguments,input:n.input})});return}case"function_call_output":case"custom_tool_call_output":{let i=n.output;if(typeof i=="string"){e.push({text:i});return}if(Array.isArray(i)){Cs(i,e,t,void 0,!1);return}throw new D(`${r} output must be a string or an array of parts`)}default:throw new D(`unsupported decisions input item (role ${JSON.stringify(s??null)}, type ${JSON.stringify(r??null)})`)}}function Bi(n,e,t,s){e==="assistant"&&st(n.phase,"assistant message phase");let r=n.content;if(typeof r=="string"){t.push({role:e,text:r});return}if(!Array.isArray(r))throw new D(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of r){if(!ne(i))throw new D("decisions assistant message parts must be JSON objects");if(i.type==="output_text"&&typeof i.text=="string")t.push({role:e,text:i.text});else if(i.type==="refusal"&&typeof i.refusal=="string")t.push({role:e,text:`[refusal] ${i.refusal}`});else throw new D(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}Cs(r,t,s,e)}function Cs(n,e,t,s,r=!0){for(let i of n){if(!ne(i))throw new D("decisions content parts must be JSON objects");switch(st(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new D("input_text requires a string text");e.push({role:s,text:i.text});break}case"input_json":{if(!r)throw new D("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let o=i.data;if(!ne(o)&&!(Array.isArray(o)&&o.every(ne)))throw new D("input_json data must be an object or an array of objects");e.push({role:s,json:o});break}case"input_image":{t.push(Ls(i));break}default:throw new D(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function Ls(n){let e=n.image_url;if(typeof e!="string"||e==="")throw new D("input_image requires a string image_url");let t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(t===null)throw new D("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,s,r]=t;if(r==="")throw new D("input_image data URL carries no image data");let i=r.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(r)||(i?r.length%4!==0:r.length%4===1))throw new D("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let o=n.detail;if(o!=null&&o!=="low"&&o!=="high"&&o!=="auto"&&o!=="original")throw new D("input_image detail must be low, high, auto, or original");let a={type:"image",mime:s,data:r};return(o==="low"||o==="high")&&(a.detail=o),a}function ji(n,e,t,s){if(!ne(n))throw new D(`questions[${e}] must be a JSON object`);let r=n.type;if(r!=="predicate"&&r!=="choice"&&r!=="score")throw new D(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(r??null)})`);let i=n.name;if(i!==void 0&&typeof i!="string")throw new D(`questions[${e}] name must be a string`);let o=i??null,a=o??`q${e}`,u=Hi(n.instructions,e,t,s);switch(r){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:r,key:a,name:o}};case"choice":{let l=n.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new D(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let b of l){if(!ne(b))throw new D(`questions[${e}] choices must be JSON objects`);let k=b.value;if(typeof k!="string"&&typeof k!="boolean")throw new D(`questions[${e}] choice value must be a string or boolean`);let _=String(k);if(c.has(_))throw new D(`questions[${e}] has duplicate choice value ${JSON.stringify(_)} (choices must be unique)`);c.add(_);let y=b.description;if(y!==void 0&&typeof y!="string")throw new D(`questions[${e}] choice description must be a string`);d.push(k),p.push(y)}let m=l.map((b,k)=>({name:String(d[k]),description:p[k]??String(d[k])}));return{entry:{kind:"choice",prompt:u,options:m},spec:{type:r,key:a,name:o,choiceValues:d}}}case"score":{let l=n.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new D(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!ne(m)||typeof m.label!="string")throw new D(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new D(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let f=m.description;if(f!==void 0&&typeof f!="string")throw new D(`questions[${e}] score level description must be a string`);let b=f!==void 0?`${m.label}: ${f}`:m.label;if(c.includes(b))throw new D(`questions[${e}] has duplicate score criterion ${JSON.stringify(b)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(b)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:r,key:a,name:o,levelLabels:d}}}}}function Hi(n,e,t,s){if(typeof n=="string")return n;if(!Array.isArray(n))throw new D(`questions[${e}] instructions must be a string or an array of input parts`);let r=[];for(let i of n){if(!ne(i))throw new D(`questions[${e}] instruction parts must be JSON objects`);switch(st(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new D(`questions[${e}] input_text requires a string text`);r.push(i.text);break}case"input_image":{if(t>1)throw new D(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);s.push(Ls(i));break}case"input_json":{let o=i.data;if(!ne(o)&&!(Array.isArray(o)&&o.every(ne)))throw new D(`questions[${e}] input_json data must be an object or an array of objects`);r.push(JSON.stringify(o));break}default:throw new D(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return r.join(`
22
+ `)}function Ui(n,e,t){if(!ne(n))throw new D("decisions input items must be JSON objects");let s=n.role,r=n.type;if(s==="user"||s==="developer"||s==="system"||s==="assistant"){Bi(n,s,e,t);return}switch(r){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:r,name:n.name,call_id:n.call_id,arguments:n.arguments,input:n.input})});return}case"function_call_output":case"custom_tool_call_output":{let i=n.output;if(typeof i=="string"){e.push({text:i});return}if(Array.isArray(i)){Ls(i,e,t,void 0,!1);return}throw new D(`${r} output must be a string or an array of parts`)}default:throw new D(`unsupported decisions input item (role ${JSON.stringify(s??null)}, type ${JSON.stringify(r??null)})`)}}function Bi(n,e,t,s){e==="assistant"&&st(n.phase,"assistant message phase");let r=n.content;if(typeof r=="string"){t.push({role:e,text:r});return}if(!Array.isArray(r))throw new D(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of r){if(!ne(i))throw new D("decisions assistant message parts must be JSON objects");if(i.type==="output_text"&&typeof i.text=="string")t.push({role:e,text:i.text});else if(i.type==="refusal"&&typeof i.refusal=="string")t.push({role:e,text:`[refusal] ${i.refusal}`});else throw new D(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}Ls(r,t,s,e)}function Ls(n,e,t,s,r=!0){for(let i of n){if(!ne(i))throw new D("decisions content parts must be JSON objects");switch(st(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new D("input_text requires a string text");e.push({role:s,text:i.text});break}case"input_json":{if(!r)throw new D("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let o=i.data;if(!ne(o)&&!(Array.isArray(o)&&o.every(ne)))throw new D("input_json data must be an object or an array of objects");e.push({role:s,json:o});break}case"input_image":{t.push($s(i));break}default:throw new D(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function $s(n){let e=n.image_url;if(typeof e!="string"||e==="")throw new D("input_image requires a string image_url");let t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(t===null)throw new D("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,s,r]=t;if(r==="")throw new D("input_image data URL carries no image data");let i=r.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(r)||(i?r.length%4!==0:r.length%4===1))throw new D("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let o=n.detail;if(o!=null&&o!=="low"&&o!=="high"&&o!=="auto"&&o!=="original")throw new D("input_image detail must be low, high, auto, or original");let a={type:"image",mime:s,data:r};return(o==="low"||o==="high")&&(a.detail=o),a}function ji(n,e,t,s){if(!ne(n))throw new D(`questions[${e}] must be a JSON object`);let r=n.type;if(r!=="predicate"&&r!=="choice"&&r!=="score")throw new D(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(r??null)})`);let i=n.name;if(i!==void 0&&typeof i!="string")throw new D(`questions[${e}] name must be a string`);let o=i??null,a=o??`q${e}`,u=Hi(n.instructions,e,t,s);switch(r){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:r,key:a,name:o}};case"choice":{let l=n.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new D(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let b of l){if(!ne(b))throw new D(`questions[${e}] choices must be JSON objects`);let k=b.value;if(typeof k!="string"&&typeof k!="boolean")throw new D(`questions[${e}] choice value must be a string or boolean`);let _=String(k);if(c.has(_))throw new D(`questions[${e}] has duplicate choice value ${JSON.stringify(_)} (choices must be unique)`);c.add(_);let y=b.description;if(y!==void 0&&typeof y!="string")throw new D(`questions[${e}] choice description must be a string`);d.push(k),p.push(y)}let m=l.map((b,k)=>({name:String(d[k]),description:p[k]??String(d[k])}));return{entry:{kind:"choice",prompt:u,options:m},spec:{type:r,key:a,name:o,choiceValues:d}}}case"score":{let l=n.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new D(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!ne(m)||typeof m.label!="string")throw new D(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new D(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let f=m.description;if(f!==void 0&&typeof f!="string")throw new D(`questions[${e}] score level description must be a string`);let b=f!==void 0?`${m.label}: ${f}`:m.label;if(c.includes(b))throw new D(`questions[${e}] has duplicate score criterion ${JSON.stringify(b)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(b)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:r,key:a,name:o,levelLabels:d}}}}}function Hi(n,e,t,s){if(typeof n=="string")return n;if(!Array.isArray(n))throw new D(`questions[${e}] instructions must be a string or an array of input parts`);let r=[];for(let i of n){if(!ne(i))throw new D(`questions[${e}] instruction parts must be JSON objects`);switch(st(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new D(`questions[${e}] input_text requires a string text`);r.push(i.text);break}case"input_image":{if(t>1)throw new D(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);s.push($s(i));break}case"input_json":{let o=i.data;if(!ne(o)&&!(Array.isArray(o)&&o.every(ne)))throw new D(`questions[${e}] input_json data must be an object or an array of objects`);r.push(JSON.stringify(o));break}default:throw new D(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return r.join(`
23
23
 
24
- `)}function $s(n,e){if(!ne(e))throw new ae("decision answer was not a JSON object");let t=e.answers;if(!ne(t))throw new ae("decision answer carried no answers object");let s=[];for(let r of n){let i=t[r.key];if(!ne(i)||i.skipped===!0){s.push({type:"refusal",name:r.name});continue}let o=ne(i.probabilities)?i.probabilities:{};switch(r.type){case"predicate":{let a=Tn(i.noul);if(a===null)throw new ae(`the predicate answer for "${r.key}" carries no noul probability to translate`);s.push({type:"predicate",name:r.name,probability:a});continue}case"choice":{let a=r.choiceValues??[],u=i.choice;if(typeof u!="string")throw new ae(`the choice answer for "${r.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new ae(`the choice answer for "${r.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=kt(i.confidence);if(d===null)throw new ae(`the choice answer for "${r.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let m=Tn(o[String(p)]);m!==null&&c.push({value:p,probability:m})}s.push({type:"choice",name:r.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=r.levelLabels??[],u=kt(i.score);if(u===null)throw new ae(`the score answer for "${r.key}" carries no numeric score to translate`);let l=kt(i.confidence);if(l===null)throw new ae(`the score answer for "${r.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let p=Tn(o[String(c)]);p!==null&&d.push({value:c,label:a[c],probability:p})}s.push({type:"score",name:r.name,score:u,confidence:l,probabilities:d});continue}}}return s}function nt(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:null}function Gi(n){let e=ne(n.input_tokens_details)?n.input_tokens_details.cached_tokens:void 0,t=e!==void 0?e:n.cached_tokens;return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:0}function Fs(n){if(n==null)return null;if(!ne(n))throw new ae("decision reply carried a usage receipt that is not a JSON object");let e=nt(n.prompt_tokens)??nt(n.input_tokens),t=nt(n.completion_tokens)??nt(n.output_tokens);if(e===null||t===null)throw new ae("decision reply carried a usage receipt with no usable token counts");let s=kt(n.ttft_ms),r=nt(n.total_tokens)??nt(e+t);if(r===null)throw new ae("decision reply carried a usage receipt with an unusable token total");return{input_tokens:e,input_tokens_details:{cache_write_tokens:0,cached_tokens:Gi(n)},output_tokens:t,output_tokens_details:{reasoning_tokens:0},total_tokens:r,...s!==null?{ttft_ms:s}:{}}}C();C();var ie=class extends Error{};async function Gt(n,e){let t=Number(n.headers["content-length"]??"0");if(Number.isFinite(t)&&t>e)throw new ie(`request body exceeds the ${e}-byte limit`);let s=[],r=0;for await(let i of n){let o=i;if(r+=o.length,r>e)throw new ie(`request body exceeds the ${e}-byte limit`);s.push(o)}return Buffer.concat(s)}async function Jt(n,e){let t=n[Symbol.asyncIterator](),s=0,r=new ReadableStream({async pull(o){try{let a=await t.next();if(a.done){o.close();return}if(s+=a.value.length,s>e){o.error(new ie(`request body exceeds the ${e}-byte limit`));return}o.enqueue(a.value)}catch(a){o.error(a)}},cancel(){t.return?.()}}),i;try{let o=new Headers;for(let[l,d]of Object.entries(n.headers))if(typeof d=="string")o.set(l,d);else if(Array.isArray(d))for(let c of d)o.append(l,c);let a={method:"POST",headers:o,body:r,duplex:"half"};i=await new Request(`https://proxy.internal${n.url??"/"}`,a).formData()}catch(o){throw o instanceof ie?o:new Error(`malformed multipart body: ${String(o instanceof Error?o.message:o)}`)}return i}var Ds="/v1/images/generations",Wt="/v1/images/edits";function Ns(n){return n===Ds||n===Wt}var qs="/v1/images/models";async function Us(n,e,t){if(n){if(n.model=ue({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}}var B=class extends Error{status;param;constructor(e,t,s){super(t),this.status=e,this.param=s}},Ji=16*1024*1024,Bs=64*1024*1024;function js(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":null}function St(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Hs(n,e,t,s,r,i){let o=i??(f=>console.error(f)),a=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1},s),u=null;for await(let f of a){if(f.type==="error"){let b=f.error??{},k=typeof b.message=="string"&&b.message.length>0&&ve(b.message)?b.message:null;throw k===null?(o(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(f)}`),new B(502,"the image upstream failed while serving this request")):new B(502,`image upstream error: ${k}`)}if(f.type==="response.completed"){u=f.response??null;break}}if(u===null)throw new B(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");r&&(r.outputSeconds=Ie(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new B(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(js(p)===null)throw new B(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Gs(n,e){if(n instanceof B)return n;if(n instanceof Oe)throw n;return n instanceof J?new B(404,n.message):new B(502,ze("image",n,e))}async function Js(n,e,t,s){if(await n(e,t))return!0;let r=t==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return St(s,new B(404,e===void 0?`no image-capable default model is configured for this caller (${r}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${t==="edit"?"edit-capable":"generation-capable"} for this caller (${r}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ws(n,e){n&&(n.outputUnits=e.images.length)}function Vs(n,e){n.statusCode=200,n.setHeader("content-type","application/json"),n.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(t=>({b64_json:t}))}))}var Wi={model:!0,prompt:!0,response_format:!0,n:!0};async function zs(n,e,t){let s=t.operatorLog??(i=>console.error(i)),r=t.maxBodyBytes??Bs;try{if(n.method!=="POST")throw new B(405,`${String(n.method)} is not supported on ${Ds}`);let i;try{i=JSON.parse((await Gt(n,r)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new B(413,p.message):new B(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new B(400,"request body must be a JSON object");let o=i;for(let p of Object.keys(o))if(!Wi[p])throw new B(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=o.prompt;if(typeof a!="string"||a.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string","prompt");let u=o.model===void 0?void 0:o.model;if(u!==void 0&&typeof u!="string")throw new B(400,"model must be a string","model");await Us(t.turn,t.clients,u);let l=o.n??1;if(l!==1)throw new B(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=o.response_format??"b64_json";if(d!=="b64_json")throw new B(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(t.stats?.request("images_generations",a.length,a.length),!await Js(t.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Hs(t.clients,u,c,t.turn?fe(t.turn):void 0,t.turn,s);Ws(t.turn,p),Vs(e,p)}catch(p){throw Gs(p,s)}}catch(i){if(i instanceof ie){St(e,new B(413,i.message));return}if(i instanceof B){St(e,i);return}throw i}}var Vi={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ks(n,e,t){let s=t.operatorLog??(o=>console.error(o)),r=t.maxBodyBytes??Bs,i=t.maxImagePartBytes??Ji;try{if(n.method!=="POST")throw new B(405,`${String(n.method)} is not supported on ${Wt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the edit endpoint consumes multipart/form-data, got ${o||"none"}`);let a;try{a=await Jt(n,r)}catch(f){throw f instanceof ie?new B(413,f.message):new B(400,String(f instanceof Error?f.message:f))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new B(400,"model must be a string field","model");let d=l===null?void 0:l;await Us(t.turn,t.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new B(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of a.keys())if(!Vi[f])throw new B(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let p=[];for(let f of["image","image[]"])for(let b of a.getAll(f)){if(!(b instanceof File))throw new B(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(b.size>i)throw new B(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let k=new Uint8Array(await b.arrayBuffer()),_=js(k);if(_===null)throw new B(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);p.push({bytes:k,mime:_})}if(p.length===0)throw new B(400,"the edit endpoint requires at least one `image` file part","image");if(t.stats?.request("images_edits",u.length,u.length),!await Js(t.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:u}];for(let{bytes:f,mime:b}of p)m.push({type:"input_image",image_url:`data:${b};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Hs(t.clients,d,m,t.turn?fe(t.turn):void 0,t.turn,s);Ws(t.turn,f),Vs(e,f)}catch(f){throw Gs(f,s)}}catch(o){if(o instanceof ie){St(e,new B(413,o.message));return}if(o instanceof B){St(e,o);return}throw o}}C();var xt="/v1/audio/speech";function rr(n){return n===xt}var Xs=4096,Ys=18e4,Qs=5e3,zi=64*1024*1024,Zs=8,er=5,tr=1024*1024,rt="voice_applied",zt="X-Urun-Voice-Applied",U=class extends Error{status;param;retryAfterSeconds;constructor(e,t,s,r){super(t),this.status=e,this.param=s,this.retryAfterSeconds=r}};function On(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&n.setHeader("retry-after",String(e.retryAfterSeconds)),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Kt=class extends U{constructor(e){super(502,e)}};function ir(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t!==9&&!(t>=32&&t<=126)&&!(t>=128&&t<=255))return!1}return!0}function or(n){return new U(502,`the runtime's ${rt} receipt ${JSON.stringify(n)} cannot be relayed as the ${zt} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function Ki(n,e,t){if(n){if(n.model=ue({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}}function ar(n,e){if(!n)return;let t=e/(24e3*2);n.outputUnits=t,n.outputMinutes=t/60}var Xi=2;function Yi(n){for(let e=0;e+1<n.byteLength;e+=2)if(Math.abs(n.readInt16LE(e))>Xi)return!1;return!0}function Qi(n){let e=24e3,t=2,s=1,r=Buffer.alloc(44);return r.write("RIFF",0,"ascii"),r.writeUInt32LE(36+n,4),r.write("WAVE",8,"ascii"),r.write("fmt ",12,"ascii"),r.writeUInt32LE(16,16),r.writeUInt16LE(1,20),r.writeUInt16LE(s,22),r.writeUInt32LE(e,24),r.writeUInt32LE(e*s*t,28),r.writeUInt16LE(s*t,32),r.writeUInt16LE(16,34),r.write("data",36,"ascii"),r.writeUInt32LE(n,40),r}var nr=new WeakMap,Vt=new WeakMap;function Zi(n,e){let t=Vt.get(n)??0;if(t>=Zs)throw new U(503,`this model's speech queue is full \u2014 ${Zs} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${er}s`,void 0,er);Vt.set(n,t+1);let s=nr.get(n)??Promise.resolve(),r,i=new Promise(o=>{r=o});return nr.set(n,i),(async()=>{await s;try{return await e()}finally{Vt.set(n,(Vt.get(n)??1)-1),r()}})()}async function eo(n,e,t,s){if(typeof n.evictSpeechSession!="function")throw new U(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await n.evictSpeechSession(e)}catch(o){if(!(o instanceof Q))throw o}if(t?.return===void 0)return;let r=Promise.resolve(t.return()).then(()=>{},()=>{}),i;await Promise.race([r,new Promise(o=>{i=setTimeout(o,s)})]).finally(()=>{clearTimeout(i)})}function He(n,e){if(n instanceof U)return n;if(n instanceof Oe)throw n;return n instanceof J?new U(404,n.message):new U(502,ze("speech",n,e))}async function sr(n,e,t,s,r,i,o,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Zi(e,async()=>{if(o?.()===!0)return null;let p=!1,m=!1,f=!1,b,k=new Promise(w=>{b=w}),_=[],y,h=!1,v=null,L=()=>{v!==null&&(clearTimeout(y),y=setTimeout(()=>{h=!0,v?.()},r.capMs))},O=()=>{m&&!f&&_.length>=r.quietRunFrames&&(f=!0,b())},I=e.onOutputAudio(w=>{let R=Buffer.from(w,"base64");if(R.byteLength===0)return;L();let M=Yi(R);if(!p){if(M)return;p=!0}if(M){_.push(R),O();return}for(let q of _)c(q);_.length=0,c(R),O()}),S=null,A,g;try{g=(await n.createResponseOn(t,{model:s.model,input:[{role:"user",content:[{type:"input_text",text:s.text}]}],stream:!1,...s.voice!==void 0?{voice:s.voice}:{}}))[Symbol.asyncIterator]();let R=()=>(clearTimeout(A),new Promise($=>{A=setTimeout($,i.capMs)})),M=R(),q=!1;for(;;){let $=g.next(),N=await Promise.race([$,M]);if(N===void 0){q=!0,$.catch(()=>{});break}if(N.done)break;let H=N.value;if(M=R(),H.type==="error"){let T=H.error??{};await g.return?.();let z=typeof T.message=="string"&&T.message.length>0&&ve(T.message)?T.message:null;throw z===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(H)}`),new U(502,"the speech upstream failed while serving this request")):new U(502,`speech upstream error: ${z}`)}if(H.type==="response.completed"){S=H.response??null,m=!0,u?.(S),O(),await g.return?.();break}}if(clearTimeout(A),q)throw new U(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(S===null)throw new U(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=new Promise($=>{v=$});if(L(),await Promise.race([k,j]),clearTimeout(y),y=void 0,v=null,s.voice!==void 0){let $=S[rt];if(typeof $!="string"||$!==s.voice){let N=`the runtime did not acknowledge the requested voice ${JSON.stringify(s.voice)} \u2014 the terminal response carried ${typeof $=="string"?`${rt} ${JSON.stringify($)}`:`no ${rt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw f?new Kt(N):new U(502,N)}}if(!p)throw new U(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(h&&!f&&_.length<1)throw new U(502,`the upstream audio stream did not quiesce within ${r.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return S}catch(w){throw w instanceof Kt||await eo(n,t,g,i.returnBoundMs),w}finally{clearTimeout(y),clearTimeout(A),I()}})}function to(n,e,t,s){let r=!1,i=0,o=a=>{n.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){t()||(r||(r=!0,n.statusCode=200,n.setHeader("content-type","audio/pcm"),s&&n.setHeader("trailer",zt)),n.write(a,u=>{u||(i+=a.byteLength,ar(e,i))}),n.writableLength>tr&&(e&&(e.streamError=!0),o(new Error(`the streamed pcm answer's undrained buffer crossed ${tr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>r,async finish(a){if(!t()){if(s){let u=a[rt];if(typeof u=="string"){if(!ir(u))throw or(u);n.addTrailers({[zt]:u})}}await new Promise(u=>{n.end(()=>u())})}},fail:o}}async function no(n,e,t,s){let r;try{r=await n(e)}catch(i){throw He(i,s)}return r?!0:(On(t,new U(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var so={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},ro="wav, pcm";async function ur(n,e,t){let s=t.operatorLog??(a=>console.error(a)),r=t.maxBodyBytes??zi,i=!1;e.once("close",()=>{i=!0});let o=()=>i||e.destroyed;try{if(n.method!=="POST")throw new U(405,`${String(n.method)} is not supported on ${xt}`);let a;try{a=JSON.parse((await Gt(n,r)).toString("utf8")||"{}")}catch(v){throw v instanceof ie?new U(413,v.message):new U(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new U(400,"request body must be a JSON object");let u=a;for(let v of Object.keys(u))if(!so[v])throw new U(400,`request field "${v}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,v);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new U(400,"input is required and must be a non-empty string","input");if(l.length>Xs)throw new U(400,`input is ${l.length} chars \u2014 over the ${Xs}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new U(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new U(400,"voice must be a non-empty string","voice");if(typeof t.clients.speechVoices!="function")throw new U(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${xt} against a stale copy of the list`);let p;try{p=await t.clients.speechVoices(d)}catch(v){throw He(v,s)}if(p.defect!==null)throw new U(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new U(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let f=u.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new U(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${ro} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new U(400,"stream_format, when present, must be a string","stream_format");let b=u.speed;if(b!==void 0){if(typeof b!="number"||!Number.isFinite(b))throw new U(400,"speed, when present, must be a number","speed");if(b!==1)throw new U(400,`speed=${JSON.stringify(b)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let k=u.instructions;if(k!==void 0){if(typeof k!="string")throw new U(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new U(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await Ki(t.turn,t.clients,d);let _=Buffer.byteLength(JSON.stringify(u));if(t.stats?.request("audio_speech",_,_),!await no(t.speechModels,d,e,s))return;if(typeof t.clients.openAudioOn!="function")throw new U(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof t.clients.speechSessionHandle!="function")throw new U(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof t.clients.evictSpeechSession!="function")throw new U(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(o())return;let y;try{y=await t.clients.speechSessionHandle(d)}catch(v){throw He(v,s)}let h;try{h=await t.clients.openAudioOn(y)}catch(v){throw He(v,s)}t.turn&&(t.turn.sessionId=h.sessionId);try{if(f==="wav"){let v=[],L=await sr(t.clients,h,y,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Ys,returnBoundMs:t.turnReturnBoundMs??Qs},o,I=>v.push(I),I=>{t.turn&&(t.turn.outputSeconds=Ie(I))},s);if(L===null||o())return;let O=Buffer.concat(v);if(m===void 0){let I=L[rt];if(typeof I=="string"){if(!ir(I))throw or(I);e.setHeader(zt,I)}}ar(t.turn,O.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Qi(O.byteLength),O]))}else{let v=to(e,t.turn,o,m===void 0),L;try{L=await sr(t.clients,h,y,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Ys,returnBoundMs:t.turnReturnBoundMs??Qs},o,v.sink,O=>{t.turn&&(t.turn.outputSeconds=Ie(O))},s)}catch(O){let I=He(O,s);if(!v.started())throw I;t.turn&&(t.turn.streamError=!0),v.fail(I);return}if(L===null)return;try{await v.finish(L)}catch(O){let I=He(O,s);t.turn&&(t.turn.streamError=!0),v.fail(I);return}}}catch(v){throw He(v,s)}}catch(a){if(a instanceof ie){On(e,new U(413,a.message));return}if(a instanceof U){On(e,a);return}throw a}}C();var Xt="/v1/audio/transcriptions";function lr(n){return n===Xt}var dr="/v1/audio/models",io=16*1024*1024,oo=64*1024*1024,Y=class extends Error{status;param;constructor(e,t,s){super(t),this.status=e,this.param=s}};function Pn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function cr(n){return n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===65&&n[10]===86&&n[11]===69}function ao(n){if(!cr(n))return null;let e=12,t=null,s=null;for(;e+8<=n.length;){let i=String.fromCharCode(n[e],n[e+1],n[e+2],n[e+3]),o=(n[e+4]|n[e+5]<<8|n[e+6]<<16|n[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=n.length){let u=n[a+2]|n[a+3]<<8,l=(n[a+4]|n[a+5]<<8|n[a+6]<<16|n[a+7]<<24)>>>0,d=n[a+14]|n[a+15]<<8;t={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=n.length-a;s=Math.min(o===0||o===4294967295?u:o,u)}e=a+o+o%2}if(t===null||s===null||s===0||t.sampleRate===0||t.channels===0||t.bitsPerSample===0)return null;let r=s/(t.sampleRate*t.channels*(t.bitsPerSample/8));return!Number.isFinite(r)||r<0?null:{seconds:r,sampleRate:t.sampleRate,channels:t.channels,bitsPerSample:t.bitsPerSample}}async function uo(n,e,t){if(n){if(n.model=ue({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}}function lo(n,e){n&&(n.outputUnits=e.seconds)}async function co(n,e,t,s,r,i,o){let a=o??(c=>console.error(c)),u=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1,...s!==void 0?{language:s}:{}},r),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",f=typeof p.message=="string"&&p.message.length>0&&ve(p.message)?p.message:null;throw f===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Y(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Y(m==="invalid_request_error"?400:502,`transcription upstream error: ${f}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Y(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=Ie(d)),et(l,d)}function pr(n,e){if(n instanceof Y)return n;if(n instanceof Oe)throw n;return n instanceof J?new Y(404,n.message):new Y(502,ze("transcription",n,e))}async function po(n,e,t,s){let r;try{r=await n(e)}catch(i){throw pr(i,s)}return r?!0:(Pn(t,new Y(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var mo=new Set(["file","model","language","response_format"]);async function mr(n,e,t){let s=t.operatorLog??(o=>console.error(o)),r=t.maxBodyBytes??oo,i=t.maxAudioPartBytes??io;try{if(n.method!=="POST")throw new Y(405,`${String(n.method)} is not supported on ${Xt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new Y(400,`the transcriptions endpoint consumes multipart/form-data, got ${o||"none"}`);let a;try{a=await Jt(n,r)}catch(y){throw y instanceof ie?new Y(413,y.message):new Y(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of a.keys()){if(!mo.has(y))throw new Y(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,h]of u)if(h>1)throw new Y(400,`form field "${y}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let l=a.get("model");if(l!==null&&typeof l!="string")throw new Y(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Y(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=a.get("response_format")??"json";if(m!=="json")throw new Y(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=a.get("file");if(!(f instanceof File))throw new Y(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>i)throw new Y(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let b=new Uint8Array(await f.arrayBuffer());if(!cr(b))throw new Y(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let k=ao(b);if(k===null)throw new Y(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await uo(t.turn,t.clients,d),t.stats?.request("audio_transcriptions",b.length,b.length),!await po(t.transcriptionModels,d,e,s))return;let _=[{type:"input_audio",input_audio:{data:Buffer.from(b).toString("base64"),format:"wav"}}];try{let y=await co(t.clients,d,_,p,t.turn?fe(t.turn):void 0,t.turn,s);lo(t.turn,k),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw pr(y,s)}}catch(o){if(o instanceof ie){Pn(e,new Y(413,o.message));return}if(o instanceof Y){Pn(e,o);return}throw o}}C();var _r="/v1/usage/requests",fr=1e4,fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Le=class extends Error{constructor(t,s=400){super(t);this.status=s;this.name="UsageRequestError"}status},se=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Yt=class extends se{constructor(e){super(e),this.name="UsageWithholdingError"}},wr=1024*1024;function Ln(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new Le(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let t=n[e];if(!Array.isArray(t))throw new Le(`"${e}" must be an array of uuid strings`);if(t.length>fr)throw new Le(`"${e}" carries ${t.length} ids; at most ${fr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let s=[],r=new Set;for(let i of t){if(typeof i!="string"||!fo.test(i))throw new Le(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);r.has(i)||(r.add(i),s.push(i))}return s}function vr(n){return Ln(n,"inference_ids")}var ho=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function it(n,e,t){let s=n[e];if(typeof s!="string"||s==="")throw new se(`${t}: ${e} is not a non-empty string (got ${at(s)})`);return s}function Mn(n,e,t){let s=n[e];if(s===null)return null;if(typeof s!="string"||s==="")throw new se(`${t}: ${e} is neither null nor a non-empty string (got ${at(s)})`);return s}function ot(n,e,t,s){let r=n[e];if(r===null)return null;let i=typeof r=="number"?r:typeof r=="string"&&/^-?\d+(\.\d+)?$/.test(r.trim())?Number(r.trim()):NaN;if(!Number.isFinite(i))throw new se(`${t}: ${e} is not a number (got ${at(r)})`);if(s&&!Number.isSafeInteger(i))throw new se(`${t}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(i<0)throw new se(`${t}: ${e} is negative`);return Object.is(i,-0)?0:i}var go=40,hr=64,gr=600;function br(n){let e=Object.keys(n).sort(),s=e.slice(0,go).map(r=>r.length>hr?`${r.slice(0,hr)}\u2026`:r).join(", ");return s.length>gr&&(s=`${s.slice(0,gr)}\u2026`),`${e.length} keys present: [${s}]`}function at(n){return n===null?"null":n===void 0?"undefined":Array.isArray(n)?"an array":typeof n=="object"?"an object":`a ${typeof n}`}function Cn(n){Pe(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:n.where,reason:n.reason})}
25
- `)}function yo(n,e){let t;try{t=n(e)}catch{yr(n,e);return}_o(t)&&Promise.resolve(t).catch(()=>{yr(n,e)})}function _o(n){return typeof n?.then=="function"}function yr(n,e){if(n!==Cn)try{Cn(e)}catch{}}function ul(n,e=Cn){let t=n?.requests;if(!Array.isArray(t)){let r=n!==null&&typeof n=="object"&&!Array.isArray(n)?br(n):at(n);throw new se(`the usage surface answered without a "requests" array: got ${at(t)} (${r})`)}let s=[];for(let r=0;r<t.length;r++){let i=`usage.requests[${r}]`;try{s.push(wo(t[r],i))}catch(o){if(o instanceof Yt||!(o instanceof se))throw o;yo(e,{where:i,reason:o.message})}}if(t.length>0&&s.length===0)throw new se(`the usage surface returned ${t.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return s}function wo(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new se(`${e} is not an object: got ${at(n)}`);let t=n;if(Object.hasOwn(t,"gpu_seconds"))throw new Yt(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let r of ho)if(!Object.hasOwn(t,r))throw new se(`${e} has no "${r}" column (${br(t)})`);let s=ot(t,"http_status",e,!0);if(s===null)throw new se(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:it(t,"inference_id",e),model_id:it(t,"model_id",e),identity_kind:it(t,"identity_kind",e),variant:Mn(t,"variant",e),task:it(t,"task",e),http_status:s,started_at:it(t,"started_at",e),completed_at:it(t,"completed_at",e),prompt_tokens:ot(t,"prompt_tokens",e,!0),completion_tokens:ot(t,"completion_tokens",e,!0),output_units:ot(t,"output_units",e,!1),output_minutes:ot(t,"output_minutes",e,!1),cost_nano_usd:ot(t,"cost_nano_usd",e,!0),price_version:Mn(t,"price_version",e),priced_at:Mn(t,"priced_at",e)}}function Qt(n,e){let t=new Set(e),s=new Set;for(let r=0;r<n.length;r++){let i=n[r];if(!t.has(i.inference_id))throw new se(`the usage surface returned an id at validated answer position ${r} that was not in the request (${e.length} asked, ${n.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(s.has(i.inference_id))throw new se(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);s.add(i.inference_id)}}import{SessionAllocationError as Jo,SessionFailedError as Wo}from"@urun-sh/core";C();var $n="/partners/huggingface/v1/billing/requests";function vo(n){return Ln(n,"requestIds")}function bo(n){return n>=200&&n<=399}function ko(n){let e=[];for(let t of n)t.cost_nano_usd!==null&&bo(t.http_status)&&e.push({requestId:t.inference_id,costNanoUsd:t.cost_nano_usd});return{requests:e.length>0?e:null}}async function kr(n,e){let t=vo(n),s=await e(t);return Qt(s,t),ko(s)}C();var So={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function xo(n){return So[n]??null}var Rr=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ro(n){let e=n?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ao(n){return n==="surface"}function Io(n){let e=n?.ledgerFailureReason;return Rr.includes(e)?e:"unknown"}var Eo=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Sr=["priced","unpriced"],To={written:Sr,already_written:Sr,skipped:Eo,failed:Rr},hl=Object.entries(To).flatMap(([n,e])=>e.map(t=>({outcome:n,reason:t})));function Oo(n){return n.status===null?!1:n.status>=200&&n.status<400&&!n.stream_error}function Po(n){let e=Date.parse(n.ts),t=Number.isFinite(n.duration_ms)?Math.max(0,n.duration_ms):0;return new Date(e-Math.round(t)).toISOString()}var Mo=256,xr=4096,Rt=12e4,Co=250,Lo=8e3,Ee=[],Fn=new Set,At=0,ut=!1;function gl(){return Ee.length}function yl(n=Date.now()){let e=Ee[0];return e===void 0?0:Math.max(0,n-e.queuedAt)}var Zt=new Set;function Ar(){return At===0&&Ee.length===0}function Ir(){if(Ar()){ut=!1;for(let n of[...Zt])n()}}async function _l(n=Er){return Ar()?!0:await new Promise(e=>{let t,s=()=>{Zt.delete(s),clearTimeout(t),e(!0)};Zt.add(s),t=setTimeout(()=>{Zt.delete(s),e(!1)},n),t.unref?.()})}function wl(){ut=!0;let n=[...Ee.splice(0,Ee.length),...Fn];for(let e of n)e.settled||Ge(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Er}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Ir(),n.length}var Er=5e3;function Tr(n,e){return`${JSON.stringify({event:n,ts:new Date().toISOString(),...e})}
26
- `}function $o(n){Pe(process.stdout,n)}function Or(n,e){try{n(e)}catch{}}function Pr(n){let{record:e,ledger:t}=n;if(t===null)return;let s=t.report??$o,r=xo(e.path);if(r===null)return;let i=d=>{try{t.observe(d)}catch{}},o=(d,c)=>{i({outcome:"skipped",reason:d}),Or(s,Tr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){o("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){o("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){o("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){o("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:r,http_status:e.status,started_at:Po(e),completed_at:e.ts,billable_outcome:Oo(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Ee.length>=xr){o("queue_full",`${Ee.length} ledger writes are already waiting (capacity ${xr}, ${At} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ee.push({entry:l,req:n.req,record:e,ledger:t,report:s,queuedAt:Date.now(),attempts:0,settled:!1}),At<Mo&&(At+=1,Fo())}async function Fo(){try{for(;;){let n=Do();if(n===void 0)return;Fn.add(n);try{await No(n)}finally{Fn.delete(n)}}}finally{At-=1,Ir()}}function Do(){let n=Date.now();for(;;){let e=Ee.shift();if(e===void 0)return;let t=n-e.queuedAt;if(t<Rt)return e;Ge(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${t}ms for the control plane (bound ${Rt}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function No(n){let{entry:e,record:t,ledger:s}=n;for(;;){n.attempts+=1;try{let r=await s.write(n.req,e);Ge(n,{outcome:"written",reason:r.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:r.inference_id,path:t.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:t.org,session_id:e.session_id,cost_nano_usd:r.cost_nano_usd,price_version:r.price_version,unpriced_reason:r.unpriced_reason,attempts:n.attempts});return}catch(r){let i=Ro(r);if(i!==null){Ge(n,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:n.attempts});return}let o=Io(r),a=Date.now()-n.queuedAt;if(ut){Ge(n,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:n.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${r instanceof Error?r.message:String(r)}`});return}if(Ao(o)&&a<Rt){if(await Uo(qo(n.attempts)),ut||Date.now()-n.queuedAt>=Rt){let u=Date.now()-n.queuedAt;Ge(n,{outcome:"failed",reason:ut?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:ut?"dropped_on_exit":"dwell_expired",attempts:n.attempts,waited_ms:u,error:`this row's backoff outlived the ${Rt}ms dwell bound (waited ${u}ms over ${n.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${r instanceof Error?r.message:String(r)}`});return}continue}Ge(n,{outcome:"failed",reason:o},{event:"inference_ledger_write_failed",reason:o,attempts:n.attempts,waited_ms:a,error:r instanceof Error?r.message:String(r)});return}}}function qo(n){return Math.min(Lo,Co*2**Math.max(0,n-1))}function Uo(n){return new Promise(e=>{setTimeout(e,n).unref?.()})}function Ge(n,e,t){if(n.settled)return;n.settled=!0;try{n.ledger.observe(e)}catch{}let{event:s,...r}=t;Or(n.report,Tr(s,{inference_id:n.entry.inference_id,path:n.record.path,org:n.record.org,...r}))}C();var Nn="x-urun-profile",It="voice";var de=class extends Error{status=400},Bo=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,jo=/\s/;function Ho(n){return Bo.test(n)}function Dn(n,e,t){let s=n[e];if(s===void 0)return t;if(typeof s!="boolean")throw new de(`stream_options.voice.${e} must be a boolean when present (got ${typeof s})`);return s}function Mr(n,e,t,s={}){let r=n[e];if(r===void 0)return t;if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new de(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(r)})`);if(s.min!==void 0&&r<s.min)throw new de(`stream_options.voice.${e} must be at least ${s.min} when present (got ${JSON.stringify(r)})${s.minReason?` \u2014 ${s.minReason}`:""}`);if(s.max!==void 0&&r>s.max)throw new de(`stream_options.voice.${e} must be at most ${s.max} when present (got ${JSON.stringify(r)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return r}function Cr(n,e){let t=Array.isArray(n)?n[0]:n,s=e.stream_options??void 0;if(s!==void 0&&(typeof s!="object"||Array.isArray(s)))throw new de(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(s)})`);let r=s,i=r?.profile,o=!1;if(t!=null){let l=t.trim();if(l==="")throw new de(`the ${Nn} header is empty \u2014 the only profile this lane accepts is "${It}" (omit the header for the ordinary lane)`);if(l!==It)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${It}"`);o=!0}if(i!==void 0){if(typeof i!="string"||i!==It)throw new de(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${It}"`);o=!0}if(!o)return null;if(e.stream!==!0)throw new de("the voice profile is streaming-only \u2014 send stream: true");let a=r?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new de("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Mr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Mr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Dn(u,"sentence_flush",!0),includeReasoning:Dn(u,"include_reasoning",!1),metadata:Dn(u,"metadata",!1)}}var lt=class{constructor(e,t){this.config=e;this.sink=t}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let t=this.boundedCut();this.sink(this.buffer.slice(0,t)),this.buffer=this.buffer.slice(t)}(this.buffer.length>=e||this.config.sentenceFlush&&Ho(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let r=e-1;r>0;r--)if(jo.test(this.buffer[r]))return r+1;let t=Math.max(1,e),s=this.buffer.charCodeAt(t-1);return s>=55296&&s<=56319?t-1:t}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function Bn(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Vo(n){n.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),n.flushHeaders(),n.socket?.setNoDelay(!0)}function oe(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function V(n,e,t,s="invalid_request_error",r){oe(n,e,{error:r?{message:t,type:s,code:r}:{message:t,type:s}})}function jn(n,e,t){let s=e.error,r=s?.type??"upstream_error",i=t?.operatorError??(d=>console.error(d)),o=xe(s),a=o??be(t?.inferenceId??null);o===null&&i(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=s?.code??null,l=r==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&n.setHeader("retry-after","30"),oe(n,l,{error:{message:a,type:r,code:u}})}function ke(n,e,t,s){oe(n,e,{type:"error",error:{type:t,message:s}})}function dt(n,e,t){if(e==="anthropic"){oe(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}oe(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var zo=64*1024*1024,Et=class extends Error{};async function Lr(n,e=zo){let t=[],s=0;for await(let i of n){if(s+=i.length,s>e)throw new Et(`request body exceeds ${e} bytes`);t.push(i)}let r=Buffer.concat(t).toString("utf8");return r?JSON.parse(r):{}}function Je(n,e,t,s){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:s}]}}function Dr(n){let e=n?.usage;if(!e||typeof e!="object")return{kind:"absent"};let t=e,s=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,r=s(t.input_tokens),i=s(t.output_tokens),o=u=>u??0,a=s(t.total_tokens)??o(r)+o(i);if(o(r)>0||o(i)>0){let u={input_tokens:o(r),output_tokens:o(i),total_tokens:a};return r===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return r===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function en(n){let e=Dr(n);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function $r(n){let e=en(n);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Ko(n)},completion_tokens_details:{reasoning_tokens:0}}}function Ko(n){let e=n?.usage;if(!e||typeof e!="object")return 0;let t=e.input_tokens_details;if(!t||typeof t!="object")return 0;let s=t.cached_tokens;return typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?s:0}function Xo(n,e){let t=Dr(e);t.kind==="absent"||t.kind==="partial"||(n.promptTokens=t.usage.input_tokens,n.completionTokens=t.usage.output_tokens)}function Yo(n){let e=n?.urun_timing;if(!e||typeof e!="object")return null;let t=e,s=u=>{let l=t[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},r=s("queue_ms"),i=s("prefill_ms"),o=s("decode_ms"),a=s("total_ms");return r===null||i===null||o===null||a===null?null:{queue_ms:r,prefill_ms:i,decode_ms:o,total_ms:a}}function Qo(n,e){let t=Yo(e);t&&(n.timing=t),n.outputSeconds=Ie(e)}function We(n,e){Xo(n,e),Qo(n,e)}async function sn(n,e,t){if(typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}function Nr(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let s of e)if(!(s.type!=="reasoning"||!Array.isArray(s.content)))for(let r of s.content)r.type==="reasoning_text"&&(t+=String(r.text??""));return t}function Zo(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var tn=class extends Error{};function ea(n,e){return Array.isArray(e)?e.map(t=>{let s=t;if(s.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:s.text};if(s.type==="image_url"){let r=s.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new tn(`unsupported chat content part type "${String(s.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ta(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let s of t.tool_calls){let r=s.function??{};e.push({type:"function_call",call_id:s.id,name:r.name,arguments:r.arguments})}continue}e.push({...t,content:ea(t.role,t.content)})}return e}function qn(n){return Qe(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function na(n,e,t,s,r,i,o){let a=_t(i.id),u=n.stream===!0;if(i.model=ue(n),i.stream=u,await sn(i,e,typeof n.model=="string"?n.model:void 0),u){let y;try{y=await vt({body:n,clients:e,store:t,stats:r,responseId:a,turn:i})}catch(h){if(h instanceof J){dt(s,"openai",h);return}if(h instanceof he){V(s,h.status,h.message);return}if(h instanceof _e||h instanceof ye){s.setHeader("retry-after","2"),V(s,503,h.message,"capacity_error");return}throw h}Bn(s);for await(let h of y.events){if(h.type==="error"){i.streamError=!0;let v=h.error,L=xe(v),O=L??be(i.id);L===null&&o(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(h)}`),s.write(`event: error
24
+ `)}function Fs(n,e){if(!ne(e))throw new ae("decision answer was not a JSON object");let t=e.answers;if(!ne(t))throw new ae("decision answer carried no answers object");let s=[];for(let r of n){let i=t[r.key];if(!ne(i)||i.skipped===!0){s.push({type:"refusal",name:r.name});continue}let o=ne(i.probabilities)?i.probabilities:{};switch(r.type){case"predicate":{let a=On(i.noul);if(a===null)throw new ae(`the predicate answer for "${r.key}" carries no noul probability to translate`);s.push({type:"predicate",name:r.name,probability:a});continue}case"choice":{let a=r.choiceValues??[],u=i.choice;if(typeof u!="string")throw new ae(`the choice answer for "${r.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new ae(`the choice answer for "${r.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=kt(i.confidence);if(d===null)throw new ae(`the choice answer for "${r.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let m=On(o[String(p)]);m!==null&&c.push({value:p,probability:m})}s.push({type:"choice",name:r.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=r.levelLabels??[],u=kt(i.score);if(u===null)throw new ae(`the score answer for "${r.key}" carries no numeric score to translate`);let l=kt(i.confidence);if(l===null)throw new ae(`the score answer for "${r.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let p=On(o[String(c)]);p!==null&&d.push({value:c,label:a[c],probability:p})}s.push({type:"score",name:r.name,score:u,confidence:l,probabilities:d});continue}}}return s}function nt(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:null}function Gi(n){let e=ne(n.input_tokens_details)?n.input_tokens_details.cached_tokens:void 0,t=e!==void 0?e:n.cached_tokens;return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:0}function Ds(n){if(n==null)return null;if(!ne(n))throw new ae("decision reply carried a usage receipt that is not a JSON object");let e=nt(n.prompt_tokens)??nt(n.input_tokens),t=nt(n.completion_tokens)??nt(n.output_tokens);if(e===null||t===null)throw new ae("decision reply carried a usage receipt with no usable token counts");let s=kt(n.ttft_ms),r=nt(n.total_tokens)??nt(e+t);if(r===null)throw new ae("decision reply carried a usage receipt with an unusable token total");return{input_tokens:e,input_tokens_details:{cache_write_tokens:0,cached_tokens:Gi(n)},output_tokens:t,output_tokens_details:{reasoning_tokens:0},total_tokens:r,...s!==null?{ttft_ms:s}:{}}}C();C();var ie=class extends Error{};async function Jt(n,e){let t=Number(n.headers["content-length"]??"0");if(Number.isFinite(t)&&t>e)throw new ie(`request body exceeds the ${e}-byte limit`);let s=[],r=0;for await(let i of n){let o=i;if(r+=o.length,r>e)throw new ie(`request body exceeds the ${e}-byte limit`);s.push(o)}return Buffer.concat(s)}async function Wt(n,e){let t=n[Symbol.asyncIterator](),s=0,r=new ReadableStream({async pull(o){try{let a=await t.next();if(a.done){o.close();return}if(s+=a.value.length,s>e){o.error(new ie(`request body exceeds the ${e}-byte limit`));return}o.enqueue(a.value)}catch(a){o.error(a)}},cancel(){t.return?.()}}),i;try{let o=new Headers;for(let[l,d]of Object.entries(n.headers))if(typeof d=="string")o.set(l,d);else if(Array.isArray(d))for(let c of d)o.append(l,c);let a={method:"POST",headers:o,body:r,duplex:"half"};i=await new Request(`https://proxy.internal${n.url??"/"}`,a).formData()}catch(o){throw o instanceof ie?o:new Error(`malformed multipart body: ${String(o instanceof Error?o.message:o)}`)}return i}var Ns="/v1/images/generations",Vt="/v1/images/edits";function qs(n){return n===Ns||n===Vt}var Us="/v1/images/models";async function Bs(n,e,t){if(n){if(n.model=ue({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}}var B=class extends Error{status;param;constructor(e,t,s){super(t),this.status=e,this.param=s}},Ji=16*1024*1024,js=64*1024*1024;function Hs(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":null}function St(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function Gs(n,e,t,s,r,i){let o=i??(f=>console.error(f)),a=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1},s),u=null;for await(let f of a){if(f.type==="error"){let b=f.error??{},k=typeof b.message=="string"&&b.message.length>0&&ve(b.message)?b.message:null;throw k===null?(o(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(f)}`),new B(502,"the image upstream failed while serving this request")):new B(502,`image upstream error: ${k}`)}if(f.type==="response.completed"){u=f.response??null;break}}if(u===null)throw new B(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");r&&(r.outputSeconds=Ie(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new B(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Hs(p)===null)throw new B(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Js(n,e){if(n instanceof B)return n;if(n instanceof Oe)throw n;return n instanceof J?new B(404,n.message):new B(502,ze("image",n,e))}async function Ws(n,e,t,s){if(await n(e,t))return!0;let r=t==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return St(s,new B(404,e===void 0?`no image-capable default model is configured for this caller (${r}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${t==="edit"?"edit-capable":"generation-capable"} for this caller (${r}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Vs(n,e){n&&(n.outputUnits=e.images.length)}function zs(n,e){n.statusCode=200,n.setHeader("content-type","application/json"),n.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(t=>({b64_json:t}))}))}var Wi={model:!0,prompt:!0,response_format:!0,n:!0};async function Ks(n,e,t){let s=t.operatorLog??(i=>console.error(i)),r=t.maxBodyBytes??js;try{if(n.method!=="POST")throw new B(405,`${String(n.method)} is not supported on ${Ns}`);let i;try{i=JSON.parse((await Jt(n,r)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new B(413,p.message):new B(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new B(400,"request body must be a JSON object");let o=i;for(let p of Object.keys(o))if(!Wi[p])throw new B(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let a=o.prompt;if(typeof a!="string"||a.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string","prompt");let u=o.model===void 0?void 0:o.model;if(u!==void 0&&typeof u!="string")throw new B(400,"model must be a string","model");await Bs(t.turn,t.clients,u);let l=o.n??1;if(l!==1)throw new B(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=o.response_format??"b64_json";if(d!=="b64_json")throw new B(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(t.stats?.request("images_generations",a.length,a.length),!await Ws(t.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Gs(t.clients,u,c,t.turn?fe(t.turn):void 0,t.turn,s);Vs(t.turn,p),zs(e,p)}catch(p){throw Js(p,s)}}catch(i){if(i instanceof ie){St(e,new B(413,i.message));return}if(i instanceof B){St(e,i);return}throw i}}var Vi={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Xs(n,e,t){let s=t.operatorLog??(o=>console.error(o)),r=t.maxBodyBytes??js,i=t.maxImagePartBytes??Ji;try{if(n.method!=="POST")throw new B(405,`${String(n.method)} is not supported on ${Vt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the edit endpoint consumes multipart/form-data, got ${o||"none"}`);let a;try{a=await Wt(n,r)}catch(f){throw f instanceof ie?new B(413,f.message):new B(400,String(f instanceof Error?f.message:f))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new B(400,"prompt is required and must be a non-empty string field","prompt");let l=a.get("model");if(l!==null&&typeof l!="string")throw new B(400,"model must be a string field","model");let d=l===null?void 0:l;await Bs(t.turn,t.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new B(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of a.keys())if(!Vi[f])throw new B(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let p=[];for(let f of["image","image[]"])for(let b of a.getAll(f)){if(!(b instanceof File))throw new B(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(b.size>i)throw new B(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let k=new Uint8Array(await b.arrayBuffer()),_=Hs(k);if(_===null)throw new B(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);p.push({bytes:k,mime:_})}if(p.length===0)throw new B(400,"the edit endpoint requires at least one `image` file part","image");if(t.stats?.request("images_edits",u.length,u.length),!await Ws(t.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:u}];for(let{bytes:f,mime:b}of p)m.push({type:"input_image",image_url:`data:${b};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Gs(t.clients,d,m,t.turn?fe(t.turn):void 0,t.turn,s);Vs(t.turn,f),zs(e,f)}catch(f){throw Js(f,s)}}catch(o){if(o instanceof ie){St(e,new B(413,o.message));return}if(o instanceof B){St(e,o);return}throw o}}C();var xt="/v1/audio/speech";function ir(n){return n===xt}var Ys=4096,Qs=18e4,Zs=5e3,zi=64*1024*1024,er=8,tr=5,nr=1024*1024,rt="voice_applied",Kt="X-Urun-Voice-Applied",U=class extends Error{status;param;retryAfterSeconds;constructor(e,t,s,r){super(t),this.status=e,this.param=s,this.retryAfterSeconds=r}};function Pn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&n.setHeader("retry-after",String(e.retryAfterSeconds)),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Xt=class extends U{constructor(e){super(502,e)}};function or(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t!==9&&!(t>=32&&t<=126)&&!(t>=128&&t<=255))return!1}return!0}function ar(n){return new U(502,`the runtime's ${rt} receipt ${JSON.stringify(n)} cannot be relayed as the ${Kt} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function Ki(n,e,t){if(n){if(n.model=ue({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}}function ur(n,e){if(!n)return;let t=e/(24e3*2);n.outputUnits=t,n.outputMinutes=t/60}function Xi(n){let e=24e3,t=2,s=1,r=Buffer.alloc(44);return r.write("RIFF",0,"ascii"),r.writeUInt32LE(36+n,4),r.write("WAVE",8,"ascii"),r.write("fmt ",12,"ascii"),r.writeUInt32LE(16,16),r.writeUInt16LE(1,20),r.writeUInt16LE(s,22),r.writeUInt32LE(e,24),r.writeUInt32LE(e*s*t,28),r.writeUInt16LE(s*t,32),r.writeUInt16LE(16,34),r.write("data",36,"ascii"),r.writeUInt32LE(n,40),r}var sr=new WeakMap,zt=new WeakMap;function Yi(n,e){let t=zt.get(n)??0;if(t>=er)throw new U(503,`this model's speech queue is full \u2014 ${er} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${tr}s`,void 0,tr);zt.set(n,t+1);let s=sr.get(n)??Promise.resolve(),r,i=new Promise(o=>{r=o});return sr.set(n,i),(async()=>{await s;try{return await e()}finally{zt.set(n,(zt.get(n)??1)-1),r()}})()}async function Qi(n,e,t,s){if(typeof n.evictSpeechSession!="function")throw new U(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await n.evictSpeechSession(e)}catch(o){if(!(o instanceof Q))throw o}if(t?.return===void 0)return;let r=Promise.resolve(t.return()).then(()=>{},()=>{}),i;await Promise.race([r,new Promise(o=>{i=setTimeout(o,s)})]).finally(()=>{clearTimeout(i)})}function He(n,e){if(n instanceof U)return n;if(n instanceof Oe)throw n;return n instanceof J?new U(404,n.message):new U(502,ze("speech",n,e))}async function rr(n,e,t,s,r,i,o,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Yi(e,async()=>{if(o?.()===!0)return null;let p=!1,m=!1,f=!1,b,k=new Promise(w=>{b=w}),_=[],y,h=!1,v=null,L=()=>{v!==null&&(clearTimeout(y),y=setTimeout(()=>{h=!0,v?.()},r.capMs))},O=()=>{m&&!f&&_.length>=r.quietRunFrames&&(f=!0,b())},I=e.onOutputAudio(w=>{let R=Buffer.from(w,"base64");if(R.byteLength===0)return;L();let M=Mt(R);if(!p){if(M)return;p=!0}if(M){_.push(R),O();return}for(let q of _)c(q);_.length=0,c(R),O()}),x=null,A,g;try{g=(await n.createResponseOn(t,{model:s.model,input:[{role:"user",content:[{type:"input_text",text:s.text}]}],stream:!1,...s.voice!==void 0?{voice:s.voice}:{}}))[Symbol.asyncIterator]();let R=()=>(clearTimeout(A),new Promise($=>{A=setTimeout($,i.capMs)})),M=R(),q=!1;for(;;){let $=g.next(),N=await Promise.race([$,M]);if(N===void 0){q=!0,$.catch(()=>{});break}if(N.done)break;let H=N.value;if(M=R(),H.type==="error"){let T=H.error??{};await g.return?.();let z=typeof T.message=="string"&&T.message.length>0&&ve(T.message)?T.message:null;throw z===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(H)}`),new U(502,"the speech upstream failed while serving this request")):new U(502,`speech upstream error: ${z}`)}if(H.type==="response.completed"){x=H.response??null,m=!0,u?.(x),O(),await g.return?.();break}}if(clearTimeout(A),q)throw new U(504,`the speech turn produced no terminal event within ${i.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(x===null)throw new U(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=new Promise($=>{v=$});if(L(),await Promise.race([k,j]),clearTimeout(y),y=void 0,v=null,s.voice!==void 0){let $=x[rt];if(typeof $!="string"||$!==s.voice){let N=`the runtime did not acknowledge the requested voice ${JSON.stringify(s.voice)} \u2014 the terminal response carried ${typeof $=="string"?`${rt} ${JSON.stringify($)}`:`no ${rt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw f?new Xt(N):new U(502,N)}}if(!p)throw new U(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(h&&!f&&_.length<1)throw new U(502,`the upstream audio stream did not quiesce within ${r.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return x}catch(w){throw w instanceof Xt||await Qi(n,t,g,i.returnBoundMs),w}finally{clearTimeout(y),clearTimeout(A),I()}})}function Zi(n,e,t,s){let r=!1,i=0,o=a=>{n.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){t()||(r||(r=!0,n.statusCode=200,n.setHeader("content-type","audio/pcm"),s&&n.setHeader("trailer",Kt)),n.write(a,u=>{u||(i+=a.byteLength,ur(e,i))}),n.writableLength>nr&&(e&&(e.streamError=!0),o(new Error(`the streamed pcm answer's undrained buffer crossed ${nr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>r,async finish(a){if(!t()){if(s){let u=a[rt];if(typeof u=="string"){if(!or(u))throw ar(u);n.addTrailers({[Kt]:u})}}await new Promise(u=>{n.end(()=>u())})}},fail:o}}async function eo(n,e,t,s){let r;try{r=await n(e)}catch(i){throw He(i,s)}return r?!0:(Pn(t,new U(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var to={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},no="wav, pcm";async function lr(n,e,t){let s=t.operatorLog??(a=>console.error(a)),r=t.maxBodyBytes??zi,i=!1;e.once("close",()=>{i=!0});let o=()=>i||e.destroyed;try{if(n.method!=="POST")throw new U(405,`${String(n.method)} is not supported on ${xt}`);let a;try{a=JSON.parse((await Jt(n,r)).toString("utf8")||"{}")}catch(v){throw v instanceof ie?new U(413,v.message):new U(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new U(400,"request body must be a JSON object");let u=a;for(let v of Object.keys(u))if(!to[v])throw new U(400,`request field "${v}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,v);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new U(400,"input is required and must be a non-empty string","input");if(l.length>Ys)throw new U(400,`input is ${l.length} chars \u2014 over the ${Ys}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new U(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new U(400,"voice must be a non-empty string","voice");if(typeof t.clients.speechVoices!="function")throw new U(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${xt} against a stale copy of the list`);let p;try{p=await t.clients.speechVoices(d)}catch(v){throw He(v,s)}if(p.defect!==null)throw new U(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new U(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let f=u.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new U(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${no} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new U(400,"stream_format, when present, must be a string","stream_format");let b=u.speed;if(b!==void 0){if(typeof b!="number"||!Number.isFinite(b))throw new U(400,"speed, when present, must be a number","speed");if(b!==1)throw new U(400,`speed=${JSON.stringify(b)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let k=u.instructions;if(k!==void 0){if(typeof k!="string")throw new U(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new U(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await Ki(t.turn,t.clients,d);let _=Buffer.byteLength(JSON.stringify(u));if(t.stats?.request("audio_speech",_,_),!await eo(t.speechModels,d,e,s))return;if(typeof t.clients.openAudioOn!="function")throw new U(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof t.clients.speechSessionHandle!="function")throw new U(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof t.clients.evictSpeechSession!="function")throw new U(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(o())return;let y;try{y=await t.clients.speechSessionHandle(d)}catch(v){throw He(v,s)}let h;try{h=await t.clients.openAudioOn(y)}catch(v){throw He(v,s)}t.turn&&(t.turn.sessionId=h.sessionId);try{if(f==="wav"){let v=[],L=await rr(t.clients,h,y,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Qs,returnBoundMs:t.turnReturnBoundMs??Zs},o,I=>v.push(I),I=>{t.turn&&(t.turn.outputSeconds=Ie(I))},s);if(L===null||o())return;let O=Buffer.concat(v);if(m===void 0){let I=L[rt];if(typeof I=="string"){if(!or(I))throw ar(I);e.setHeader(Kt,I)}}ur(t.turn,O.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Xi(O.byteLength),O]))}else{let v=Zi(e,t.turn,o,m===void 0),L;try{L=await rr(t.clients,h,y,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Qs,returnBoundMs:t.turnReturnBoundMs??Zs},o,v.sink,O=>{t.turn&&(t.turn.outputSeconds=Ie(O))},s)}catch(O){let I=He(O,s);if(!v.started())throw I;t.turn&&(t.turn.streamError=!0),v.fail(I);return}if(L===null)return;try{await v.finish(L)}catch(O){let I=He(O,s);t.turn&&(t.turn.streamError=!0),v.fail(I);return}}}catch(v){throw He(v,s)}}catch(a){if(a instanceof ie){Pn(e,new U(413,a.message));return}if(a instanceof U){Pn(e,a);return}throw a}}C();var Yt="/v1/audio/transcriptions";function dr(n){return n===Yt}var cr="/v1/audio/models",so=16*1024*1024,ro=64*1024*1024,Y=class extends Error{status;param;constructor(e,t,s){super(t),this.status=e,this.param=s}};function Mn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function pr(n){return n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===65&&n[10]===86&&n[11]===69}function io(n){if(!pr(n))return null;let e=12,t=null,s=null;for(;e+8<=n.length;){let i=String.fromCharCode(n[e],n[e+1],n[e+2],n[e+3]),o=(n[e+4]|n[e+5]<<8|n[e+6]<<16|n[e+7]<<24)>>>0,a=e+8;if(i==="fmt "&&a+16<=n.length){let u=n[a+2]|n[a+3]<<8,l=(n[a+4]|n[a+5]<<8|n[a+6]<<16|n[a+7]<<24)>>>0,d=n[a+14]|n[a+15]<<8;t={sampleRate:l,channels:u,bitsPerSample:d}}else if(i==="data"){let u=n.length-a;s=Math.min(o===0||o===4294967295?u:o,u)}e=a+o+o%2}if(t===null||s===null||s===0||t.sampleRate===0||t.channels===0||t.bitsPerSample===0)return null;let r=s/(t.sampleRate*t.channels*(t.bitsPerSample/8));return!Number.isFinite(r)||r<0?null:{seconds:r,sampleRate:t.sampleRate,channels:t.channels,bitsPerSample:t.bitsPerSample}}async function oo(n,e,t){if(n){if(n.model=ue({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}}function ao(n,e){n&&(n.outputUnits=e.seconds)}async function uo(n,e,t,s,r,i,o){let a=o??(c=>console.error(c)),u=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1,...s!==void 0?{language:s}:{}},r),l=[],d=null;for await(let c of u){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",f=typeof p.message=="string"&&p.message.length>0&&ve(p.message)?p.message:null;throw f===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Y(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Y(m==="invalid_request_error"?400:502,`transcription upstream error: ${f}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Y(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=Ie(d)),et(l,d)}function mr(n,e){if(n instanceof Y)return n;if(n instanceof Oe)throw n;return n instanceof J?new Y(404,n.message):new Y(502,ze("transcription",n,e))}async function lo(n,e,t,s){let r;try{r=await n(e)}catch(i){throw mr(i,s)}return r?!0:(Mn(t,new Y(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var co=new Set(["file","model","language","response_format"]);async function fr(n,e,t){let s=t.operatorLog??(o=>console.error(o)),r=t.maxBodyBytes??ro,i=t.maxAudioPartBytes??so;try{if(n.method!=="POST")throw new Y(405,`${String(n.method)} is not supported on ${Yt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new Y(400,`the transcriptions endpoint consumes multipart/form-data, got ${o||"none"}`);let a;try{a=await Wt(n,r)}catch(y){throw y instanceof ie?new Y(413,y.message):new Y(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of a.keys()){if(!co.has(y))throw new Y(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,h]of u)if(h>1)throw new Y(400,`form field "${y}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let l=a.get("model");if(l!==null&&typeof l!="string")throw new Y(400,"model must be a string field","model");let d=l===null?void 0:l,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Y(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=a.get("response_format")??"json";if(m!=="json")throw new Y(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=a.get("file");if(!(f instanceof File))throw new Y(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>i)throw new Y(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let b=new Uint8Array(await f.arrayBuffer());if(!pr(b))throw new Y(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let k=io(b);if(k===null)throw new Y(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await oo(t.turn,t.clients,d),t.stats?.request("audio_transcriptions",b.length,b.length),!await lo(t.transcriptionModels,d,e,s))return;let _=[{type:"input_audio",input_audio:{data:Buffer.from(b).toString("base64"),format:"wav"}}];try{let y=await uo(t.clients,d,_,p,t.turn?fe(t.turn):void 0,t.turn,s);ao(t.turn,k),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw mr(y,s)}}catch(o){if(o instanceof ie){Mn(e,new Y(413,o.message));return}if(o instanceof Y){Mn(e,o);return}throw o}}C();var wr="/v1/usage/requests",hr=1e4,po=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Le=class extends Error{constructor(t,s=400){super(t);this.status=s;this.name="UsageRequestError"}status},se=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Qt=class extends se{constructor(e){super(e),this.name="UsageWithholdingError"}},vr=1024*1024;function $n(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new Le(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let t=n[e];if(!Array.isArray(t))throw new Le(`"${e}" must be an array of uuid strings`);if(t.length>hr)throw new Le(`"${e}" carries ${t.length} ids; at most ${hr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let s=[],r=new Set;for(let i of t){if(typeof i!="string"||!po.test(i))throw new Le(`"${e}" contains ${JSON.stringify(i)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);r.has(i)||(r.add(i),s.push(i))}return s}function br(n){return $n(n,"inference_ids")}var mo=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function it(n,e,t){let s=n[e];if(typeof s!="string"||s==="")throw new se(`${t}: ${e} is not a non-empty string (got ${at(s)})`);return s}function Cn(n,e,t){let s=n[e];if(s===null)return null;if(typeof s!="string"||s==="")throw new se(`${t}: ${e} is neither null nor a non-empty string (got ${at(s)})`);return s}function ot(n,e,t,s){let r=n[e];if(r===null)return null;let i=typeof r=="number"?r:typeof r=="string"&&/^-?\d+(\.\d+)?$/.test(r.trim())?Number(r.trim()):NaN;if(!Number.isFinite(i))throw new se(`${t}: ${e} is not a number (got ${at(r)})`);if(s&&!Number.isSafeInteger(i))throw new se(`${t}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(i<0)throw new se(`${t}: ${e} is negative`);return Object.is(i,-0)?0:i}var fo=40,gr=64,yr=600;function kr(n){let e=Object.keys(n).sort(),s=e.slice(0,fo).map(r=>r.length>gr?`${r.slice(0,gr)}\u2026`:r).join(", ");return s.length>yr&&(s=`${s.slice(0,yr)}\u2026`),`${e.length} keys present: [${s}]`}function at(n){return n===null?"null":n===void 0?"undefined":Array.isArray(n)?"an array":typeof n=="object"?"an object":`a ${typeof n}`}function Ln(n){Pe(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:n.where,reason:n.reason})}
25
+ `)}function ho(n,e){let t;try{t=n(e)}catch{_r(n,e);return}go(t)&&Promise.resolve(t).catch(()=>{_r(n,e)})}function go(n){return typeof n?.then=="function"}function _r(n,e){if(n!==Ln)try{Ln(e)}catch{}}function ol(n,e=Ln){let t=n?.requests;if(!Array.isArray(t)){let r=n!==null&&typeof n=="object"&&!Array.isArray(n)?kr(n):at(n);throw new se(`the usage surface answered without a "requests" array: got ${at(t)} (${r})`)}let s=[];for(let r=0;r<t.length;r++){let i=`usage.requests[${r}]`;try{s.push(yo(t[r],i))}catch(o){if(o instanceof Qt||!(o instanceof se))throw o;ho(e,{where:i,reason:o.message})}}if(t.length>0&&s.length===0)throw new se(`the usage surface returned ${t.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return s}function yo(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new se(`${e} is not an object: got ${at(n)}`);let t=n;if(Object.hasOwn(t,"gpu_seconds"))throw new Qt(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let r of mo)if(!Object.hasOwn(t,r))throw new se(`${e} has no "${r}" column (${kr(t)})`);let s=ot(t,"http_status",e,!0);if(s===null)throw new se(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:it(t,"inference_id",e),model_id:it(t,"model_id",e),identity_kind:it(t,"identity_kind",e),variant:Cn(t,"variant",e),task:it(t,"task",e),http_status:s,started_at:it(t,"started_at",e),completed_at:it(t,"completed_at",e),prompt_tokens:ot(t,"prompt_tokens",e,!0),completion_tokens:ot(t,"completion_tokens",e,!0),output_units:ot(t,"output_units",e,!1),output_minutes:ot(t,"output_minutes",e,!1),cost_nano_usd:ot(t,"cost_nano_usd",e,!0),price_version:Cn(t,"price_version",e),priced_at:Cn(t,"priced_at",e)}}function Zt(n,e){let t=new Set(e),s=new Set;for(let r=0;r<n.length;r++){let i=n[r];if(!t.has(i.inference_id))throw new se(`the usage surface returned an id at validated answer position ${r} that was not in the request (${e.length} asked, ${n.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(s.has(i.inference_id))throw new se(`the usage surface returned ${i.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);s.add(i.inference_id)}}import{SessionAllocationError as Ho,SessionFailedError as Go}from"@urun-sh/core";C();var Fn="/partners/huggingface/v1/billing/requests";function _o(n){return $n(n,"requestIds")}function wo(n){return n>=200&&n<=399}function vo(n){let e=[];for(let t of n)t.cost_nano_usd!==null&&wo(t.http_status)&&e.push({requestId:t.inference_id,costNanoUsd:t.cost_nano_usd});return{requests:e.length>0?e:null}}async function Sr(n,e){let t=_o(n),s=await e(t);return Zt(s,t),vo(s)}C();var bo={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function ko(n){return bo[n]??null}var Ar=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function So(n){let e=n?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function xo(n){return n==="surface"}function Ro(n){let e=n?.ledgerFailureReason;return Ar.includes(e)?e:"unknown"}var Ao=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],xr=["priced","unpriced"],Io={written:xr,already_written:xr,skipped:Ao,failed:Ar},ml=Object.entries(Io).flatMap(([n,e])=>e.map(t=>({outcome:n,reason:t})));function Eo(n){return n.status===null?!1:n.status>=200&&n.status<400&&!n.stream_error}function To(n){let e=Date.parse(n.ts),t=Number.isFinite(n.duration_ms)?Math.max(0,n.duration_ms):0;return new Date(e-Math.round(t)).toISOString()}var Oo=256,Rr=4096,Rt=12e4,Po=250,Mo=8e3,Ee=[],Dn=new Set,At=0,ut=!1;function fl(){return Ee.length}function hl(n=Date.now()){let e=Ee[0];return e===void 0?0:Math.max(0,n-e.queuedAt)}var en=new Set;function Ir(){return At===0&&Ee.length===0}function Er(){if(Ir()){ut=!1;for(let n of[...en])n()}}async function gl(n=Tr){return Ir()?!0:await new Promise(e=>{let t,s=()=>{en.delete(s),clearTimeout(t),e(!0)};en.add(s),t=setTimeout(()=>{en.delete(s),e(!1)},n),t.unref?.()})}function yl(){ut=!0;let n=[...Ee.splice(0,Ee.length),...Dn];for(let e of n)e.settled||Ge(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Tr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Er(),n.length}var Tr=5e3;function Or(n,e){return`${JSON.stringify({event:n,ts:new Date().toISOString(),...e})}
26
+ `}function Co(n){Pe(process.stdout,n)}function Pr(n,e){try{n(e)}catch{}}function Mr(n){let{record:e,ledger:t}=n;if(t===null)return;let s=t.report??Co,r=ko(e.path);if(r===null)return;let i=d=>{try{t.observe(d)}catch{}},o=(d,c)=>{i({outcome:"skipped",reason:d}),Pr(s,Or("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){o("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){o("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){o("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){o("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...u,task:r,http_status:e.status,started_at:To(e),completed_at:e.ts,billable_outcome:Eo(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Ee.length>=Rr){o("queue_full",`${Ee.length} ledger writes are already waiting (capacity ${Rr}, ${At} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ee.push({entry:l,req:n.req,record:e,ledger:t,report:s,queuedAt:Date.now(),attempts:0,settled:!1}),At<Oo&&(At+=1,Lo())}async function Lo(){try{for(;;){let n=$o();if(n===void 0)return;Dn.add(n);try{await Fo(n)}finally{Dn.delete(n)}}}finally{At-=1,Er()}}function $o(){let n=Date.now();for(;;){let e=Ee.shift();if(e===void 0)return;let t=n-e.queuedAt;if(t<Rt)return e;Ge(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${t}ms for the control plane (bound ${Rt}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function Fo(n){let{entry:e,record:t,ledger:s}=n;for(;;){n.attempts+=1;try{let r=await s.write(n.req,e);Ge(n,{outcome:"written",reason:r.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:r.inference_id,path:t.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:t.org,session_id:e.session_id,cost_nano_usd:r.cost_nano_usd,price_version:r.price_version,unpriced_reason:r.unpriced_reason,attempts:n.attempts});return}catch(r){let i=So(r);if(i!==null){Ge(n,{outcome:"already_written",reason:i.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:i.cost_nano_usd,price_version:i.price_version,attempts:n.attempts});return}let o=Ro(r),a=Date.now()-n.queuedAt;if(ut){Ge(n,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:n.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${r instanceof Error?r.message:String(r)}`});return}if(xo(o)&&a<Rt){if(await No(Do(n.attempts)),ut||Date.now()-n.queuedAt>=Rt){let u=Date.now()-n.queuedAt;Ge(n,{outcome:"failed",reason:ut?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:ut?"dropped_on_exit":"dwell_expired",attempts:n.attempts,waited_ms:u,error:`this row's backoff outlived the ${Rt}ms dwell bound (waited ${u}ms over ${n.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${r instanceof Error?r.message:String(r)}`});return}continue}Ge(n,{outcome:"failed",reason:o},{event:"inference_ledger_write_failed",reason:o,attempts:n.attempts,waited_ms:a,error:r instanceof Error?r.message:String(r)});return}}}function Do(n){return Math.min(Mo,Po*2**Math.max(0,n-1))}function No(n){return new Promise(e=>{setTimeout(e,n).unref?.()})}function Ge(n,e,t){if(n.settled)return;n.settled=!0;try{n.ledger.observe(e)}catch{}let{event:s,...r}=t;Pr(n.report,Or(s,{inference_id:n.entry.inference_id,path:n.record.path,org:n.record.org,...r}))}C();var qn="x-urun-profile",It="voice";var de=class extends Error{status=400},qo=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Uo=/\s/;function Bo(n){return qo.test(n)}function Nn(n,e,t){let s=n[e];if(s===void 0)return t;if(typeof s!="boolean")throw new de(`stream_options.voice.${e} must be a boolean when present (got ${typeof s})`);return s}function Cr(n,e,t,s={}){let r=n[e];if(r===void 0)return t;if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new de(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(r)})`);if(s.min!==void 0&&r<s.min)throw new de(`stream_options.voice.${e} must be at least ${s.min} when present (got ${JSON.stringify(r)})${s.minReason?` \u2014 ${s.minReason}`:""}`);if(s.max!==void 0&&r>s.max)throw new de(`stream_options.voice.${e} must be at most ${s.max} when present (got ${JSON.stringify(r)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return r}function Lr(n,e){let t=Array.isArray(n)?n[0]:n,s=e.stream_options??void 0;if(s!==void 0&&(typeof s!="object"||Array.isArray(s)))throw new de(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(s)})`);let r=s,i=r?.profile,o=!1;if(t!=null){let l=t.trim();if(l==="")throw new de(`the ${qn} header is empty \u2014 the only profile this lane accepts is "${It}" (omit the header for the ordinary lane)`);if(l!==It)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${It}"`);o=!0}if(i!==void 0){if(typeof i!="string"||i!==It)throw new de(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${It}"`);o=!0}if(!o)return null;if(e.stream!==!0)throw new de("the voice profile is streaming-only \u2014 send stream: true");let a=r?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new de("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Cr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Cr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Nn(u,"sentence_flush",!0),includeReasoning:Nn(u,"include_reasoning",!1),metadata:Nn(u,"metadata",!1)}}var lt=class{constructor(e,t){this.config=e;this.sink=t}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let t=this.boundedCut();this.sink(this.buffer.slice(0,t)),this.buffer=this.buffer.slice(t)}(this.buffer.length>=e||this.config.sentenceFlush&&Bo(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let r=e-1;r>0;r--)if(Uo.test(this.buffer[r]))return r+1;let t=Math.max(1,e),s=this.buffer.charCodeAt(t-1);return s>=55296&&s<=56319?t-1:t}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function jn(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Jo(n){n.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),n.flushHeaders(),n.socket?.setNoDelay(!0)}function oe(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function V(n,e,t,s="invalid_request_error",r){oe(n,e,{error:r?{message:t,type:s,code:r}:{message:t,type:s}})}function Hn(n,e,t){let s=e.error,r=s?.type??"upstream_error",i=t?.operatorError??(d=>console.error(d)),o=xe(s),a=o??be(t?.inferenceId??null);o===null&&i(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let u=s?.code??null,l=r==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&n.setHeader("retry-after","30"),oe(n,l,{error:{message:a,type:r,code:u}})}function ke(n,e,t,s){oe(n,e,{type:"error",error:{type:t,message:s}})}function dt(n,e,t){if(e==="anthropic"){oe(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}oe(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var Wo=64*1024*1024,Et=class extends Error{};async function $r(n,e=Wo){let t=[],s=0;for await(let i of n){if(s+=i.length,s>e)throw new Et(`request body exceeds ${e} bytes`);t.push(i)}let r=Buffer.concat(t).toString("utf8");return r?JSON.parse(r):{}}function Je(n,e,t,s){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:s}]}}function Nr(n){let e=n?.usage;if(!e||typeof e!="object")return{kind:"absent"};let t=e,s=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,r=s(t.input_tokens),i=s(t.output_tokens),o=u=>u??0,a=s(t.total_tokens)??o(r)+o(i);if(o(r)>0||o(i)>0){let u={input_tokens:o(r),output_tokens:o(i),total_tokens:a};return r===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return r===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function tn(n){let e=Nr(n);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Fr(n){let e=tn(n);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Vo(n)},completion_tokens_details:{reasoning_tokens:0}}}function Vo(n){let e=n?.usage;if(!e||typeof e!="object")return 0;let t=e.input_tokens_details;if(!t||typeof t!="object")return 0;let s=t.cached_tokens;return typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?s:0}function zo(n,e){let t=Nr(e);t.kind==="absent"||t.kind==="partial"||(n.promptTokens=t.usage.input_tokens,n.completionTokens=t.usage.output_tokens)}function Ko(n){let e=n?.urun_timing;if(!e||typeof e!="object")return null;let t=e,s=u=>{let l=t[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},r=s("queue_ms"),i=s("prefill_ms"),o=s("decode_ms"),a=s("total_ms");return r===null||i===null||o===null||a===null?null:{queue_ms:r,prefill_ms:i,decode_ms:o,total_ms:a}}function Xo(n,e){let t=Ko(e);t&&(n.timing=t),n.outputSeconds=Ie(e)}function We(n,e){zo(n,e),Xo(n,e)}async function rn(n,e,t){if(typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let s=await e.catalogIdentity(t);if(s!==null){n.catalog={kind:"catalog",model_id:s.model_id,variant:s.variant};return}let r=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:r??t??null}}catch(s){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${s instanceof Error?s.message:String(s)}`}}}function qr(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let s of e)if(!(s.type!=="reasoning"||!Array.isArray(s.content)))for(let r of s.content)r.type==="reasoning_text"&&(t+=String(r.text??""));return t}function Yo(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var nn=class extends Error{};function Qo(n,e){return Array.isArray(e)?e.map(t=>{let s=t;if(s.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:s.text};if(s.type==="image_url"){let r=s.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new nn(`unsupported chat content part type "${String(s.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Zo(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let s of t.tool_calls){let r=s.function??{};e.push({type:"function_call",call_id:s.id,name:r.name,arguments:r.arguments})}continue}e.push({...t,content:Qo(t.role,t.content)})}return e}function Un(n){return Qe(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function ea(n,e,t,s,r,i,o){let a=_t(i.id),u=n.stream===!0;if(i.model=ue(n),i.stream=u,await rn(i,e,typeof n.model=="string"?n.model:void 0),u){let y;try{y=await vt({body:n,clients:e,store:t,stats:r,responseId:a,turn:i})}catch(h){if(h instanceof J){dt(s,"openai",h);return}if(h instanceof he){V(s,h.status,h.message);return}if(h instanceof _e||h instanceof ye){s.setHeader("retry-after","2"),V(s,503,h.message,"capacity_error");return}throw h}jn(s);for await(let h of y.events){if(h.type==="error"){i.streamError=!0;let v=h.error,L=xe(v),O=L??be(i.id);L===null&&o(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(h)}`),s.write(`event: error
27
27
  data: ${JSON.stringify({error:{message:O,type:v?.type??"upstream_error",code:v?.code??null}})}
28
28
 
29
29
  `),s.end();return}h.type==="response.completed"&&We(i,h.response),s.write(`event: ${String(h.type??"message")}
@@ -31,7 +31,7 @@ data: ${JSON.stringify(h)}
31
31
 
32
32
  `)}s.write(`data: [DONE]
33
33
 
34
- `),s.end();return}let l;try{l=tt(t,n)}catch(y){if(y instanceof he){V(s,y.status,y.message);return}throw y}n.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(n.input)));let d=n.store!==!1,c=ue(n);r.model(c);let p=Array.isArray(n.tools)&&n.tools.length>0,m;try{m=await Rn(e,n,l,!1,fe(i))}catch(y){if(y instanceof J){dt(s,"openai",y);return}if(y instanceof he){V(s,y.status,y.message);return}if(y instanceof _e||y instanceof ye){s.setHeader("retry-after","2"),V(s,503,y.message,"capacity_error");return}throw y}let f=[],b=null;for await(let y of r.track(m,c,i)){if(f.push(y),y.type==="error"){jn(s,y,{inferenceId:i.id,operatorError:o});return}y.type==="response.completed"&&(b=y.response)}if(b==null){V(s,502,"upstream produced no response.completed event","upstream_error");return}We(i,b);let k=et(f,b),_=je(p,Qe(b).length,k);if(_){V(s,502,Be(c,_),"upstream_error");return}d&&t.remember(a,l,xn(b,k),d),oe(s,200,{...b,id:a})}async function sa(n,e,t,s,r,i,o){let a=n.messages;if(!Array.isArray(a)){V(t,400,"chat/completions requires a messages array");return}let u;try{u=Cr(i,n)}catch(g){if(g instanceof de){V(t,g.status,g.message);return}throw g}let l=String(n.model??"urun"),d=Ss(r.id),c;try{c=ta(a)}catch(g){if(g instanceof tn){V(t,400,g.message);return}throw g}let p=ue(n);s.model(p),r.model=p,r.stream=n.stream===!0,await sn(r,e,typeof n.model=="string"?n.model:void 0);let m=Array.isArray(n.tools)&&n.tools.length>0,f;try{f=await e.createResponse({model:n.model,input:c,stream:!0,tools:Zo(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,top_p:n.top_p,stop:n.stop,max_output_tokens:n.max_completion_tokens??n.max_tokens,...n.reasoning_effort!==void 0?{reasoning_effort:n.reasoning_effort}:{},...n.chat_template_kwargs!==void 0?{chat_template_kwargs:n.chat_template_kwargs}:{},...n.response_format!==void 0?{response_format:n.response_format}:{}},fe(r))}catch(g){if(g instanceof J){dt(t,"openai",g);return}if(g instanceof _e||g instanceof ye){t.setHeader("retry-after","2"),V(t,503,g.message,"capacity_error");return}throw g}if(n.stream===!0){u?Vo(t):Bn(t);let g=[],w=new Ce,R="",M=u?new lt(u,j=>{t.write(`data: ${JSON.stringify(Je(d,l,{content:j},null))}
34
+ `),s.end();return}let l;try{l=tt(t,n)}catch(y){if(y instanceof he){V(s,y.status,y.message);return}throw y}n.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(n.input)));let d=n.store!==!1,c=ue(n);r.model(c);let p=Array.isArray(n.tools)&&n.tools.length>0,m;try{m=await An(e,n,l,!1,fe(i))}catch(y){if(y instanceof J){dt(s,"openai",y);return}if(y instanceof he){V(s,y.status,y.message);return}if(y instanceof _e||y instanceof ye){s.setHeader("retry-after","2"),V(s,503,y.message,"capacity_error");return}throw y}let f=[],b=null;for await(let y of r.track(m,c,i)){if(f.push(y),y.type==="error"){Hn(s,y,{inferenceId:i.id,operatorError:o});return}y.type==="response.completed"&&(b=y.response)}if(b==null){V(s,502,"upstream produced no response.completed event","upstream_error");return}We(i,b);let k=et(f,b),_=je(p,Qe(b).length,k);if(_){V(s,502,Be(c,_),"upstream_error");return}d&&t.remember(a,l,Rn(b,k),d),oe(s,200,{...b,id:a})}async function ta(n,e,t,s,r,i,o){let a=n.messages;if(!Array.isArray(a)){V(t,400,"chat/completions requires a messages array");return}let u;try{u=Lr(i,n)}catch(g){if(g instanceof de){V(t,g.status,g.message);return}throw g}let l=String(n.model??"urun"),d=xs(r.id),c;try{c=Zo(a)}catch(g){if(g instanceof nn){V(t,400,g.message);return}throw g}let p=ue(n);s.model(p),r.model=p,r.stream=n.stream===!0,await rn(r,e,typeof n.model=="string"?n.model:void 0);let m=Array.isArray(n.tools)&&n.tools.length>0,f;try{f=await e.createResponse({model:n.model,input:c,stream:!0,tools:Yo(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,top_p:n.top_p,stop:n.stop,max_output_tokens:n.max_completion_tokens??n.max_tokens,...n.reasoning_effort!==void 0?{reasoning_effort:n.reasoning_effort}:{},...n.chat_template_kwargs!==void 0?{chat_template_kwargs:n.chat_template_kwargs}:{},...n.response_format!==void 0?{response_format:n.response_format}:{}},fe(r))}catch(g){if(g instanceof J){dt(t,"openai",g);return}if(g instanceof _e||g instanceof ye){t.setHeader("retry-after","2"),V(t,503,g.message,"capacity_error");return}throw g}if(n.stream===!0){u?Jo(t):jn(t);let g=[],w=new Ce,R="",M=u?new lt(u,j=>{t.write(`data: ${JSON.stringify(Je(d,l,{content:j},null))}
35
35
 
36
36
  `)}):null,q=j=>{M?.flush(),t.write(j),t.end()};try{u?.metadata&&t.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
37
37
 
@@ -45,22 +45,22 @@ data: ${JSON.stringify(h)}
45
45
 
46
46
  `)}else if(T.type==="error"){r.streamError=!0;let P=T.error??{},F=xe(P),W=F??be(r.id);F===null&&o(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(T)}`),q(`data: ${JSON.stringify({error:{message:W,type:P.type??"upstream_error",code:P.code??null}})}
47
47
 
48
- `);return}}let j=qn(Ae(g)),$=je(m,w.size+j.length,R);if($){r.streamError=!0,q(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Be(p,$)}})}
48
+ `);return}}let j=Un(Ae(g)),$=je(m,w.size+j.length,R);if($){r.streamError=!0,q(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Be(p,$)}})}
49
49
 
50
50
  `);return}M?.flush(),w.size===0&&j.length>0&&t.write(`data: ${JSON.stringify(Je(d,l,{tool_calls:j},null))}
51
51
 
52
52
  `);let N=w.size>0||j.length>0;t.write(`data: ${JSON.stringify(Je(d,l,{},N?"tool_calls":"stop"))}
53
53
 
54
- `);let H=en(Ae(g));We(r,Ae(g)),H&&t.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:$r(Ae(g))})}
54
+ `);let H=tn(Ae(g));We(r,Ae(g)),H&&t.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:Fr(Ae(g))})}
55
55
 
56
56
  `),t.write(`data: [DONE]
57
57
 
58
- `),t.end();return}finally{M?.flush(),M?.dispose()}}let b="",k="",_=[],y=new Ce;for await(let g of s.track(f,p,r)){_.push(g),g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(b+=g.delta),g.type==="response.reasoning_text.delta"&&typeof g.delta=="string"&&(k+=g.delta);let w=Ze(g);if(w&&y.add(w),g.type==="error"){jn(t,g,{inferenceId:r.id,operatorError:o});return}}let h=Ae(_);We(r,h);let v=qn(h),L=v.length>0?v:qn({output:y.items()}),O=je(m,L.length,b);if(O){V(t,502,Be(p,O),"upstream_error");return}let I=L.map(({index:g,...w})=>w),S={role:"assistant",content:b||null},A=k||Nr(h);A&&(S.reasoning_content=A),I.length>0&&(S.tool_calls=I),oe(t,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:S,finish_reason:I.length>0?"tool_calls":"stop"}],usage:$r(h)})}var qr="sense-latest";async function ra(n,e,t,s,r,i){if(n===null||typeof n!="object"||Array.isArray(n)){V(t,400,"systemone requires a JSON object body");return}delete n.key;let o=typeof n.model=="string"&&n.model?n.model:qr,a=ue({model:o});if(r.model=a,r.stream=!1,n.state===void 0||n.state===null){V(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){V(t,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(n.media!==void 0&&!Array.isArray(n.media)){V(t,400,"systemone media, when present, must be an array");return}let l=await Ur(n,o,a,e,t,s,r,i);l!==null&&oe(t,200,l.answer)}async function Ur(n,e,t,s,r,i,o,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=u;let l=performance.now();i.model(t),await sn(o,s,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await s.createResponse({model:e,input:[{role:"user",content:JSON.stringify(n)}],stream:!0},fe(o))}catch(_){if(_ instanceof J)return dt(r,"openai",_),null;if(_ instanceof _e||_ instanceof ye)return r.setHeader("retry-after","2"),V(r,503,_.message,"capacity_error"),null;throw _}u.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let _ of i.track(d,t,o))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),p.push(_),_.type==="error")return jn(r,_,{inferenceId:o.id,operatorError:a}),null}catch(_){if(_ instanceof J)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),dt(r,"openai",_),null;if(_ instanceof _e||_ instanceof ye)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),r.setHeader("retry-after","2"),V(r,503,_.message,"capacity_error"),null;throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),_}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let f=Ae(p);if(f==null)return V(r,502,"upstream produced no response.completed event","upstream_error"),null;We(o,f);let b=et(p,f),k;try{k=JSON.parse(b)}catch{return V(r,502,"systemone answer was not valid JSON","upstream_error"),null}if(k===null||typeof k!="object"||Array.isArray(k))return V(r,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"timing"in k){let _=k.timing;if(typeof _=="object"&&_!==null&&!Array.isArray(_)&&"question_fwd_ms"in _&&"head_ms"in _){let y=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=y(_.question_fwd_ms),u.head_ms=y(_.head_ms)}}return{answer:k,completed:f}}async function ia(n,e,t,s,r,i){if(n===null||typeof n!="object"||Array.isArray(n)){V(t,400,"decisions requires a JSON object body");return}let o=typeof n.model=="string"&&n.model?n.model:qr,a=ue({model:o});r.model=a,r.stream=!1;let u;try{u=Ms(n,o)}catch(p){if(p instanceof D){V(t,400,p.message);return}throw p}let l=await Ur(u.systemone,o,a,e,t,s,r,i);if(l===null)return;let d;try{d=$s(u.specs,l.answer)}catch(p){if(p instanceof ae){V(t,502,p.message,"upstream_error");return}throw p}let c;try{c=Fs(l.completed.usage)}catch(p){if(p instanceof ae){V(t,502,p.message,"upstream_error");return}throw p}oe(t,200,{model:o,answers:d,...c===null?{}:{usage:c}})}function oa(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Tt=class extends Error{};function nn(n){return new Tt(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function aa(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 ua(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 Tt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function la(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw nn(typeof n);let e="";for(let t of n){let s=String(t.type??"");if(s!=="text")throw nn(`tool_result > ${s}`);e+=String(t.text??"")}return e}function da(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 nn(typeof t);let s=[],r="",i=()=>{r&&(s.push({role:e,content:r}),r="")};for(let o of t){let a=String(o.type??"");if(a==="text")r+=String(o.text??"");else if(a==="tool_use")i(),s.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.input??{})});else if(a==="tool_result")i(),s.push({type:"function_call_output",call_id:o.tool_use_id,output:la(o.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw nn(a)}}return i(),s}function Un(n){return Qe(n).map((e,t)=>{let s;try{s=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:s}})}async function ca(n,e,t,s,r,i){let o=n.messages;if(!Array.isArray(o)){ke(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){ke(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){ke(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"))){ke(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(n.model??"urun"),u=xs(r.id),l=[],d;try{n.system&&l.push({role:"system",content:oa(n.system)});for(let S of o)l.push(...da(S));d=ua(n.tool_choice)}catch(S){if(S instanceof Tt){ke(t,400,"invalid_request_error",S.message);return}throw S}let c=ue(n);s.model(c),r.model=c,r.stream=n.stream===!0,await sn(r,e,typeof n.model=="string"?n.model:void 0);let p=Array.isArray(n.tools)&&n.tools.length>0,m;try{m=await e.createResponse({model:n.model,input:l,stream:!0,tools:aa(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences},fe(r))}catch(S){if(S instanceof J){dt(t,"anthropic",S);return}if(S instanceof _e||S instanceof ye){t.setHeader("retry-after","2"),ke(t,503,"capacity_error",S.message);return}throw S}let f=(S,A)=>{t.destroyed||t.write(`event: ${S}
59
- data: ${JSON.stringify({type:S,...A})}
58
+ `),t.end();return}finally{M?.flush(),M?.dispose()}}let b="",k="",_=[],y=new Ce;for await(let g of s.track(f,p,r)){_.push(g),g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(b+=g.delta),g.type==="response.reasoning_text.delta"&&typeof g.delta=="string"&&(k+=g.delta);let w=Ze(g);if(w&&y.add(w),g.type==="error"){Hn(t,g,{inferenceId:r.id,operatorError:o});return}}let h=Ae(_);We(r,h);let v=Un(h),L=v.length>0?v:Un({output:y.items()}),O=je(m,L.length,b);if(O){V(t,502,Be(p,O),"upstream_error");return}let I=L.map(({index:g,...w})=>w),x={role:"assistant",content:b||null},A=k||qr(h);A&&(x.reasoning_content=A),I.length>0&&(x.tool_calls=I),oe(t,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:x,finish_reason:I.length>0?"tool_calls":"stop"}],usage:Fr(h)})}var Ur="sense-latest";async function na(n,e,t,s,r,i){if(n===null||typeof n!="object"||Array.isArray(n)){V(t,400,"systemone requires a JSON object body");return}delete n.key;let o=typeof n.model=="string"&&n.model?n.model:Ur,a=ue({model:o});if(r.model=a,r.stream=!1,n.state===void 0||n.state===null){V(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){V(t,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(n.media!==void 0&&!Array.isArray(n.media)){V(t,400,"systemone media, when present, must be an array");return}let l=await Br(n,o,a,e,t,s,r,i);l!==null&&oe(t,200,l.answer)}async function Br(n,e,t,s,r,i,o,a){let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=u;let l=performance.now();i.model(t),await rn(o,s,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await s.createResponse({model:e,input:[{role:"user",content:JSON.stringify(n)}],stream:!0},fe(o))}catch(_){if(_ instanceof J)return dt(r,"openai",_),null;if(_ instanceof _e||_ instanceof ye)return r.setHeader("retry-after","2"),V(r,503,_.message,"capacity_error"),null;throw _}u.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let _ of i.track(d,t,o))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),p.push(_),_.type==="error")return Hn(r,_,{inferenceId:o.id,operatorError:a}),null}catch(_){if(_ instanceof J)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),dt(r,"openai",_),null;if(_ instanceof _e||_ instanceof ye)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),r.setHeader("retry-after","2"),V(r,503,_.message,"capacity_error"),null;throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),_}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let f=Ae(p);if(f==null)return V(r,502,"upstream produced no response.completed event","upstream_error"),null;We(o,f);let b=et(p,f),k;try{k=JSON.parse(b)}catch{return V(r,502,"systemone answer was not valid JSON","upstream_error"),null}if(k===null||typeof k!="object"||Array.isArray(k))return V(r,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"timing"in k){let _=k.timing;if(typeof _=="object"&&_!==null&&!Array.isArray(_)&&"question_fwd_ms"in _&&"head_ms"in _){let y=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=y(_.question_fwd_ms),u.head_ms=y(_.head_ms)}}return{answer:k,completed:f}}async function sa(n,e,t,s,r,i){if(n===null||typeof n!="object"||Array.isArray(n)){V(t,400,"decisions requires a JSON object body");return}let o=typeof n.model=="string"&&n.model?n.model:Ur,a=ue({model:o});r.model=a,r.stream=!1;let u;try{u=Cs(n,o)}catch(p){if(p instanceof D){V(t,400,p.message);return}throw p}let l=await Br(u.systemone,o,a,e,t,s,r,i);if(l===null)return;let d;try{d=Fs(u.specs,l.answer)}catch(p){if(p instanceof ae){V(t,502,p.message,"upstream_error");return}throw p}let c;try{c=Ds(l.completed.usage)}catch(p){if(p instanceof ae){V(t,502,p.message,"upstream_error");return}throw p}oe(t,200,{model:o,answers:d,...c===null?{}:{usage:c}})}function ra(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Tt=class extends Error{};function sn(n){return new Tt(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function ia(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 oa(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 Tt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function aa(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw sn(typeof n);let e="";for(let t of n){let s=String(t.type??"");if(s!=="text")throw sn(`tool_result > ${s}`);e+=String(t.text??"")}return e}function ua(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 sn(typeof t);let s=[],r="",i=()=>{r&&(s.push({role:e,content:r}),r="")};for(let o of t){let a=String(o.type??"");if(a==="text")r+=String(o.text??"");else if(a==="tool_use")i(),s.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.input??{})});else if(a==="tool_result")i(),s.push({type:"function_call_output",call_id:o.tool_use_id,output:aa(o.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw sn(a)}}return i(),s}function Bn(n){return Qe(n).map((e,t)=>{let s;try{s=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:s}})}async function la(n,e,t,s,r,i){let o=n.messages;if(!Array.isArray(o)){ke(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){ke(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){ke(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(x=>typeof x!="string"))){ke(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(n.model??"urun"),u=Rs(r.id),l=[],d;try{n.system&&l.push({role:"system",content:ra(n.system)});for(let x of o)l.push(...ua(x));d=oa(n.tool_choice)}catch(x){if(x instanceof Tt){ke(t,400,"invalid_request_error",x.message);return}throw x}let c=ue(n);s.model(c),r.model=c,r.stream=n.stream===!0,await rn(r,e,typeof n.model=="string"?n.model:void 0);let p=Array.isArray(n.tools)&&n.tools.length>0,m;try{m=await e.createResponse({model:n.model,input:l,stream:!0,tools:ia(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences},fe(r))}catch(x){if(x instanceof J){dt(t,"anthropic",x);return}if(x instanceof _e||x instanceof ye){t.setHeader("retry-after","2"),ke(t,503,"capacity_error",x.message);return}throw x}let f=(x,A)=>{t.destroyed||t.write(`event: ${x}
59
+ data: ${JSON.stringify({type:x,...A})}
60
60
 
61
- `)};if(n.stream===!0){let S=s.track(m,c,r);Bn(t),f("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,g="",w=0,R="none",M=()=>R,q=-1,j=-1,$=new Ce,N=[],H=()=>{R!=="none"&&(R="none",f("content_block_stop",{index:q}))},T=(K,te)=>{H(),R=K,q=w++,f("content_block_start",{index:q,content_block:te})};for await(let K of S){if(t.destroyed)break;N.push(K);let te=Ze(K);if(K.type==="response.reasoning_text.delta"&&typeof K.delta=="string")M()!=="thinking"&&T("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:K.delta}});else if(K.type==="response.output_text.delta"&&typeof K.delta=="string")M()!=="text"&&T("text",{type:"text",text:""}),A+=1,g+=K.delta,f("content_block_delta",{index:q,delta:{type:"text_delta",text:K.delta}});else if(te){let{call:ge}=$.add(te);(M()!=="tool"||te.tool_index!==j)&&(j=te.tool_index,T("tool",{type:"tool_use",id:ge.id??`call_${te.tool_index}`,name:ge.name??"",input:{}})),te.delta&&f("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:te.delta}})}else if(K.type==="error"){r.streamError=!0;let ge=K.error,$e=xe(ge);$e===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(K)}`),f("error",{error:{type:"api_error",message:$e??be(r.id)}}),t.end();return}}if(t.destroyed)return;let z=Ae(N),P=Qe(z),F=je(p,$.size+P.length,g);if(F){r.streamError=!0,f("error",{error:{type:"api_error",message:Be(c,F)}}),t.end();return}H();let W=[];if($.size===0)try{W=Un(z)}catch(K){r.streamError=!0;let te=ce(K,{inferenceId:r.id});te.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(K instanceof Error?K.message:K)}`),f("error",{error:{type:"api_error",message:te.message}}),t.end();return}w===0&&W.length===0&&(T("text",{type:"text",text:""}),H()),W.forEach(K=>{let te=w++;f("content_block_start",{index:te,content_block:{...K,input:{}}}),f("content_block_delta",{index:te,delta:{type:"input_json_delta",partial_json:JSON.stringify(K.input??{})}}),f("content_block_stop",{index:te})});let Se=$.size>0||W.length>0,Ve=en(z);We(r,z),f("message_delta",{delta:{stop_reason:Se?"tool_use":"end_turn"},usage:Ve?{input_tokens:Ve.input_tokens,output_tokens:Ve.output_tokens}:{output_tokens:A}}),f("message_stop",{}),t.end();return}let b="",k="",_=[],y=new Ce;for await(let S of s.track(m,c,r)){_.push(S),S.type==="response.output_text.delta"&&typeof S.delta=="string"&&(b+=S.delta),S.type==="response.reasoning_text.delta"&&typeof S.delta=="string"&&(k+=S.delta);let A=Ze(S);if(A&&y.add(A),S.type==="error"){let g=S.error,w=g?.type==="invalid_request_error",R=xe(g);R===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(S)}`),ke(t,w?400:502,w?"invalid_request_error":"api_error",R??be(r.id));return}if(t.destroyed)break}if(t.destroyed)return;let h=Ae(_);We(r,h);let v;try{v=Un(h),v.length===0&&y.size>0&&(v=Un({output:y.items()}))}catch(S){let A=ce(S,{inferenceId:r.id});A.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(S instanceof Error?S.message:S)}`),ke(t,502,"api_error",A.message);return}let L=je(p,v.length,b);if(L){ke(t,502,"api_error",Be(c,L));return}let O=[],I=k||Nr(h);I&&O.push({type:"thinking",thinking:I}),(b||v.length===0)&&O.push({type:"text",text:b}),O.push(...v),oe(t,200,{id:u,type:"message",role:"assistant",content:O,model:a,stop_reason:v.length>0?"tool_use":"end_turn",usage:en(h)??{input_tokens:0,output_tokens:0}})}function pa(n){Pe(process.stdout,n)}function ma(n){let{clients:e,apiKey:t,identity:s,statusOf:r}=n,i=typeof e=="function"?e:()=>e,o=n.requestLog??pa,a=n.operatorLog??(d=>console.error(d)),u=n.observe,l=new qe;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),f=(h,v,L,O,I)=>m?ke(c,h,O,v):V(c,h,v,L,I),b=Sn(p.pathname),k=p.pathname.startsWith("/partners/"),_=b||k?{id:yt(),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;_&&(c.setHeader(bs,_.id),c.once("close",()=>{let h=Rs({turn:_,method:d.method??"",path:p.pathname,res:c});o(As(h)),u?.(h),Pr({record:h,ledger:n.ledger??null,req:d})}));let y=()=>ks(p.pathname,_);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){oe(c,200,s?{identity:s,...l.snapshot()}:l.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===_r?"canonical":p.pathname===$n?"huggingface":null;if(h){if(d.method!=="POST"){f(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let I=n.usage;if(!I){f(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=I.authorize(d),A;try{A=await Lr(d,wr)}catch(R){if(R instanceof Et){f(413,R.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=R=>I.lookup(S,R),w;try{if(h==="canonical"){let R=vr(A),M=await g(R);Qt(M,R),w={requests:M}}else w=await kr(A,g)}catch(R){if(R instanceof Le){f(R.status,R.message,"invalid_request_error","invalid_request_error");return}throw R}oe(c,200,w);return}if(d.method==="GET"&&p.pathname===ct){let I=await i(d);if(_&&(_.org=I.tenant??null),!I.openRouterModels){f(501,`GET ${ct} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}oe(c,200,await I.openRouterModels());return}if(p.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${$n} and GET ${ct}`,"invalid_request_error","not_found_error");return}let v=await i(d);if(_&&(_.org=v.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ct}),c.end();return}oe(c,200,await v.listModels());return}if(d.method==="GET"&&p.pathname===qs){if(!v.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listImageModels());return}if(Ns(p.pathname)){if(!v.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let I={clients:v,imageModels:v.supportsImages,stats:l,turn:y(),operatorLog:a};p.pathname===Wt?await Ks(d,c,I):await zs(d,c,I);return}if(d.method==="GET"&&p.pathname===dr){if(!v.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listSpeechToTextModels());return}if(lr(p.pathname)){if(!v.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Xt}`,"not_implemented","not_implemented_error");return}let I={clients:v,transcriptionModels:v.supportsTranscription,stats:l,turn:y(),operatorLog:a};await mr(d,c,I);return}if(rr(p.pathname)){if(!v.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${xt}`,"not_implemented","not_implemented_error");return}let I={clients:v,speechModels:v.supportsSpeech,stats:l,turn:y(),operatorLog:a};await ur(d,c,I);return}if(d.method!=="POST"){f(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let L;try{L=await Lr(d)}catch(I){if(I instanceof Et){f(413,I.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let O=Buffer.byteLength(JSON.stringify(L));if(p.pathname==="/v1/responses"){l.request("responses",O,O),await na(L,v,wt(v),c,l,y(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",O,O),await sa(L,v,c,l,y(),d.headers[Nn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",O,O),await ra(L,v,c,l,y(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",O,O),await ia(L,v,c,l,y(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",O,O),await ca(L,v,c,l,y(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",O,O),ke(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}f(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let v=String(h instanceof Error?h.message:h);if(!c.headersSent){let I=r?.(h)??null;if(I){I.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${I.operatorDetail}`),f(I.status,v,I.openaiType,I.anthropicType,I.code);return}if(h instanceof Jo){let A=Bt(h.code);if(A){let g=h.retryAfterSeconds??(A.status===429?30:void 0);g!==void 0&&c.setHeader("Retry-After",String(g)),f(A.status,gt(A,h.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof Wo){let A=jt(h);if(A){let g=A.status===429?30:void 0;g!==void 0&&c.setHeader("Retry-After",String(g)),f(A.status,gt(A,h.status.sessionId?`session ${h.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof se){f(502,v,"upstream_error","api_error");return}if(h instanceof we){h.retryable&&c.setHeader("Retry-After","1");let A=ce(h,{inferenceId:_?.id??null});A.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}`:me(h)}`),f(502,A.message,"upstream_error","api_error",h.code);return}if(h instanceof Me){c.setHeader("Retry-After",String(h.retryAfterSeconds)),f(h.status,v,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let S=ce(h,{inferenceId:_?.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}`:me(h)}`),f(500,S.message,"proxy_error","api_error","proxy_error");return}_&&(_.streamError=!0);let L=h instanceof we?h.code:null,O=ce(h,{inferenceId:_?.id??null});O.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}`:me(h)}`),c.destroyed||(m?c.write(`event: error
61
+ `)};if(n.stream===!0){let x=s.track(m,c,r);jn(t),f("message_start",{message:{id:u,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,g="",w=0,R="none",M=()=>R,q=-1,j=-1,$=new Ce,N=[],H=()=>{R!=="none"&&(R="none",f("content_block_stop",{index:q}))},T=(K,te)=>{H(),R=K,q=w++,f("content_block_start",{index:q,content_block:te})};for await(let K of x){if(t.destroyed)break;N.push(K);let te=Ze(K);if(K.type==="response.reasoning_text.delta"&&typeof K.delta=="string")M()!=="thinking"&&T("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:K.delta}});else if(K.type==="response.output_text.delta"&&typeof K.delta=="string")M()!=="text"&&T("text",{type:"text",text:""}),A+=1,g+=K.delta,f("content_block_delta",{index:q,delta:{type:"text_delta",text:K.delta}});else if(te){let{call:ge}=$.add(te);(M()!=="tool"||te.tool_index!==j)&&(j=te.tool_index,T("tool",{type:"tool_use",id:ge.id??`call_${te.tool_index}`,name:ge.name??"",input:{}})),te.delta&&f("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:te.delta}})}else if(K.type==="error"){r.streamError=!0;let ge=K.error,$e=xe(ge);$e===null&&i(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(K)}`),f("error",{error:{type:"api_error",message:$e??be(r.id)}}),t.end();return}}if(t.destroyed)return;let z=Ae(N),P=Qe(z),F=je(p,$.size+P.length,g);if(F){r.streamError=!0,f("error",{error:{type:"api_error",message:Be(c,F)}}),t.end();return}H();let W=[];if($.size===0)try{W=Bn(z)}catch(K){r.streamError=!0;let te=ce(K,{inferenceId:r.id});te.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(K instanceof Error?K.message:K)}`),f("error",{error:{type:"api_error",message:te.message}}),t.end();return}w===0&&W.length===0&&(T("text",{type:"text",text:""}),H()),W.forEach(K=>{let te=w++;f("content_block_start",{index:te,content_block:{...K,input:{}}}),f("content_block_delta",{index:te,delta:{type:"input_json_delta",partial_json:JSON.stringify(K.input??{})}}),f("content_block_stop",{index:te})});let Se=$.size>0||W.length>0,Ve=tn(z);We(r,z),f("message_delta",{delta:{stop_reason:Se?"tool_use":"end_turn"},usage:Ve?{input_tokens:Ve.input_tokens,output_tokens:Ve.output_tokens}:{output_tokens:A}}),f("message_stop",{}),t.end();return}let b="",k="",_=[],y=new Ce;for await(let x of s.track(m,c,r)){_.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(b+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(k+=x.delta);let A=Ze(x);if(A&&y.add(A),x.type==="error"){let g=x.error,w=g?.type==="invalid_request_error",R=xe(g);R===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(x)}`),ke(t,w?400:502,w?"invalid_request_error":"api_error",R??be(r.id));return}if(t.destroyed)break}if(t.destroyed)return;let h=Ae(_);We(r,h);let v;try{v=Bn(h),v.length===0&&y.size>0&&(v=Bn({output:y.items()}))}catch(x){let A=ce(x,{inferenceId:r.id});A.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(x instanceof Error?x.message:x)}`),ke(t,502,"api_error",A.message);return}let L=je(p,v.length,b);if(L){ke(t,502,"api_error",Be(c,L));return}let O=[],I=k||qr(h);I&&O.push({type:"thinking",thinking:I}),(b||v.length===0)&&O.push({type:"text",text:b}),O.push(...v),oe(t,200,{id:u,type:"message",role:"assistant",content:O,model:a,stop_reason:v.length>0?"tool_use":"end_turn",usage:tn(h)??{input_tokens:0,output_tokens:0}})}function da(n){Pe(process.stdout,n)}function ca(n){let{clients:e,apiKey:t,identity:s,statusOf:r}=n,i=typeof e=="function"?e:()=>e,o=n.requestLog??da,a=n.operatorLog??(d=>console.error(d)),u=n.observe,l=new qe;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),f=(h,v,L,O,I)=>m?ke(c,h,O,v):V(c,h,v,L,I),b=xn(p.pathname),k=p.pathname.startsWith("/partners/"),_=b||k?{id:yt(),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;_&&(c.setHeader(ks,_.id),c.once("close",()=>{let h=As({turn:_,method:d.method??"",path:p.pathname,res:c});o(Is(h)),u?.(h),Mr({record:h,ledger:n.ledger??null,req:d})}));let y=()=>Ss(p.pathname,_);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){oe(c,200,s?{identity:s,...l.snapshot()}:l.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===wr?"canonical":p.pathname===Fn?"huggingface":null;if(h){if(d.method!=="POST"){f(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let I=n.usage;if(!I){f(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 x=I.authorize(d),A;try{A=await $r(d,vr)}catch(R){if(R instanceof Et){f(413,R.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let g=R=>I.lookup(x,R),w;try{if(h==="canonical"){let R=br(A),M=await g(R);Zt(M,R),w={requests:M}}else w=await Sr(A,g)}catch(R){if(R instanceof Le){f(R.status,R.message,"invalid_request_error","invalid_request_error");return}throw R}oe(c,200,w);return}if(d.method==="GET"&&p.pathname===ct){let I=await i(d);if(_&&(_.org=I.tenant??null),!I.openRouterModels){f(501,`GET ${ct} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}oe(c,200,await I.openRouterModels());return}if(p.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Fn} and GET ${ct}`,"invalid_request_error","not_found_error");return}let v=await i(d);if(_&&(_.org=v.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ct}),c.end();return}oe(c,200,await v.listModels());return}if(d.method==="GET"&&p.pathname===Us){if(!v.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listImageModels());return}if(qs(p.pathname)){if(!v.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let I={clients:v,imageModels:v.supportsImages,stats:l,turn:y(),operatorLog:a};p.pathname===Vt?await Xs(d,c,I):await Ks(d,c,I);return}if(d.method==="GET"&&p.pathname===cr){if(!v.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}oe(c,200,await v.listSpeechToTextModels());return}if(dr(p.pathname)){if(!v.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Yt}`,"not_implemented","not_implemented_error");return}let I={clients:v,transcriptionModels:v.supportsTranscription,stats:l,turn:y(),operatorLog:a};await fr(d,c,I);return}if(ir(p.pathname)){if(!v.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${xt}`,"not_implemented","not_implemented_error");return}let I={clients:v,speechModels:v.supportsSpeech,stats:l,turn:y(),operatorLog:a};await lr(d,c,I);return}if(d.method!=="POST"){f(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let L;try{L=await $r(d)}catch(I){if(I instanceof Et){f(413,I.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let O=Buffer.byteLength(JSON.stringify(L));if(p.pathname==="/v1/responses"){l.request("responses",O,O),await ea(L,v,wt(v),c,l,y(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",O,O),await ta(L,v,c,l,y(),d.headers[qn],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",O,O),await na(L,v,c,l,y(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",O,O),await sa(L,v,c,l,y(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",O,O),await la(L,v,c,l,y(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",O,O),ke(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}f(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let v=String(h instanceof Error?h.message:h);if(!c.headersSent){let I=r?.(h)??null;if(I){I.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${I.operatorDetail}`),f(I.status,v,I.openaiType,I.anthropicType,I.code);return}if(h instanceof Ho){let A=jt(h.code);if(A){let g=h.retryAfterSeconds??(A.status===429?30:void 0);g!==void 0&&c.setHeader("Retry-After",String(g)),f(A.status,gt(A,h.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof Go){let A=Ht(h);if(A){let g=A.status===429?30:void 0;g!==void 0&&c.setHeader("Retry-After",String(g)),f(A.status,gt(A,h.status.sessionId?`session ${h.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(h instanceof se){f(502,v,"upstream_error","api_error");return}if(h instanceof we){h.retryable&&c.setHeader("Retry-After","1");let A=ce(h,{inferenceId:_?.id??null});A.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}`:me(h)}`),f(502,A.message,"upstream_error","api_error",h.code);return}if(h instanceof Me){c.setHeader("Retry-After",String(h.retryAfterSeconds)),f(h.status,v,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let x=ce(h,{inferenceId:_?.id??null});x.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:me(h)}`),f(500,x.message,"proxy_error","api_error","proxy_error");return}_&&(_.streamError=!0);let L=h instanceof we?h.code:null,O=ce(h,{inferenceId:_?.id??null});O.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}`:me(h)}`),c.destroyed||(m?c.write(`event: error
62
62
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:O.message}})}
63
63
 
64
64
  `):c.write(`data: ${JSON.stringify({error:{message:O.message,type:"upstream_error",code:L}})}
65
65
 
66
- `)),c.end()})}}function Xl(n){let{clients:e,apiKey:t}=n,s=Go(ma(n)),r=Ps(s,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),i=kn(s,{resolver:Fr(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),o=s.close.bind(s);return s.close=(a=>(r.close(),i(),o(a))),cs(s,{clients:e,apiKey:t}),s}C();var Te=(n,e)=>Object.assign(new Error(e),{status:n}),ga='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Gn=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Hn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof J?Te(404,t.message):t}};async function Br(n,e,t,s,r){if(r!==void 0&&r!=="transcription")throw Te(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ga}`);if(r==="transcription")throw Te(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Te(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Te(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(m){throw m instanceof J?Te(404,m.message):m}if(!p)throw Te(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(m){throw m instanceof J?Te(404,m.message):m}if(p!=="stt")throw Te(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Hn(n,t.stt),o=await Hn(n,e),a=await Hn(n,t.tts),u=await n.openAudioOn(i,s),l=await n.openAudioOn(a,s),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,ya({clients:n,chatHandle:o,ttsHandle:a,chatModel:e,companions:t},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(i,p)}catch(m){throw m instanceof Q?Gn("stt",t.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function jr(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var Ot=class extends Error{};async function*ya(n,e,t,s){let{clients:r,chatHandle:i,ttsHandle:o,chatModel:a,companions:u}=n;if(t?.aborted){s?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,f=null,b=null,k=[],_=null,y=new Promise((w,R)=>{t&&t.addEventListener("abort",()=>R(new Ot),{once:!0})}),h=()=>m||t?.aborted===!0,v=async w=>{if(h())return;let R;try{R=await r.createResponseOn(o,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:w}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(q){throw q instanceof Q?Gn("tts",u.tts,q):q}let M=R[Symbol.asyncIterator]();b=M;try{for(;;){let q=M.next(),j;try{j=await Promise.race([q,y])}catch(N){if(q.catch(()=>{}),N instanceof Ot)return;throw N}if(j.done)return;let $=j.value;if($.type==="error"){let N=$.error&&typeof $.error.message=="string"?$.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${N}`)}if($.type==="response.completed")return}}finally{b===M&&(b=null)}},L=async()=>{for(;k.length>0&&!h();){let w=k.shift();await v(w)}},O=w=>{if(w===""||h()||(k.push(w),_!==null))return;let R=L();_=R,R.then(()=>{_===R&&(_=null)},M=>{_===R&&(_=null),f??=M})},I=()=>{m=!0,k.length=0;let w=b;if(b=null,w){let R=w.return?.();R&&R.catch(()=>{})}},S=async()=>{for(;k.length>0||_!==null;){let w=_;if(w===null){await v(k.shift());continue}await w}},A=p?new lt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},w=>O(w)):null,g=null;try{let w;try{w=await r.createResponseOn(i,d)}catch(M){throw M instanceof Q?Gn("chat",a,M):M}let R=w[Symbol.asyncIterator]();try{for(;;){let M=R.next(),q;try{q=await Promise.race([M,y])}catch(N){if(M.catch(()=>{}),N instanceof Ot)break;throw N}if(q.done)break;let j=q.value;if(h())return;let $=j;if($.type==="error"){yield j;return}if($.type==="response.output_text.delta"&&typeof $.delta=="string"){yield j,A?.push($.delta);continue}if($.type==="response.function_call_arguments.delta"){A?.flush(),yield j;continue}if($.type==="response.completed"){g=j.response;continue}}}finally{Promise.resolve(R.return?.()).catch(()=>{})}A?.flush(),A?.dispose(),p&&await S(),g!==null&&(yield{type:"response.completed",response:g})}finally{A?.dispose(),I();try{if(f instanceof Q)throw f}finally{s?.()}}}var pe=(n,e)=>Object.assign(new Error(e),{status:n});function wa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function va(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}function md(n){let e=new URL(n.url??"/","http://localhost").searchParams.get("session"),t=n.headers?.["x-urun-session"],s=(e??(typeof t=="string"?t:t?.[0]))?.trim();if(!(s===void 0||s==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(s))throw Object.assign(new Error(`invalid realtime session id "${s.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return s}}var ba='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ka(n,e,t,s,r){if(!n.supportsAudio)throw pe(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await n.supportsAudio(e)}catch(m){throw m instanceof J?pe(404,m.message):m}if(!i){let m=null;if(n.realtimeCompanionsFor)try{m=await n.realtimeCompanionsFor(e)}catch(f){throw f instanceof J?pe(404,f.message):f}if(m!==null)return await Br(n,e,m,t,s);throw pe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw pe(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(m){throw m instanceof J?pe(404,m.message):m}if(o&&!n.openTurnsOn)throw pe(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let m;try{m=await n.transcriptStreamFor(e)}catch(f){throw f instanceof J?pe(404,f.message):f}if(m!=="stt")throw pe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(s!==void 0&&s!=="transcription")throw pe(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ba}`);if(s==="transcription"&&!o)throw pe(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=n.dedicatedSessionHandle?await n.dedicatedSessionHandle(e):await n.sessionHandle(e)}catch(m){throw m instanceof ye?pe(503,m.message):m}let u=n.realtimeBillingIdentityFor?await n.realtimeBillingIdentityFor(e):null,l=`conn_${_a()}`,c={audio:await n.openAudioOn(a,t,l,r).catch(m=>{throw n.releaseSessionHandle?.(a),m})},p={clients:{createResponse:async m=>await n.createResponseOn(a,m,l)},voice:i,audioSession:c};return n.openVideoOn&&(p.video=()=>n.openVideoOn(a,t)),o&&(p.turns=m=>n.openTurnsOn(a,m)),s==="transcription"&&(p.intent="transcription"),n.releaseSessionHandle&&(p.release=()=>n.releaseSessionHandle(a)),(n.touchSessionPresence||n.detachSessionPresence)&&(p.presence={touch:m=>n.touchSessionPresence?.(a,m),detach:m=>n.detachSessionPresence?.(a,m)}),n.endDedicatedSession&&(p.endSession=()=>n.endDedicatedSession(a)),n.onSessionEnd&&(p.onSessionEnd=m=>n.onSessionEnd(a,m)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Fr(n,e,t){let s=jr(n,t);return{resolve:async(r,i,o)=>{if(e!==void 0){let a=r.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw pe(401,"invalid local proxy api key")}return ka(s,wa(r),i,va(r),o)}}}export{Ct as a,cs as b,Ia as c,yt as d,ps as e,zr as f,La as g,$a as h,Pi as i,Ps as j,ht as k,bn as l,kn as m,jr as n,wa as o,va as p,md as q,ka as r,Fr as s,_r as t,se as u,ul as v,$n as w,hl as x,gl as y,yl as z,_l as A,wl as B,Pr as C,qr as D,ma as E,Xl as F};
66
+ `)),c.end()})}}function zl(n){let{clients:e,apiKey:t}=n,s=jo(ca(n)),r=Ms(s,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),i=Sn(s,{resolver:Dr(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),o=s.close.bind(s);return s.close=(a=>(r.close(),i(),o(a))),ps(s,{clients:e,apiKey:t}),s}C();var Te=(n,e)=>Object.assign(new Error(e),{status:n}),fa='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Jn=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Gn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof J?Te(404,t.message):t}};async function jr(n,e,t,s,r){if(r!==void 0&&r!=="transcription")throw Te(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${fa}`);if(r==="transcription")throw Te(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Te(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Te(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(m){throw m instanceof J?Te(404,m.message):m}if(!p)throw Te(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(m){throw m instanceof J?Te(404,m.message):m}if(p!=="stt")throw Te(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await Gn(n,t.stt),o=await Gn(n,e),a=await Gn(n,t.tts),u=await n.openAudioOn(i,s),l=await n.openAudioOn(a,s),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,ha({clients:n,chatHandle:o,ttsHandle:a,chatModel:e,companions:t},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(i,p)}catch(m){throw m instanceof Q?Jn("stt",t.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Hr(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var Ot=class extends Error{};async function*ha(n,e,t,s){let{clients:r,chatHandle:i,ttsHandle:o,chatModel:a,companions:u}=n;if(t?.aborted){s?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,f=null,b=null,k=[],_=null,y=new Promise((w,R)=>{t&&t.addEventListener("abort",()=>R(new Ot),{once:!0})}),h=()=>m||t?.aborted===!0,v=async w=>{if(h())return;let R;try{R=await r.createResponseOn(o,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:w}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(q){throw q instanceof Q?Jn("tts",u.tts,q):q}let M=R[Symbol.asyncIterator]();b=M;try{for(;;){let q=M.next(),j;try{j=await Promise.race([q,y])}catch(N){if(q.catch(()=>{}),N instanceof Ot)return;throw N}if(j.done)return;let $=j.value;if($.type==="error"){let N=$.error&&typeof $.error.message=="string"?$.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${N}`)}if($.type==="response.completed")return}}finally{b===M&&(b=null)}},L=async()=>{for(;k.length>0&&!h();){let w=k.shift();await v(w)}},O=w=>{if(w===""||h()||(k.push(w),_!==null))return;let R=L();_=R,R.then(()=>{_===R&&(_=null)},M=>{_===R&&(_=null),f??=M})},I=()=>{m=!0,k.length=0;let w=b;if(b=null,w){let R=w.return?.();R&&R.catch(()=>{})}},x=async()=>{for(;k.length>0||_!==null;){let w=_;if(w===null){await v(k.shift());continue}await w}},A=p?new lt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},w=>O(w)):null,g=null;try{let w;try{w=await r.createResponseOn(i,d)}catch(M){throw M instanceof Q?Jn("chat",a,M):M}let R=w[Symbol.asyncIterator]();try{for(;;){let M=R.next(),q;try{q=await Promise.race([M,y])}catch(N){if(M.catch(()=>{}),N instanceof Ot)break;throw N}if(q.done)break;let j=q.value;if(h())return;let $=j;if($.type==="error"){yield j;return}if($.type==="response.output_text.delta"&&typeof $.delta=="string"){yield j,A?.push($.delta);continue}if($.type==="response.function_call_arguments.delta"){A?.flush(),yield j;continue}if($.type==="response.completed"){g=j.response;continue}}}finally{Promise.resolve(R.return?.()).catch(()=>{})}A?.flush(),A?.dispose(),p&&await x(),g!==null&&(yield{type:"response.completed",response:g})}finally{A?.dispose(),I();try{if(f instanceof Q)throw f}finally{s?.()}}}var pe=(n,e)=>Object.assign(new Error(e),{status:n});function ya(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function _a(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}function cd(n){let e=new URL(n.url??"/","http://localhost").searchParams.get("session"),t=n.headers?.["x-urun-session"],s=(e??(typeof t=="string"?t:t?.[0]))?.trim();if(!(s===void 0||s==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(s))throw Object.assign(new Error(`invalid realtime session id "${s.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return s}}var wa='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function va(n,e,t,s,r){if(!n.supportsAudio)throw pe(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await n.supportsAudio(e)}catch(m){throw m instanceof J?pe(404,m.message):m}if(!i){let m=null;if(n.realtimeCompanionsFor)try{m=await n.realtimeCompanionsFor(e)}catch(f){throw f instanceof J?pe(404,f.message):f}if(m!==null)return await jr(n,e,m,t,s);throw pe(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw pe(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(m){throw m instanceof J?pe(404,m.message):m}if(o&&!n.openTurnsOn)throw pe(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let m;try{m=await n.transcriptStreamFor(e)}catch(f){throw f instanceof J?pe(404,f.message):f}if(m!=="stt")throw pe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(s!==void 0&&s!=="transcription")throw pe(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${wa}`);if(s==="transcription"&&!o)throw pe(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=n.dedicatedSessionHandle?await n.dedicatedSessionHandle(e):await n.sessionHandle(e)}catch(m){throw m instanceof ye?pe(503,m.message):m}let u=n.realtimeBillingIdentityFor?await n.realtimeBillingIdentityFor(e):null,l=`conn_${ga()}`,c={audio:await n.openAudioOn(a,t,l,r).catch(m=>{throw n.releaseSessionHandle?.(a),m})},p={clients:{createResponse:async m=>await n.createResponseOn(a,m,l)},voice:i,audioSession:c};return n.openVideoOn&&(p.video=()=>n.openVideoOn(a,t)),o&&(p.turns=m=>n.openTurnsOn(a,m)),s==="transcription"&&(p.intent="transcription"),n.releaseSessionHandle&&(p.release=()=>n.releaseSessionHandle(a)),(n.touchSessionPresence||n.detachSessionPresence)&&(p.presence={touch:m=>n.touchSessionPresence?.(a,m),detach:m=>n.detachSessionPresence?.(a,m)}),n.endDedicatedSession&&(p.endSession=()=>n.endDedicatedSession(a)),n.onSessionEnd&&(p.onSessionEnd=m=>n.onSessionEnd(a,m)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Dr(n,e,t){let s=Hr(n,t);return{resolve:async(r,i,o)=>{if(e!==void 0){let a=r.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw pe(401,"invalid local proxy api key")}return va(s,ya(r),i,_a(r),o)}}}export{Lt as a,ps as b,Ra as c,yt as d,ms as e,Kr as f,Ma as g,Ca as h,Pi as i,Ms as j,ht as k,kn as l,Sn as m,Hr as n,ya as o,_a as p,cd as q,va as r,Dr as s,wr as t,se as u,ol as v,Fn as w,ml as x,fl as y,hl as z,gl as A,yl as B,Mr as C,Ur as D,ca as E,zl as F};