@urun-sh/openai 0.6.46 → 0.6.48

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,66 +0,0 @@
1
- import{a as Gn,c as Wn,d as Fe,e as Et,f as re,g as Vn,h as zn,i as Kn,j as Xn,k as Yn,l as Qn,m as Zn,n as er,r as tr,t as nr,u as rr,v as sr,w as ir,x as or}from"./chunk-X5BLQXHK.js";import{a as rn,e as sn}from"./chunk-64VO62LW.js";import{a as Te,b as ye,v as Oe}from"./chunk-2AFSBZLN.js";import{a as Hn,e as ut,f as Jn,i as J,j as Z,k as on,l as an}from"./chunk-CUO2JOW4.js";import{c as $}from"./chunk-YSFSRI3D.js";$();import{randomUUID as Ds}from"crypto";import{WebSocketServer as qs}from"ws";var Us=256,Tt=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Us;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Bs="local",lt=n=>n.slice(0,120),Ot=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Wn,lt(e.message));return}if(e instanceof Z){this.ws.close(Et,lt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close(Fe,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Vn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=er(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=nr(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:tr);return}this.transcript.push(...rr(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=Yn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Et);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Et);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Xn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[zn]=Kn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(ir(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=Ds();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Qn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Zn(e.timeLeftMs)),this.ws.close(Fe,lt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=sr(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}=or(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ne=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function js(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new Ne(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new Ne(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new Ne(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ar(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new qs({noServer:!0}),s=new Tt;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Gn&&(a.on("error",()=>{}),(async()=>{let d=js(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ne(401,"invalid local proxy api key");c={clients:e.clients,scope:Bs}}r.handleUpgrade(o,a,u,p=>{new Ot(p,c,s)})})().catch(d=>{let c=502;(d instanceof Ne||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
- Connection: close\r
3
- \r
4
- ${m}\r
5
- `),a.destroy())}))});let i=null;return()=>(i??=(async()=>{for(let o of r.clients)o.close(1001,"server closing");await new Promise((o,a)=>r.close(u=>u===void 0?o():a(u)))})(),i)}function va(n,e,t=new Tt){new Ot(n,e,t)}$();var Pe=class extends Error{code;status;retryAfterSeconds;constructor(e,t,r,s){super(s),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},dt=class extends Pe{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},un=class extends Pe{constructor(e,t=!1){super("acquire_timeout",429,30,t?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},ur=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let t={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(t.min)||t.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(t.max)||t.max<t.min||t.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(t.inFlightCap)||t.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(t.warmWaitMs!==void 0&&(!Number.isInteger(t.warmWaitMs)||t.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=t.min,this.opts.max=t.max,this.opts.inFlightCap=t.inFlightCap,this.opts.warmWaitMs=t.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,t=0){let r=`decision:${this.opts.replicaId}:${e}`;return t===0?r:`${r}:${t}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let t=this.now(),r=this.slots.filter(s=>s.state==="paused"&&!s.opening&&(e||!s.dead)&&(!s.dead||t>=s.nextDialAt)).sort((s,i)=>s.slot.index-i.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let t=this.slots[e];t.dead&&!t.opening&&t.inFlight===0&&(t.backoffTimer&&(clearTimeout(t.backoffTimer),t.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(t)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${t instanceof Error?t.message:String(t)}`):(e.state="paused",this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new dt;this.lastDemandAt=this.now();let t=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let s=this.tryLease();if(s)return this.pump(),s;if(this.draining)throw new dt;let i=this.slots.some(c=>c.state==="queued"),o=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!i&&(o||a)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let u=r+t-Date.now();if(u<=0)throw new un(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 dt}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let t=this.tryLease();if(t)return t;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(i=>i.state==="attached"),s=this.slots.some(i=>i.dead&&!i.opening&&this.now()>=i.nextDialAt);(r||s)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let i=s.session;if(typeof i!="object"||i===null||!("whenLive"in i))return!1;let o=i.whenLive;if(typeof o!="function")return!1;let a=r.entry;try{return await o.call(i,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let i of this.slots)i.state!=="attached"||i.inFlight>=this.opts.inFlightCap||(!e||i.inFlight<e.inFlight)&&(e=i);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1;let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.opening=null,this.rotate(t,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,t){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,t),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),t=this.slots.filter(i=>i.state==="attached"&&i.inFlight===0&&i.idleSince!==null&&e-i.idleSince>=this.idleGraceMs).sort((i,o)=>(i.idleSince??0)-(o.idleSince??0)||o.slot.index-i.slot.index),r=this.slots.filter(i=>i.state==="attached").length,s=Math.max(0,Math.min(t.length,r-this.opts.min));for(let i of t.slice(0,s))this.endSlot(i);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(t=>t.state==="attached"||t.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(s=>s.state==="attached").length,t=this.slots.filter(s=>s.state==="queued").length,r=this.slots.filter(s=>s.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:r,inFlight:this.slots.reduce((s,i)=>s+i.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,t)=>e+t.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let t of this.waiters.splice(0))t.settled||(t.settled=!0,t.resolve());if(this.slots.reduce((t,r)=>t+r.inFlight,0)>0){if(!this.drainComplete){let r,s=new Promise(i=>{r=i});this.drainComplete={promise:s,resolve:r}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let s of this.waiters.splice(0))s.settled||(s.settled=!0,s.resolve());let e=this.slots.map(s=>s.entry).filter(s=>s!==null);for(let s of this.slots)clearTimeout(s.backoffTimer),s.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(s=>this.opts.closeSlot(s)))).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};$();import{SessionFailedError as Ys}from"@urun-sh/core";$();$();import{SessionFailedError as lr}from"@urun-sh/core";var we=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},Hs=33e4;function Ia(n,e=Hs){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,i=new Promise((l,d)=>{s=d}),o=setTimeout(()=>s(new Pt),e),a;try{a=await Promise.race([r.next(),i])}catch(l){throw l instanceof Z||l instanceof lr&&l.kind==="transport-failed"?l:l instanceof Pt?(await r.return?.(void 0),new we("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new we("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(o)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new we("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Pt=class extends Error{constructor(){super("stream idle timeout")}};function Ea(n){return n instanceof we?!1:n instanceof Z?!0:n instanceof lr?n.kind==="transport-failed":!1}var Js=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ve(n){return!Js.some(e=>e.test(n))}function be(n){return n==null||n===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${n} when reporting it`}function de(n,e){if(n instanceof Z)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=dr(n);return t||{message:be(e?.inferenceId??null),redacted:!0}}function dr(n){return n instanceof Jn?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:n instanceof Hn?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:n instanceof J?{message:n.message,redacted:!1}:n instanceof Te?{message:n.message,redacted:!1}:n instanceof Pe?{message:n.message,redacted:!1}:n instanceof we?ve(n.message)?{message:n.message,redacted:!1}:null:n instanceof _e?{message:n.message,redacted:!1}:n instanceof ye?{message:n.message,redacted:!1}:null}function Ve(n,e,t){let r=t??(o=>console.error(o)),s=dr(e);if(s)return s.redacted&&r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed: ${s.message}`;let i=e instanceof Error?e.message:"";return e instanceof Error&&i.length>0&&ve(i)?`the ${n} upstream failed: ${i}`:(r(`[caller-message-boundary] ${n} upstream failure detail withheld from the caller: ${pe(e)}`),`the ${n} upstream failed while serving this request`)}function Se(n){let e=n?.message;return typeof e=="string"&&e.length>0&&ve(e)?e:null}function pe(n){if(n instanceof Error)return n.message;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}$();import{randomUUID as Gs}from"crypto";function R(n){return`${n}_${Gs().replace(/-/g,"").slice(0,24)}`}var Mt=4*1024*1024,ln=8*1024*1024,dn=512,Ct=20*1024*1024;function z(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 H(n){return{type:"error",event_id:R("event"),error:n}}function cn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var E=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},Ws={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},Vs={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},zs={format:!0,voice:!0,speed:!0};function Ks(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.values(n).every(e=>e==null):!1}function ze(n,e){if(!Array.isArray(n)||n.length===0)throw new E(`${e} must be a non-empty array`,e,"invalid_modalities");let t=[];for(let r of n){if(r!=="text"&&r!=="audio")throw new E(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");t.includes(r)||t.push(r)}return t}function cr(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 Xs=10;function pn(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:Xs})}function ct(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new E("session must be an object","session","invalid_request");let s=n,i=Object.keys(s).filter(a=>!(a in Ws));if(i.length>0)throw new E(`session field(s) not supported by this backend: ${i.join(", ")}`,i[0],"unsupported_field");if(s.modalities!==void 0&&s.output_modalities!==void 0){let a=ze(s.modalities,"modalities"),u=ze(s.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==u.slice().sort().join(","))throw new E("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let o={...e,outputModalities:[...e.outputModalities]};for(let[a,u]of Object.entries(s))switch(a){case"type":{if(u!=="realtime"&&u!=="transcription")throw new E(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new E(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(u==="transcription"&&!t.turns)throw new E('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");o.type=u;break}case"object":case"id":case"expires_at":{if(u===null)break;let l=a==="object"?"realtime.session":a==="id"?r:null;if(u!==l)throw new E(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(u)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let l=ze(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(!Ks(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=pn(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 Vs))throw new E(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&cr(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=ct({input_audio_transcription:d.transcription},o,t,r);o.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=ct({turn_detection:d.turn_detection},o,t,r);o.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new E("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new E("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in zs))throw new E(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&cr(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 Lt(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 mn(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:R("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let r=t.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new E('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new E("message item content must be an array","item.content","invalid_request");let s=[];for(let i of t.content){let o=i;if(!o||typeof o!="object")throw new E("content part must be an object","item.content","invalid_request");if(o.type==="input_text"||r==="assistant"&&o.type==="output_text"){if(typeof o.text!="string")throw new E(`${String(o.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){if(!e)throw new E("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof o.audio!="string")throw new E("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof o.transcript=="string"?{transcript:o.transcript}:{}});continue}if(o.type==="input_image"){if(r!=="user")throw new E("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof o.image_url=="string"?o.image_url:o.image_url?.url;if(typeof a!="string"||a.length===0)throw new E("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new E("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let u=typeof o.detail=="string"?o.detail:void 0;s.push({type:"input_image",imageUrl:a,...u!==void 0?{detail:u}:{}});continue}throw new E(`content part type ${String(o.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof t.id=="string"?t.id:R("item"),type:"message",role:r,content:s}}throw new E(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function $t(n){let e=[],t=!1;for(let r of n){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let s=[];for(let i of r.content??[]){if(i.type==="input_text"||i.type==="output_text"){s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){let o=i.transcript;if(typeof o=="string"&&o.trim().length>0){s.push({type:"input_text",text:o});continue}t=!0;continue}}e.push({role:r.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Qs=1001,Zs=1011,ei=15e3;var Ft=class extends Error{},Nt=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},fn=n=>n.slice(0,120),ti=/^[A-Za-z0-9+/=]*$/,ni=2;function ri(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>ni)return!1;return!0}var pt=class{id=R("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=cn();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(t=>console.error(t)),this.turnStallMs=e.turnStallMs??ei,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===on&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:R("event"),session:Lt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let t of e.replayFrames??[])this.onMessage(t)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let r=await t.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof Z&&this.binding.composite===!0)this.failSessionGone(r);else{let s=this.callerLine(r,"turn/transcript lane read"),i=this.pendingTranscriptItemId;i!==null?this.failPendingTranscription(i,s):this.send(H(Re("turn_lane_fault",`the backend turn/transcript lane failed: ${s}`)))}}finally{this.turnLaneIterator===t&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let t=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,t),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:e,content_index:0,transcript:t});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,t){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:R("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:t}}),this.emitItemDone(e)}writeItemTranscript(e,t){let r=this.items.find(i=>i.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:t},...(r.content??[]).slice(1)])}emitItemDone(e){let t=this.items.findIndex(r=>r.id===e);t<0||this.send({type:"conversation.item.done",event_id:R("event"),previous_item_id:t>0?this.items[t-1].id:null,item:this.itemToProtocol(this.items[t])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,t.length>0&&(this.turnTranscript.text+=t),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&t.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:R("event"),item_id:r??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:R("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let s=this.turnTranscript.text.trim(),i=s.length>0?s:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=i,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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=R("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:R("event"),previous_item_id:a,item_id:o}),this.send({type:"conversation.item.added",event_id:R("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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:R("event"),item_id:o,content_index:0,transcript:i}),this.emitItemDone(o),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let t;try{t=e.toString()}catch{this.fail(z("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>Mt){this.fail(z("frame_too_large",`frame exceeds the ${Mt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(z("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(z("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(s){let i=s;if(i&&typeof i=="object"&&i.name==="SessionUpdateError"){this.send(H({type:"invalid_request_error",code:i.code??"invalid_value",message:i.message,param:i.param??null}));return}if(s instanceof Ft){this.fail(Re(null,this.callerLine(s,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
6
- ${s?.stack??pe(s)}`),this.send(H(Re(null,this.callerLine(s,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let t=ct(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&t.turnDetection!==null){this.send(H(z("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:R("event"),session:Lt(this.config,this.sessionId)});return}case"conversation.item.create":{let t=mn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,s=t.content??[];(s.length===0||s.some(i=>i.type!=="input_image"))&&this.pushItem(t),this.forwardImageFrames(t),this.send({type:"conversation.item.added",event_id:R("event"),previous_item_id:r,item:this.itemToProtocol(t)}),this.emitItemDone(t.id);return}case"conversation.item.delete":{let t=this.items.findIndex(r=>r.id===e.item_id);if(t<0){this.send(H(z("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:R("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(r=>r.id===e.item_id);if(!t){this.send(H(z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:R("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(r=>r.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(H(z("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:R("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(H(z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ti.test(e.audio)){this.send(H(z("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,t);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,t),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Ct){this.send(H(z("buffer_full",`uncommitted input audio exceeds the ${Ct}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:t}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(H(z("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.added",event_id:R("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(t!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:t}),this.emitItemDone(r);else if(this.turnTranscript.final){let i=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,i),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:i}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(H(z("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(H(z("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(H(z("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,fn("session ended by client"))}catch{}});return}default:this.send(H(z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(H(z("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 Ft("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(H({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let t=e[Symbol.asyncIterator](),r=this.turnCancelled,s=!0;try{for(;;){let i;if(s||this.turnStallMs<=0)s=!1,i=r?await Promise.race([t.next(),r]):await t.next();else{let o,a=new Promise((l,d)=>{o=setTimeout(()=>d(new Nt),this.turnStallMs)});i=await(r?Promise.race([t.next(),a,r]):Promise.race([t.next(),a])).finally(()=>clearTimeout(o))}if(i.done===!0)return;yield i.value}}finally{Promise.resolve(t.return?.()).catch(()=>{})}}async upstreamStream(e,t){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let i=e.response??e;return r.sendResponseCreate({type:"response.create",response:i},e.input??[],t)}let s=this.binding.clients;if(s&&typeof s.createResponse=="function"){let{response:i,input:o,...a}=e;return await s.createResponse({...a,input:o})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(H(z("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{},r=t.modalities!==void 0?ze(t.modalities,"response.modalities"):void 0,s=t.output_modalities!==void 0?ze(t.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&s!==void 0&&r.slice().sort().join(",")!==s.slice().sort().join(","))throw new E("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((s??r)?.includes("audio")&&!this.ensureVoice())return;if(t.input!==void 0){this.send(H(z("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;let o=()=>{},a=new Promise(y=>{o=()=>y({done:!0,value:void 0})});this.turnCancelled=a,this.wakeTurnCancelled=()=>o(),this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let u=R("req"),l=`resp_${u}`;this.activeResponseId=l,this.activeRequestId=u;let d=this.binding.composite===!0,c=d?0:this.items.length,p=d?null:$t(this.items),m=pn(typeof t.instructions=="string"?t.instructions:this.config.instructions),f=typeof t.temperature=="number"?t.temperature:this.config.temperature,v=t.max_output_tokens??this.config.maxOutputTokens,S=v==="inf"||v===void 0?void 0:v,w=t.tools!==void 0?t.tools:this.config.tools,_=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,h={stream:!0,...this.config.model?{model:this.config.model}:{},...m!==void 0?{instructions:m}:{},...f!==void 0?{temperature:f}:{},...S!==void 0?{max_output_tokens:S}:{},...w!==void 0?{tools:w}:{},..._!==void 0?{tool_choice:_}:{}};if(!(d&&!this.ensureVoice())){for(let{audio:y,captureWallMs:C}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(y,C);this.inFlight=(async()=>{let y=[],C=I=>{this.responseFlushed?this.send(I):y.push(I)},T=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:R("event"),response:this.responseObject(l,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(l,"in_progress")});for(let I of y)this.send(I);y.length=0,this.responseFlushed=!0}},b={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},A=null;try{if(d){if(this.pendingTranscriptItemId!==null&&(await new Promise(P=>{this.pendingTranscriptSettled=P}),this.cancelled||this.closed))return;c=this.items.length,p=$t(this.items)}let{input:I,sawAudioOnlyItem:g}=p??{input:[],sawAudioOnlyItem:!1},k={...h,input:I,...d?this.compositeTurnAsk(t):{}};g&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(k,u)}catch(P){this.upstreamTurnFault(P,l);return}T();try{for await(let P of this.stallBoundedTurn(x)){if(this.cancelled)break;let O=P;if(O.type==="error"){let q=this.upstreamErrorBody(O);b.contentFlowed?this.send(H(q)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(l,q)});return}if(O.type==="response.output_text.delta"&&typeof O.delta=="string"){T(),b.contentFlowed=!0,b.messageOpen||(this.beginMessageItem(l,b.nextOutputIndex++),b.messageOpen=!0),this.config.outputModalities.includes("text")&&C({type:"response.output_text.delta",event_id:R("event"),item_id:`${l}_msg_0`,response_id:l,output_index:0,content_index:0,delta:O.delta}),this.turnOutputIsAudio()&&(b.transcriptDelta=!0,C({type:"response.output_audio_transcript.delta",event_id:R("event"),item_id:`${l}_msg_0`,response_id:l,output_index:0,content_index:0,delta:O.delta})),b.messageText+=O.delta;continue}if(O.type==="response.function_call_arguments.delta"){T(),b.contentFlowed=!0;let q=typeof O.delta=="string"?O.delta:"",M=typeof O.call_id=="string"&&O.call_id.length>0?O.call_id:`${l}_fc_${b.nextOutputIndex}`,L=b.tools.get(M);if(!L){let ee=typeof O.name=="string"&&O.name.length>0?O.name:void 0;L={outputIndex:b.nextOutputIndex++,name:ee,args:""},b.tools.set(M,L);let j={id:M,object:"realtime.item",type:"function_call",call_id:M,name:ee??"",arguments:"",status:"in_progress"};C({type:"response.output_item.added",event_id:R("event"),response_id:l,output_index:L.outputIndex,item:j}),this.emitAssistantItemAdded(j)}typeof O.name=="string"&&O.name.length>0&&(L.name=O.name),L.args+=q,C({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:M,response_id:l,output_index:L.outputIndex,call_id:M,name:L.name??"",delta:q});continue}if(O.type==="response.completed"){A=O.response??null;continue}}}catch(P){if(P instanceof Nt)this.operatorLog(`[realtime] turn ${l} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(P,l);return}}if(this.cancelled)return;this.closeOpenItems(l,b,c),T(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(l,c,A)})}finally{this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){if(ri(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(H({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:R("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let t=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:R("event"),previous_item_id:t,item:e})}beginMessageItem(e,t){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let s={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:t,item:s}),this.emitAssistantItemAdded(s)}this.send({type:"response.content_part.added",event_id:R("event"),item_id:r,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:R("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,r){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,i=this.messageItemOpenForAudio,o=this.config.outputModalities.includes("text"),a=t.messageText;i?(this.send({type:"response.output_audio_transcript.done",event_id:R("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:R("event"),item_id:s,response_id:e,output_index:0,content_index:0})):t.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:R("event"),item_id:s,response_id:e,output_index:0,content_index:0,transcript:a}),t.messageText.length>0&&o&&this.send({type:"response.output_text.done",event_id:R("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:R("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:i?{type:"output_audio",transcript:a}:{type:"output_text",text:t.messageText}});let u=[];i&&u.push({type:"output_audio",transcript:a}),t.messageText.length>0&&u.push({type:"output_text",text:t.messageText});let l={id:s,type:"message",role:"assistant",content:u};this.pushItem(l),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[s,i]of t.tools){let o=i.args.length>0?i.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:R("event"),item_id:s,response_id:e,output_index:i.outputIndex,call_id:s,name:i.name??"",arguments:o});let a={id:s,type:"function_call",callId:s,name:i.name,arguments:o};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:i.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,r){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,r){let s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,i=[];for(let o=t;o<this.items.length;o++)i.push(this.itemToProtocol(this.items[o]));return this.responseObject(e,"completed",{output:i,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let t=e.error,r=Se(t);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let s=r??be(null);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:s}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Re(an,"the organization is out of credits \u2014 top up to continue"),an))}failSessionGone(e){if(e instanceof Z&&e.reason===on){this.failInsufficientCredits();return}let t=e instanceof Error&&ve(e.message)?e.message:null;t===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${pe(e)}`);let r=this.binding.composite===!0?t===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${t}`:t===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`;this.fail(Re("session_gone",r),"session_gone")}upstreamTurnFault(e,t){if(e instanceof Z){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ys&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Re(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(H(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(t,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(H(z("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.wakeTurnCancelled?.();let t=this.activeRequestId,r=this.binding.session;t!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(t),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let s=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,s?.();let i=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:R("event"),response:this.responseObject(i,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>dn&&this.items.shift()}forwardImageFrames(e){for(let t of e.content??[]){if(t.type!=="input_image")continue;let r=t.imageUrl.indexOf(","),s=r>=0?Buffer.from(t.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(s.byteLength===0){this.send(H(z("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(s.byteLength>sn){this.send(H(z("frame_too_large",`input_image frame is ${s.byteLength} bytes \u2014 over the ${sn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(H(z("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(i=>{throw this.videoLane=null,i}),this.videoLane.then(i=>i.sendInputFrame(new Uint8Array(s))).catch(i=>this.send(H(Re(null,i instanceof Error?i.message:String(i)))))}}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:s.type==="input_image"?{type:"input_image",image_url:s.imageUrl,...s.detail?{detail:s.detail}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>ln){this.ws.close(Qs,fn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,t){let r=de(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${t} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${pe(e)}`),r.message}fail(e,t){this.send(H(e)),this.ws.close(Zs,fn(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let t=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,t?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let s=r.return?.();s&&s.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(s=>pr(this.id,`binding release failed: ${s instanceof Error?s.message:String(s)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),pr(this.id,e)}},hn=[];function pr(n,e){hn.push({id:n,reason:e}),hn.length>256&&hn.shift()}$();import{SessionFailedError as mr}from"@urun-sh/core";$();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as si}from"@urun-sh/core";var ii={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},oi={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 mt(n,e){let t=oi[n.code];return e?`${t} (${e})`:t}function Dt(n){if(n==null)return null;let e=ii[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 qt(n){if(n.kind==="create-failed")return Dt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=si;return Dt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocket as fr,WebSocketServer as ai}from"ws";var yn="/v1/realtime",hr="urun.admission",gr=n=>n.slice(0,120);function ui(n,e,t){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
7
- Connection: close\r
8
- Content-Type: text/plain\r
9
- \r
10
- ${gr(t)}\r
11
- `),n.destroy()}function li(n){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...n})}
12
- `}function di(n){Oe(process.stdout,n)}function ci(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function gn(n){return n.audioSession?.audio.sessionId??void 0}function _n(n,e){let t=new ai({noServer:!0}),r=new Set;return n.on("upgrade",(s,i,o)=>{if(new URL(s.url??"/","http://localhost").pathname!==yn)return;r.add(i),i.on("close",()=>{r.delete(i)});let u=R("rtup"),l=ci(s),d=g=>{(e.log??di)(li(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"),v=()=>m("client socket closed (half-close)"),S=g=>m(`client socket error: ${g.message}`);i.once("close",f),i.once("end",v),i.once("error",S);let w=()=>{i.removeListener("close",f),i.removeListener("end",v),i.removeListener("error",S)},_=g=>{d({stage:"close",conn:u,model:l,...g})},h=null,y=!1,C=null,T=g=>JSON.stringify({type:hr,event_id:R("event"),...g}),b=g=>{if(h!==null){h.readyState===fr.OPEN&&h.send(T(g));return}y||(y=!0,t.handleUpgrade(s,i,o,k=>{h=k,C=[],k.on("message",x=>{C?.push(String(x))}),d({stage:"waiting",conn:u,model:l,status:g.status}),k.send(T(g))}))},A=g=>{let k=g,x=k.session!=null&&typeof k.session.sendResponseCreate=="function",P=k.clients!=null&&typeof k.clients.createResponse=="function";if(!x&&!P)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((O,q)=>{let M=(L,ee)=>{try{let j=Date.now();new pt({ws:L,binding:g,operatorLog:e.operatorLog,...ee.length>0?{replayFrames:ee}:{},onClosed:(te,F)=>{_({while:"live",reason:F.reason});try{e.onSessionEnded?.({req:s,binding:g,connected_ms:Math.max(0,Date.now()-j),reason:F.reason})}catch(B){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${B instanceof Error?B.message:String(B)}
13
- `)}}}),d({stage:"admit",conn:u,model:l,...gn(g)===void 0?{}:{session:gn(g)}}),O()}catch(j){q(j)}};if(h!==null){let L=C??[];C=null,M(h,L);return}t.handleUpgrade(s,i,o,L=>M(L,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(s,c.signal,b).then(async g=>{if(c.signal.aborted){w();let k=gn(g);try{await g.release?.()}catch(x){_({while:"queued",...k===void 0?{}:{session:k},reason:p??"client socket closed",release_failed:x instanceof Error?x.message:String(x)});return}_({while:"queued",...k===void 0?{}:{session:k},reason:p??"client socket closed",released:!0}),i.destroy();return}w(),await A(g)}).catch(g=>{let k=g instanceof mr?qt(g):null,x=null;if(g!==null&&typeof g=="object"&&"status"in g){let M=g.status;typeof M=="number"&&(x=M)}let P=x??k?.status??502,O=g instanceof Error?g.message:String(g),q=x!==null?O:k!==null?mt(k,g instanceof mr&&g.status.sessionId?`session ${g.status.sessionId}`:void 0):de(g).message;if(_({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:O,status:P}}),h!==null&&!c.signal.aborted){let M=JSON.stringify({type:hr,event_id:R("event"),status:P<500?"rejected":"failed",reason:q});h.readyState===fr.OPEN&&h.send(M),h.close(1011,gr(q));return}i.destroyed||ui(i,P,q)}).finally(()=>{r.delete(i)})}),async()=>{let s=Date.now()+5e3;for(;r.size>0&&Date.now()<s;)await new Promise(i=>setTimeout(i,25));await new Promise(i=>t.close(()=>i()))}}$();$();import{randomUUID as ca}from"crypto";$();import{createServer as No}from"http";$();import{WebSocketServer as xi,WebSocket as _t}from"ws";$();$();import{randomUUID as pi}from"crypto";var yr="Inference-Id";function ft(){return pi()}function wn(n){return n==="/v1"||n.startsWith("/v1/")}function _r(n,e){if(!wn(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 ht(n){return`resp_${n}`}function wr(n){return`chatcmpl-${n}`}function vr(n){return`msg_${n}`}function me(n){return e=>{n.sessionId=e.sessionId,n.catalog=e.identity}}function br(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 kr(n){return`${JSON.stringify(n)}
14
- `}var mi=256,fi=128;function ae(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,fi)}var De=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=r}modelEntry(e){let t=this.models[e];if(t)return t;let r=Object.keys(this.models).length>=mi?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t,r){let s=this,i=performance.now(),o=null,a=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(o===null&&(o=performance.now(),s.ttftMs.push(o-i),s.ttftMs.length>512&&s.ttftMs.shift(),r!==void 0&&(r.ttftMs=o-r.startedAt)),a+=1,s.tokensOut+=1,s.charsOut+=l.delta.length,t!==void 0&&(s.modelEntry(t).tokens_out+=1)),yield l;let u=(performance.now()-(o??i))/1e3;a>0&&u>0&&(s.tokRates.push(a/u),s.tokRates.length>512&&s.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((r,s)=>r-s);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,r)=>t+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},hi=256;function gi(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 qe=class extends Error{},Ke=class{conversations=new Map;thread(e,t){let r=gi(t);if(e==null)return r;let s=this.conversations.get(String(e));if(!s)throw new qe(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...r]}remember(e,t,r,s=!0){this.conversations.set(e,[...t,...r]);for(let i of this.conversations.keys()){if(this.conversations.size<=hi)break;this.conversations.delete(i)}}forget(e){this.conversations.delete(e)}},Sr=new WeakMap;function gt(n){let e=Sr.get(n);return e||(e=new Ke,Sr.set(n,e)),e}function Xe(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function xe(n){return n.find(e=>e.type==="response.completed")?.response??null}function Ye(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 Me=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),r=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},yi=["<tool_call>","<function="];function _i(n){return yi.find(e=>n.includes(e))}function Ue(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 Be(n,e,t){if(!(!n||e>0))return _i(t)}function Qe(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ae(n){let e=n?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function wi(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s=r;s.type==="message"?t.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return t}function vn(n,e){let t=wi(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var fe=class extends Error{constructor(t,r,s=400,i){super(t);this.code=r;this.status=s;this.param=i}code;status;param};function Ze(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof qe?new fe(t.message,"previous_response_not_found",400,"previous_response_id"):new fe(String(t instanceof Error?t.message:t),"invalid_input")}}function xr(n){let e=n.text;if(e!==null&&typeof e=="object"){let t=e.format;if(t!==void 0)return t}}async function bn(n,e,t,r,s){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new fe("instructions must be a string","invalid_instructions");let i=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...i!==void 0?{instructions:i}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...xr(e)!==void 0?{response_format:xr(e)}:{}},s)}async function yt(n){let{body:e,clients:t,store:r,stats:s}=n,i=Ze(r,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(i))-Buffer.byteLength(JSON.stringify(e.input)));let o=n.responseId,a=n.remember??e.store!==!1,u=e.store!==!1,l=ae(e);s.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=n.turn,p=await bn(t,e,i,!0,c?me(c):void 0);return{responseId:o,events:Si({events:p,conversation:i,responseId:o,modelKey:l,requestHadTools:d,remember:a,persist:u,store:r,stats:s,turn:n.turn})}}function vi(n,e){let t=[...n].sort((u,l)=>u.output_index-l.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],s=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),i=t.filter(u=>u.type==="message").length===s.length,o=0;return[...t.map(u=>u.type==="message"&&i?ki(s[o++],u):u),...bi(r,t)]}function bi(n,e){let t=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),s=l=>String(l.call_id??l.id??""),i=e.filter(l=>l.type==="function_call"),o=n.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,a=i.length===o,u=new Set(i.map(s));return n.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!t:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!u.has(s(d)):!0})}function ki(n,e){let t=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(n.content)?n.content:[];if(r.filter(t).length!==1)return e;let i=(Array.isArray(e.content)?e.content:[]).find(t);if(i===void 0)return e;let o={...n};return o.id=e.id,n.role===void 0&&(o.role=e.role),n.status===void 0&&(o.status=e.status),o.content=r.map(a=>t(a)?{...a,text:i.text}:a),o}async function*Si(n){let{events:e,conversation:t,responseId:r,modelKey:s,requestHadTools:i,remember:o,persist:a,store:u,stats:l}=n,d=[],c=F=>F.response&&typeof F.response=="object"?{...F,response:{...F.response,id:r}}:F,p=`item_${r.slice(5)}`,m=!1,f=!1,v=0;function*S(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let w=[],_=(F,B)=>{w.push({output_index:F,item:B})},h=!1,y=0,C="",T=0,b="";function*A(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:C,output_index:y,content_index:0,text:b};let F={id:C,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:F},_(y,F),b=""}let I=!1,g=0,k="",x=0,P="",O="";function*q(F){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:k,output_index:g,content_index:0,text:P},yield{type:"response.content_part.done",item_id:k,output_index:g,content_index:0,part:{type:"output_text",text:P}};let B={id:k,type:"message",role:"assistant",status:F,content:[{type:"output_text",text:P}]};yield{type:"response.output_item.done",output_index:g,item:B},_(g,B),P=""}let M=new Me,L=null,ee=-1;function*j(F){if(!L)return;let B=L;L=null,yield{type:"response.function_call_arguments.done",item_id:B.fcId,output_index:B.outputIndex,arguments:B.args};let W={id:B.fcId,type:"function_call",call_id:B.callId??B.fcId,name:B.name??"",arguments:B.args,status:F};yield{type:"response.output_item.done",output_index:B.outputIndex,item:W},_(B.outputIndex,W)}let te=!1;for await(let F of l.track(e,s,n.turn)){d.push(F);let B=String(F.type??"");if(B==="response.created"||B==="response.in_progress"){m=!0,yield c(F);continue}if(B==="response.output_item.added"){f=!0,yield c(F);continue}if(B==="response.reasoning_text.delta"&&!f){yield*S(),h||(h=!0,y=v++,T+=1,C=T===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${T}`,yield{type:"response.output_item.added",output_index:y,item:{id:C,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(F.delta??""),yield{type:"response.reasoning_text.delta",item_id:C,output_index:y,content_index:0,delta:F.delta};continue}if(B==="response.output_text.delta"&&!f){yield*S(),yield*A(),I||(I=!0,g=v++,x+=1,k=x===1?p:`${p}_${x}`,yield{type:"response.output_item.added",output_index:g,item:{id:k,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:k,output_index:g,content_index:0,part:{type:"output_text",text:""}}),P+=String(F.delta??""),O+=String(F.delta??""),yield{type:B,item_id:k,output_index:g,content_index:0,delta:F.delta};continue}let W=f?null:Ye(F);if(W){if(yield*S(),yield*A(),yield*q("completed"),M.add(W),W.tool_index!==ee){yield*j("completed"),ee=W.tool_index;let Le=v++;L={fcId:`fc_${r.slice(5)}_${W.tool_index}`,outputIndex:Le,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:Le,item:{id:L.fcId,type:"function_call",call_id:L.callId??L.fcId,name:L.name??"",arguments:"",status:"in_progress"}}}L&&(W.call_id&&(L.callId=W.call_id),W.name&&(L.name=W.name),L.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:L.fcId,output_index:L.outputIndex,delta:W.delta});continue}if(B==="response.completed"&&!f){let Le=Xe(F.response),We=Be(i,M.size+Le.length,O);if(We){te=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ue(s,We)}};break}if(yield*A(),yield*q("completed"),yield*j("completed"),M.size===0)for(let Q of Le){let ge=v++,$e=Q.id??Q.call_id??`fc_${ge}`,nn=Q.arguments??"",Bn={id:$e,type:"function_call",call_id:Q.call_id??$e,name:Q.name??""};yield{type:"response.output_item.added",output_index:ge,item:{...Bn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:$e,output_index:ge,delta:nn},yield{type:"response.function_call_arguments.done",item_id:$e,output_index:ge,arguments:nn};let jn={...Bn,arguments:nn,status:"completed"};yield{type:"response.output_item.done",output_index:ge,item:jn},_(ge,jn)}let V=vi(w,F.response);yield V.length>0?c({...F,response:{...F.response,output:V}}):c(F);continue}yield c(F)}if(yield*A(),yield*q("incomplete"),yield*j("incomplete"),o&&!te){let F=xe(d);u.remember(r,t,vn(F,Qe(d,F)),a)}}var Ri="/v1/responses",Ai=64*1024*1024,Ii=8*1024*1024,Ei=16,Rr=32,Ar=3600*1e3,Ti=/^[A-Za-z0-9._-]{1,256}$/;function ue(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Oi=ue(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 xn(){let n,e;return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}async function Pi(n){for(;n.bufferedAmount>Ii&&n.readyState===_t.OPEN;){let{promise:e,resolve:t}=xn();setTimeout(t,5),await e}}var kn=class extends Ke{constructor(t){super();this.shared=t}shared;thread(t,r){if(t==null)return super.thread(t,r);try{return super.thread(t,r)}catch(s){if(!(s instanceof qe))throw s;return this.shared.thread(t,r)}}remember(t,r,s,i=!0){i?this.shared.remember(t,r,s):super.remember(t,r,s)}forget(t){super.forget(t),this.shared.forget(t)}},Sn=class{constructor(e,t,r,s,i){this.ws=e;this.clients=t;this.stats=r;this.statusOf=s;this.operatorLog=i;this.store=new kn(gt(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(ue(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ar/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ar).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(ue(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ue(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ue(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let s=r;if(s.type!=="response.create"){this.sendFrame(ue(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(s.type??null)}; only "response.create" is supported`}));return}if("stream"in s){this.sendFrame(ue(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in s){this.sendFrame(ue(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let i;if(s.stream_id!==void 0){if(typeof s.stream_id!="string"||!Ti.test(s.stream_id)){this.sendFrame(Oi);return}if(i=s.stream_id,!this.lanes.has(i)&&this.namedLaneCount()>=Rr){this.sendFrame(ue(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Rr}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},i));return}}let o=s.generate===!1?()=>this.runWarmup(s,i):()=>this.runTurn(s,i),a=i??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(o).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,t){if(this.closed)return;await this.acquire();let r=ft();try{let s=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",s,s);let i;try{i=await yt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ht(r)})}catch(a){this.failTurn(a,t,e,r);return}this.laneOfResponse.set(i.responseId,t??null);let o=i.events;this.activeTurns.add(o);try{for await(let a of o){if(this.closed||this.ws.readyState!==_t.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,t,r));break}this.send(a,t),await Pi(this.ws)}}finally{this.activeTurns.delete(o)}}catch(s){this.failTurn(s,t,e,r)}finally{this.release()}}runWarmup(e,t){if(this.closed)return;let r=ft(),s=ht(r);try{let i=Ze(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(s,i,[],e.store!==!1),this.laneOfResponse.set(s,t??null),this.send({type:"response.created",response:{id:s,object:"response",status:"in_progress"}},t)}catch(i){this.failTurn(i,t,e,r)}}failTurn(e,t,r,s){this.sendFrame(this.errorFrameOf(e,t,s));let i=r.previous_response_id;typeof i=="string"&&this.laneOfResponse.get(i)===(t??null)&&(this.store.forget(i),this.laneOfResponse.delete(i))}errorFrameOf(e,t,r){let s=e instanceof Error?e.message:pe(e);if(e instanceof fe)return ue(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 ue(404,{type:"invalid_request_error",code:"model_not_found",message:s},t);if(e instanceof Z){let a=de(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),ue(503,{type:"upstream_error",code:"session_gone",message:a.message},t)}let i=this.statusOf?.(e)??null;if(i)return i.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${i.operatorDetail}`),ue(i.status,{type:i.openaiType,message:s},t);let o=de(e,{inferenceId:r});return o.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${s}`),ue(500,{type:"upstream_error",message:o.message},t)}upstreamErrorFrameOf(e,t,r){let s=e.error,i=s?.type??"upstream_error",o=Se(s),a=o??be(r);return o===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),ue(i==="invalid_request_error"?400:502,{type:i,...s&&typeof s.code=="string"?{code:s.code}:{},message:a},t)}async acquire(){for(;this.active>=Ei;){let{promise:e,resolve:t}=xn();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!==_t.OPEN)return;let r=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==_t.OPEN||this.ws.send(JSON.stringify(e))}};function Ut(n,e,t){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",s=`${t}\r
15
- `;n.end(`HTTP/1.1 ${e} ${r}\r
16
- Connection: close\r
17
- Content-Type: text/plain; charset=utf-8\r
18
- Content-Length: ${Buffer.byteLength(s)}\r
19
- \r
20
- ${s}`)}function Ir(n,e){let t=new xi({noServer:!0,maxPayload:Ai}),r=new De,s=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{Ut(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>o.delete(c)),m.pathname!==Ri){o.add(c);return}i.add(c);let f=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Ut(c,401,"invalid local proxy api key");return}let v;try{v=await a(d)}catch(S){let w=e.statusOf?.(S)??null;Ut(c,w?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(f=!0,t.handleUpgrade(d,c,p,S=>{i.delete(c),s.add(S),S.on("close",()=>s.delete(S));try{new Sn(S,v,r,e.statusOf,e.operatorLog??(w=>console.error(w)))}catch{s.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!f&&!c.destroyed&&Ut(c,500,"responses websocket upgrade failed")}).finally(()=>i.delete(c))};return n.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=xn();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 s)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of s)m.readyState!==_t.CLOSED&&m.terminate()},2e3);return p.unref?.(),t.close(()=>{clearTimeout(p),c()}),d}}}$();var N=class extends Error{},he=class extends Error{};function se(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Bt(n){return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:null}function et(n,e){if(n!=null)throw new N(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Rn(n){let e=Bt(n);return e!==null&&e<=1?e:null}function Er(n,e){if(!se(n))throw new N("decisions requires a JSON object body");et(n.prompt_cache_key,"prompt_cache_key"),et(n.prompt_cache_options,"prompt_cache_options"),et(n.safety_identifier,"safety_identifier");let t=[],r=Mi(n.input,t),s=n.questions;if(!Array.isArray(s)||s.length<1||s.length>400)throw new N("decisions requires a questions array of 1 to 400 questions");let i={},o=[],a=new Set;for(let l=0;l<s.length;l++){let{entry:d,spec:c}=Fi(s[l],l,s.length,t);if(a.has(c.key))throw new N(`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:r,questions:i};return t.length>0&&(u.media=t),{systemone:u,specs:o}}function Mi(n,e){if(typeof n=="string")return n;if(!se(n)&&!Array.isArray(n))throw new N("decisions input must be a string or an array of messages");let t=Array.isArray(n)?n:[n],r=[];for(let s of t)Li(s,r,e);return Ci(r)}function Ci(n){return n.length===0?"":n.some(e=>e.role!==void 0)?n:n.flatMap(e=>"text"in e?[e.text]:[]).join(`
21
-
22
- `)}function Li(n,e,t){if(!se(n))throw new N("decisions input items must be JSON objects");let r=n.role,s=n.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){$i(n,r,e,t);return}switch(s){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:s,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)){Tr(i,e,t,void 0,!1);return}throw new N(`${s} output must be a string or an array of parts`)}default:throw new N(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(s??null)})`)}}function $i(n,e,t,r){e==="assistant"&&et(n.phase,"assistant message phase");let s=n.content;if(typeof s=="string"){t.push({role:e,text:s});return}if(!Array.isArray(s))throw new N(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let i of s){if(!se(i))throw new N("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 N(`unsupported decisions assistant message part type ${JSON.stringify(i.type??null)}`)}return}Tr(s,t,r,e)}function Tr(n,e,t,r,s=!0){for(let i of n){if(!se(i))throw new N("decisions content parts must be JSON objects");switch(et(i.prompt_cache_breakpoint,"prompt_cache_breakpoint"),i.type){case"input_text":{if(typeof i.text!="string")throw new N("input_text requires a string text");e.push({role:r,text:i.text});break}case"input_json":{if(!s)throw new N("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(!se(o)&&!(Array.isArray(o)&&o.every(se)))throw new N("input_json data must be an object or an array of objects");e.push({role:r,json:o});break}case"input_image":{t.push(Or(i));break}default:throw new N(`unsupported decisions content part type ${JSON.stringify(i.type??null)}`)}}}function Or(n){let e=n.image_url;if(typeof e!="string"||e==="")throw new N("input_image requires a string image_url");let t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(t===null)throw new N("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,s]=t;if(s==="")throw new N("input_image data URL carries no image data");let i=s.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(s)||(i?s.length%4!==0:s.length%4===1))throw new N("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 N("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:s};return(o==="low"||o==="high")&&(a.detail=o),a}function Fi(n,e,t,r){if(!se(n))throw new N(`questions[${e}] must be a JSON object`);let s=n.type;if(s!=="predicate"&&s!=="choice"&&s!=="score")throw new N(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(s??null)})`);let i=n.name;if(i!==void 0&&typeof i!="string")throw new N(`questions[${e}] name must be a string`);let o=i??null,a=o??`q${e}`,u=Ni(n.instructions,e,t,r);switch(s){case"predicate":return{entry:{kind:"noul",prompt:u,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:s,key:a,name:o}};case"choice":{let l=n.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new N(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let v of l){if(!se(v))throw new N(`questions[${e}] choices must be JSON objects`);let S=v.value;if(typeof S!="string"&&typeof S!="boolean")throw new N(`questions[${e}] choice value must be a string or boolean`);let w=String(S);if(c.has(w))throw new N(`questions[${e}] has duplicate choice value ${JSON.stringify(w)} (choices must be unique)`);c.add(w);let _=v.description;if(_!==void 0&&typeof _!="string")throw new N(`questions[${e}] choice description must be a string`);d.push(S),p.push(_)}let m=l.map((v,S)=>({name:String(d[S]),description:p[S]??String(d[S])}));return{entry:{kind:"choice",prompt:u,options:m},spec:{type:s,key:a,name:o,choiceValues:d}}}case"score":{let l=n.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new N(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!se(m)||typeof m.label!="string")throw new N(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new N(`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 N(`questions[${e}] score level description must be a string`);let v=f!==void 0?`${m.label}: ${f}`:m.label;if(c.includes(v))throw new N(`questions[${e}] has duplicate score criterion ${JSON.stringify(v)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(v)}return{entry:{kind:"score",prompt:u,criteria:c},spec:{type:s,key:a,name:o,levelLabels:d}}}}}function Ni(n,e,t,r){if(typeof n=="string")return n;if(!Array.isArray(n))throw new N(`questions[${e}] instructions must be a string or an array of input parts`);let s=[];for(let i of n){if(!se(i))throw new N(`questions[${e}] instruction parts must be JSON objects`);switch(et(i.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),i.type){case"input_text":{if(typeof i.text!="string")throw new N(`questions[${e}] input_text requires a string text`);s.push(i.text);break}case"input_image":{if(t>1)throw new N(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Or(i));break}case"input_json":{let o=i.data;if(!se(o)&&!(Array.isArray(o)&&o.every(se)))throw new N(`questions[${e}] input_json data must be an object or an array of objects`);s.push(JSON.stringify(o));break}default:throw new N(`unsupported decisions instruction part type ${JSON.stringify(i.type??null)}`)}}return s.join(`
23
-
24
- `)}function Pr(n,e){if(!se(e))throw new he("decision answer was not a JSON object");let t=e.answers;if(!se(t))throw new he("decision answer carried no answers object");let r=[];for(let s of n){let i=t[s.key];if(!se(i)||i.skipped===!0){r.push({type:"refusal",name:s.name});continue}let o=se(i.probabilities)?i.probabilities:{};switch(s.type){case"predicate":{let a=Rn(i.noul);if(a===null)throw new he(`the predicate answer for "${s.key}" carries no noul probability to translate`);r.push({type:"predicate",name:s.name,probability:a});continue}case"choice":{let a=s.choiceValues??[],u=i.choice;if(typeof u!="string")throw new he(`the choice answer for "${s.key}" carries no string choice`);let l=a.findIndex(p=>String(p)===u);if(l===-1)throw new he(`the choice answer for "${s.key}" is not one of the supplied options (${JSON.stringify(u)})`);let d=Bt(i.confidence);if(d===null)throw new he(`the choice answer for "${s.key}" carries no numeric confidence to translate`);let c=[];for(let p of a){let m=Rn(o[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:s.name,choice:a[l],confidence:d,probabilities:c});continue}case"score":{let a=s.levelLabels??[],u=Bt(i.score);if(u===null)throw new he(`the score answer for "${s.key}" carries no numeric score to translate`);let l=Bt(i.confidence);if(l===null)throw new he(`the score answer for "${s.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let p=Rn(o[String(c)]);p!==null&&d.push({value:c,label:a[c],probability:p})}r.push({type:"score",name:s.name,score:u,confidence:l,probabilities:d});continue}}}return r}$();$();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 r=[],s=0;for await(let i of n){let o=i;if(s+=o.length,s>e)throw new ie(`request body exceeds the ${e}-byte limit`);r.push(o)}return Buffer.concat(r)}async function Ht(n,e){let t=n[Symbol.asyncIterator](),r=0,s=new ReadableStream({async pull(o){try{let a=await t.next();if(a.done){o.close();return}if(r+=a.value.length,r>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:s,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 Mr="/v1/images/generations",Jt="/v1/images/edits";function Cr(n){return n===Mr||n===Jt}var Lr="/v1/images/models";async function $r(n,e,t){if(n){if(n.model=ae({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 r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var U=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}},Di=16*1024*1024,Fr=64*1024*1024;function Nr(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 wt(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 Dr(n,e,t,r,s,i){let o=i??(f=>console.error(f)),a=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1},r),u=null;for await(let f of a){if(f.type==="error"){let v=f.error??{},S=typeof v.message=="string"&&v.message.length>0&&ve(v.message)?v.message:null;throw S===null?(o(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(f)}`),new U(502,"the image upstream failed while serving this request")):new U(502,`image upstream error: ${S}`)}if(f.type==="response.completed"){u=f.response??null;break}}if(u===null)throw new U(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");s&&(s.outputSeconds=Ae(u));let l=u.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new U(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(Nr(p)===null)throw new U(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 qr(n,e){if(n instanceof U)return n;if(n instanceof Te)throw n;return n instanceof J?new U(404,n.message):new U(502,Ve("image",n,e))}async function Ur(n,e,t,r){if(await n(e,t))return!0;let s=t==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return wt(r,new U(404,e===void 0?`no image-capable default model is configured for this caller (${s}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${t==="edit"?"edit-capable":"generation-capable"} for this caller (${s}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Br(n,e){n&&(n.outputUnits=e.images.length)}function jr(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 qi={model:!0,prompt:!0,response_format:!0,n:!0};async function Hr(n,e,t){let r=t.operatorLog??(i=>console.error(i)),s=t.maxBodyBytes??Fr;try{if(n.method!=="POST")throw new U(405,`${String(n.method)} is not supported on ${Mr}`);let i;try{i=JSON.parse((await jt(n,s)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new U(413,p.message):new U(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new U(400,"request body must be a JSON object");let o=i;for(let p of Object.keys(o))if(!qi[p])throw new U(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 U(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 U(400,"model must be a string","model");await $r(t.turn,t.clients,u);let l=o.n??1;if(l!==1)throw new U(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 U(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 Ur(t.imageModels,u,"generation",e))return;let c=[{type:"input_text",text:a}];try{let p=await Dr(t.clients,u,c,t.turn?me(t.turn):void 0,t.turn,r);Br(t.turn,p),jr(e,p)}catch(p){throw qr(p,r)}}catch(i){if(i instanceof ie){wt(e,new U(413,i.message));return}if(i instanceof U){wt(e,i);return}throw i}}var Ui={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Jr(n,e,t){let r=t.operatorLog??(o=>console.error(o)),s=t.maxBodyBytes??Fr,i=t.maxImagePartBytes??Di;try{if(n.method!=="POST")throw new U(405,`${String(n.method)} is not supported on ${Jt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new U(400,`the edit endpoint consumes multipart/form-data, got ${o||"none"}`);let a;try{a=await Ht(n,s)}catch(f){throw f instanceof ie?new U(413,f.message):new U(400,String(f instanceof Error?f.message:f))}let u=a.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new U(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 U(400,"model must be a string field","model");let d=l===null?void 0:l;await $r(t.turn,t.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new U(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(!Ui[f])throw new U(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 v of a.getAll(f)){if(!(v instanceof File))throw new U(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(v.size>i)throw new U(413,`image part exceeds the ${i}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let S=new Uint8Array(await v.arrayBuffer()),w=Nr(S);if(w===null)throw new U(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:S,mime:w})}if(p.length===0)throw new U(400,"the edit endpoint requires at least one `image` file part","image");if(t.stats?.request("images_edits",u.length,u.length),!await Ur(t.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:u}];for(let{bytes:f,mime:v}of p)m.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Dr(t.clients,d,m,t.turn?me(t.turn):void 0,t.turn,r);Br(t.turn,f),jr(e,f)}catch(f){throw qr(f,r)}}catch(o){if(o instanceof ie){wt(e,new U(413,o.message));return}if(o instanceof U){wt(e,o);return}throw o}}$();var vt="/v1/audio/speech";function Zr(n){return n===vt}var Gr=4096,Wr=18e4,Vr=5e3,Bi=64*1024*1024,zr=8,Kr=5,Xr=1024*1024,tt="voice_applied",Wt="X-Urun-Voice-Applied",D=class extends Error{status;param;retryAfterSeconds;constructor(e,t,r,s){super(t),this.status=e,this.param=r,this.retryAfterSeconds=s}};function An(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 Vt=class extends D{constructor(e){super(502,e)}};function es(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 ts(n){return new D(502,`the runtime's ${tt} receipt ${JSON.stringify(n)} cannot be relayed as the ${Wt} 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 ji(n,e,t){if(n){if(n.model=ae({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 r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function ns(n,e){if(!n)return;let t=e/(24e3*2);n.outputUnits=t,n.outputMinutes=t/60}var Hi=2;function Ji(n){for(let e=0;e+1<n.byteLength;e+=2)if(Math.abs(n.readInt16LE(e))>Hi)return!1;return!0}function Gi(n){let e=24e3,t=2,r=1,s=Buffer.alloc(44);return s.write("RIFF",0,"ascii"),s.writeUInt32LE(36+n,4),s.write("WAVE",8,"ascii"),s.write("fmt ",12,"ascii"),s.writeUInt32LE(16,16),s.writeUInt16LE(1,20),s.writeUInt16LE(r,22),s.writeUInt32LE(e,24),s.writeUInt32LE(e*r*t,28),s.writeUInt16LE(r*t,32),s.writeUInt16LE(16,34),s.write("data",36,"ascii"),s.writeUInt32LE(n,40),s}var Yr=new WeakMap,Gt=new WeakMap;function Wi(n,e){let t=Gt.get(n)??0;if(t>=zr)throw new D(503,`this model's speech queue is full \u2014 ${zr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Kr}s`,void 0,Kr);Gt.set(n,t+1);let r=Yr.get(n)??Promise.resolve(),s,i=new Promise(o=>{s=o});return Yr.set(n,i),(async()=>{await r;try{return await e()}finally{Gt.set(n,(Gt.get(n)??1)-1),s()}})()}async function Vi(n,e,t,r){if(typeof n.evictSpeechSession!="function")throw new D(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 Z))throw o}if(t?.return===void 0)return;let s=Promise.resolve(t.return()).then(()=>{},()=>{}),i;await Promise.race([s,new Promise(o=>{i=setTimeout(o,r)})]).finally(()=>{clearTimeout(i)})}function je(n,e){if(n instanceof D)return n;if(n instanceof Te)throw n;return n instanceof J?new D(404,n.message):new D(502,Ve("speech",n,e))}async function Qr(n,e,t,r,s,i,o,a,u,l){let d=l??(p=>console.error(p)),c=a??(()=>{});return Wi(e,async()=>{if(o?.()===!0)return null;let p=!1,m=!1,f=!1,v,S=new Promise(k=>{v=k}),w=[],_,h=!1,y=null,C=()=>{y!==null&&(clearTimeout(_),_=setTimeout(()=>{h=!0,y?.()},s.capMs))},T=()=>{m&&!f&&w.length>=s.quietRunFrames&&(f=!0,v())},b=e.onOutputAudio(k=>{let x=Buffer.from(k,"base64");if(x.byteLength===0)return;C();let P=Ji(x);if(!p){if(P)return;p=!0}if(P){w.push(x),T();return}for(let O of w)c(O);w.length=0,c(x),T()}),A=null,I,g;try{g=(await n.createResponseOn(t,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let x=()=>(clearTimeout(I),new Promise(M=>{I=setTimeout(M,i.capMs)})),P=x(),O=!1;for(;;){let M=g.next(),L=await Promise.race([M,P]);if(L===void 0){O=!0,M.catch(()=>{});break}if(L.done)break;let ee=L.value;if(P=x(),ee.type==="error"){let j=ee.error??{};await g.return?.();let te=typeof j.message=="string"&&j.message.length>0&&ve(j.message)?j.message:null;throw te===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(ee)}`),new D(502,"the speech upstream failed while serving this request")):new D(502,`speech upstream error: ${te}`)}if(ee.type==="response.completed"){A=ee.response??null,m=!0,u?.(A),T(),await g.return?.();break}}if(clearTimeout(I),O)throw new D(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(A===null)throw new D(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let q=new Promise(M=>{y=M});if(C(),await Promise.race([S,q]),clearTimeout(_),_=void 0,y=null,r.voice!==void 0){let M=A[tt];if(typeof M!="string"||M!==r.voice){let L=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof M=="string"?`${tt} ${JSON.stringify(M)}`:`no ${tt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw f?new Vt(L):new D(502,L)}}if(!p)throw new D(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(h&&!f&&w.length<1)throw new D(502,`the upstream audio stream did not quiesce within ${s.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 A}catch(k){throw k instanceof Vt||await Vi(n,t,g,i.returnBoundMs),k}finally{clearTimeout(_),clearTimeout(I),b()}})}function zi(n,e,t,r){let s=!1,i=0,o=a=>{n.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){t()||(s||(s=!0,n.statusCode=200,n.setHeader("content-type","audio/pcm"),r&&n.setHeader("trailer",Wt)),n.write(a,u=>{u||(i+=a.byteLength,ns(e,i))}),n.writableLength>Xr&&(e&&(e.streamError=!0),o(new Error(`the streamed pcm answer's undrained buffer crossed ${Xr} 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:()=>s,async finish(a){if(!t()){if(r){let u=a[tt];if(typeof u=="string"){if(!es(u))throw ts(u);n.addTrailers({[Wt]:u})}}await new Promise(u=>{n.end(()=>u())})}},fail:o}}async function Ki(n,e,t,r){let s;try{s=await n(e)}catch(i){throw je(i,r)}return s?!0:(An(t,new D(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 Xi={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Yi="wav, pcm";async function rs(n,e,t){let r=t.operatorLog??(a=>console.error(a)),s=t.maxBodyBytes??Bi,i=!1;e.once("close",()=>{i=!0});let o=()=>i||e.destroyed;try{if(n.method!=="POST")throw new D(405,`${String(n.method)} is not supported on ${vt}`);let a;try{a=JSON.parse((await jt(n,s)).toString("utf8")||"{}")}catch(y){throw y instanceof ie?new D(413,y.message):new D(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new D(400,"request body must be a JSON object");let u=a;for(let y of Object.keys(u))if(!Xi[y])throw new D(400,`request field "${y}" 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.`,y);let l=u.input;if(typeof l!="string"||l.trim().length===0)throw new D(400,"input is required and must be a non-empty string","input");if(l.length>Gr)throw new D(400,`input is ${l.length} chars \u2014 over the ${Gr}-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 D(400,"model must be a string","model");let c=u.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new D(400,"voice must be a non-empty string","voice");if(typeof t.clients.speechVoices!="function")throw new D(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 ${vt} against a stale copy of the list`);let p;try{p=await t.clients.speechVoices(d)}catch(y){throw je(y,r)}if(p.defect!==null)throw new D(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 D(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 D(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 ${Yi} \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 D(400,"stream_format, when present, must be a string","stream_format");let v=u.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new D(400,"speed, when present, must be a number","speed");if(v!==1)throw new D(400,`speed=${JSON.stringify(v)} 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 S=u.instructions;if(S!==void 0){if(typeof S!="string")throw new D(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new D(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 ji(t.turn,t.clients,d);let w=Buffer.byteLength(JSON.stringify(u));if(t.stats?.request("audio_speech",w,w),!await Ki(t.speechModels,d,e,r))return;if(typeof t.clients.openAudioOn!="function")throw new D(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 D(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 D(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 _;try{_=await t.clients.speechSessionHandle(d)}catch(y){throw je(y,r)}let h;try{h=await t.clients.openAudioOn(_)}catch(y){throw je(y,r)}t.turn&&(t.turn.sessionId=h.sessionId);try{if(f==="wav"){let y=[],C=await Qr(t.clients,h,_,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Wr,returnBoundMs:t.turnReturnBoundMs??Vr},o,b=>y.push(b),b=>{t.turn&&(t.turn.outputSeconds=Ae(b))},r);if(C===null||o())return;let T=Buffer.concat(y);if(m===void 0){let b=C[tt];if(typeof b=="string"){if(!es(b))throw ts(b);e.setHeader(Wt,b)}}ns(t.turn,T.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Gi(T.byteLength),T]))}else{let y=zi(e,t.turn,o,m===void 0),C;try{C=await Qr(t.clients,h,_,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??Wr,returnBoundMs:t.turnReturnBoundMs??Vr},o,y.sink,T=>{t.turn&&(t.turn.outputSeconds=Ae(T))},r)}catch(T){let b=je(T,r);if(!y.started())throw b;t.turn&&(t.turn.streamError=!0),y.fail(b);return}if(C===null)return;try{await y.finish(C)}catch(T){let b=je(T,r);t.turn&&(t.turn.streamError=!0),y.fail(b);return}}}catch(y){throw je(y,r)}}catch(a){if(a instanceof ie){An(e,new D(413,a.message));return}if(a instanceof D){An(e,a);return}throw a}}$();var zt="/v1/audio/transcriptions";function ss(n){return n===zt}var is="/v1/audio/models",Qi=16*1024*1024,Zi=64*1024*1024,K=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}};function In(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 os(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 eo(n){if(!os(n))return null;let e=12,t=null,r=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;r=Math.min(o===0||o===4294967295?u:o,u)}e=a+o+o%2}if(t===null||r===null||r===0||t.sampleRate===0||t.channels===0||t.bitsPerSample===0)return null;let s=r/(t.sampleRate*t.channels*(t.bitsPerSample/8));return!Number.isFinite(s)||s<0?null:{seconds:s,sampleRate:t.sampleRate,channels:t.channels,bitsPerSample:t.bitsPerSample}}async function to(n,e,t){if(n){if(n.model=ae({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 r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function no(n,e){n&&(n.outputUnits=e.seconds)}async function ro(n,e,t,r,s,i,o){let a=o??(c=>console.error(c)),u=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1,...r!==void 0?{language:r}:{}},s),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 K(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new K(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 K(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return i&&(i.outputSeconds=Ae(d)),Qe(l,d)}function as(n,e){if(n instanceof K)return n;if(n instanceof Te)throw n;return n instanceof J?new K(404,n.message):new K(502,Ve("transcription",n,e))}async function so(n,e,t,r){let s;try{s=await n(e)}catch(i){throw as(i,r)}return s?!0:(In(t,new K(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 io=new Set(["file","model","language","response_format"]);async function us(n,e,t){let r=t.operatorLog??(o=>console.error(o)),s=t.maxBodyBytes??Zi,i=t.maxAudioPartBytes??Qi;try{if(n.method!=="POST")throw new K(405,`${String(n.method)} is not supported on ${zt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the transcriptions endpoint consumes multipart/form-data, got ${o||"none"}`);let a;try{a=await Ht(n,s)}catch(_){throw _ instanceof ie?new K(413,_.message):new K(400,String(_ instanceof Error?_.message:_))}let u=new Map;for(let _ of a.keys()){if(!io.has(_))throw new K(400,`form field "${_}" 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.`,_);u.set(_,(u.get(_)??0)+1)}for(let[_,h]of u)if(h>1)throw new K(400,`form field "${_}" 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`,_);let l=a.get("model");if(l!==null&&typeof l!="string")throw new K(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 K(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 K(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 K(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 K(413,`file part exceeds the ${i}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await f.arrayBuffer());if(!os(v))throw new K(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 S=eo(v);if(S===null)throw new K(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 to(t.turn,t.clients,d),t.stats?.request("audio_transcriptions",v.length,v.length),!await so(t.transcriptionModels,d,e,r))return;let w=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let _=await ro(t.clients,d,w,p,t.turn?me(t.turn):void 0,t.turn,r);no(t.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:_}))}catch(_){throw as(_,r)}}catch(o){if(o instanceof ie){In(e,new K(413,o.message));return}if(o instanceof K){In(e,o);return}throw o}}$();var ms="/v1/usage/requests",ls=1e4,oo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ce=class extends Error{constructor(t,r=400){super(t);this.status=r;this.name="UsageRequestError"}status},ne=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Kt=class extends ne{constructor(e){super(e),this.name="UsageWithholdingError"}},fs=1024*1024;function On(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new Ce(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let t=n[e];if(!Array.isArray(t))throw new Ce(`"${e}" must be an array of uuid strings`);if(t.length>ls)throw new Ce(`"${e}" carries ${t.length} ids; at most ${ls} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],s=new Set;for(let i of t){if(typeof i!="string"||!oo.test(i))throw new Ce(`"${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`);s.has(i)||(s.add(i),r.push(i))}return r}function hs(n){return On(n,"inference_ids")}var ao=["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 nt(n,e,t){let r=n[e];if(typeof r!="string"||r==="")throw new ne(`${t}: ${e} is not a non-empty string (got ${st(r)})`);return r}function En(n,e,t){let r=n[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new ne(`${t}: ${e} is neither null nor a non-empty string (got ${st(r)})`);return r}function rt(n,e,t,r){let s=n[e];if(s===null)return null;let i=typeof s=="number"?s:typeof s=="string"&&/^-?\d+(\.\d+)?$/.test(s.trim())?Number(s.trim()):NaN;if(!Number.isFinite(i))throw new ne(`${t}: ${e} is not a number (got ${st(s)})`);if(r&&!Number.isSafeInteger(i))throw new ne(`${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 ne(`${t}: ${e} is negative`);return Object.is(i,-0)?0:i}var uo=40,ds=64,cs=600;function gs(n){let e=Object.keys(n).sort(),r=e.slice(0,uo).map(s=>s.length>ds?`${s.slice(0,ds)}\u2026`:s).join(", ");return r.length>cs&&(r=`${r.slice(0,cs)}\u2026`),`${e.length} keys present: [${r}]`}function st(n){return n===null?"null":n===void 0?"undefined":Array.isArray(n)?"an array":typeof n=="object"?"an object":`a ${typeof n}`}function Tn(n){Oe(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:n.where,reason:n.reason})}
25
- `)}function lo(n,e){let t;try{t=n(e)}catch{ps(n,e);return}co(t)&&Promise.resolve(t).catch(()=>{ps(n,e)})}function co(n){return typeof n?.then=="function"}function ps(n,e){if(n!==Tn)try{Tn(e)}catch{}}function tl(n,e=Tn){let t=n?.requests;if(!Array.isArray(t)){let s=n!==null&&typeof n=="object"&&!Array.isArray(n)?gs(n):st(n);throw new ne(`the usage surface answered without a "requests" array: got ${st(t)} (${s})`)}let r=[];for(let s=0;s<t.length;s++){let i=`usage.requests[${s}]`;try{r.push(po(t[s],i))}catch(o){if(o instanceof Kt||!(o instanceof ne))throw o;lo(e,{where:i,reason:o.message})}}if(t.length>0&&r.length===0)throw new ne(`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 r}function po(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new ne(`${e} is not an object: got ${st(n)}`);let t=n;if(Object.hasOwn(t,"gpu_seconds"))throw new Kt(`${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 s of ao)if(!Object.hasOwn(t,s))throw new ne(`${e} has no "${s}" column (${gs(t)})`);let r=rt(t,"http_status",e,!0);if(r===null)throw new ne(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:nt(t,"inference_id",e),model_id:nt(t,"model_id",e),identity_kind:nt(t,"identity_kind",e),variant:En(t,"variant",e),task:nt(t,"task",e),http_status:r,started_at:nt(t,"started_at",e),completed_at:nt(t,"completed_at",e),prompt_tokens:rt(t,"prompt_tokens",e,!0),completion_tokens:rt(t,"completion_tokens",e,!0),output_units:rt(t,"output_units",e,!1),output_minutes:rt(t,"output_minutes",e,!1),cost_nano_usd:rt(t,"cost_nano_usd",e,!0),price_version:En(t,"price_version",e),priced_at:En(t,"priced_at",e)}}function Xt(n,e){let t=new Set(e),r=new Set;for(let s=0;s<n.length;s++){let i=n[s];if(!t.has(i.inference_id))throw new ne(`the usage surface returned an id at validated answer position ${s} 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(r.has(i.inference_id))throw new ne(`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`);r.add(i.inference_id)}}import{SessionAllocationError as Do,SessionFailedError as qo}from"@urun-sh/core";$();var Pn="/partners/huggingface/v1/billing/requests";function mo(n){return On(n,"requestIds")}function fo(n){return n>=200&&n<=399}function ho(n){let e=[];for(let t of n)t.cost_nano_usd!==null&&fo(t.http_status)&&e.push({requestId:t.inference_id,costNanoUsd:t.cost_nano_usd});return{requests:e.length>0?e:null}}async function ys(n,e){let t=mo(n),r=await e(t);return Xt(r,t),ho(r)}$();var go={"/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 yo(n){return go[n]??null}var vs=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function _o(n){let e=n?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function wo(n){return n==="surface"}function vo(n){let e=n?.ledgerFailureReason;return vs.includes(e)?e:"unknown"}var bo=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],_s=["priced","unpriced"],ko={written:_s,already_written:_s,skipped:bo,failed:vs},ul=Object.entries(ko).flatMap(([n,e])=>e.map(t=>({outcome:n,reason:t})));function So(n){return n.status===null?!1:n.status>=200&&n.status<400&&!n.stream_error}function xo(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 Ro=256,ws=4096,bt=12e4,Ao=250,Io=8e3,Ie=[],Mn=new Set,kt=0,it=!1;function ll(){return Ie.length}function dl(n=Date.now()){let e=Ie[0];return e===void 0?0:Math.max(0,n-e.queuedAt)}var Yt=new Set;function bs(){return kt===0&&Ie.length===0}function ks(){if(bs()){it=!1;for(let n of[...Yt])n()}}async function cl(n=Ss){return bs()?!0:await new Promise(e=>{let t,r=()=>{Yt.delete(r),clearTimeout(t),e(!0)};Yt.add(r),t=setTimeout(()=>{Yt.delete(r),e(!1)},n),t.unref?.()})}function pl(){it=!0;let n=[...Ie.splice(0,Ie.length),...Mn];for(let e of n)e.settled||He(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 ${Ss}ms drain \u2014 the request was served and answered, and its billing row was never written`});return ks(),n.length}var Ss=5e3;function xs(n,e){return`${JSON.stringify({event:n,ts:new Date().toISOString(),...e})}
26
- `}function Eo(n){Oe(process.stdout,n)}function Rs(n,e){try{n(e)}catch{}}function As(n){let{record:e,ledger:t}=n;if(t===null)return;let r=t.report??Eo,s=yo(e.path);if(s===null)return;let i=d=>{try{t.observe(d)}catch{}},o=(d,c)=>{i({outcome:"skipped",reason:d}),Rs(r,xs("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:s,http_status:e.status,started_at:xo(e),completed_at:e.ts,billable_outcome:So(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(Ie.length>=ws){o("queue_full",`${Ie.length} ledger writes are already waiting (capacity ${ws}, ${kt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ie.push({entry:l,req:n.req,record:e,ledger:t,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),kt<Ro&&(kt+=1,To())}async function To(){try{for(;;){let n=Oo();if(n===void 0)return;Mn.add(n);try{await Po(n)}finally{Mn.delete(n)}}}finally{kt-=1,ks()}}function Oo(){let n=Date.now();for(;;){let e=Ie.shift();if(e===void 0)return;let t=n-e.queuedAt;if(t<bt)return e;He(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 ${bt}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 Po(n){let{entry:e,record:t,ledger:r}=n;for(;;){n.attempts+=1;try{let s=await r.write(n.req,e);He(n,{outcome:"written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:s.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:s.cost_nano_usd,price_version:s.price_version,unpriced_reason:s.unpriced_reason,attempts:n.attempts});return}catch(s){let i=_o(s);if(i!==null){He(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=vo(s),a=Date.now()-n.queuedAt;if(it){He(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: ${s instanceof Error?s.message:String(s)}`});return}if(wo(o)&&a<bt){if(await Co(Mo(n.attempts)),it||Date.now()-n.queuedAt>=bt){let u=Date.now()-n.queuedAt;He(n,{outcome:"failed",reason:it?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:it?"dropped_on_exit":"dwell_expired",attempts:n.attempts,waited_ms:u,error:`this row's backoff outlived the ${bt}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: ${s instanceof Error?s.message:String(s)}`});return}continue}He(n,{outcome:"failed",reason:o},{event:"inference_ledger_write_failed",reason:o,attempts:n.attempts,waited_ms:a,error:s instanceof Error?s.message:String(s)});return}}}function Mo(n){return Math.min(Io,Ao*2**Math.max(0,n-1))}function Co(n){return new Promise(e=>{setTimeout(e,n).unref?.()})}function He(n,e,t){if(n.settled)return;n.settled=!0;try{n.ledger.observe(e)}catch{}let{event:r,...s}=t;Rs(n.report,xs(r,{inference_id:n.entry.inference_id,path:n.record.path,org:n.record.org,...s}))}$();var Ln="x-urun-profile",St="voice";var le=class extends Error{status=400},Lo=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,$o=/\s/;function Fo(n){return Lo.test(n)}function Cn(n,e,t){let r=n[e];if(r===void 0)return t;if(typeof r!="boolean")throw new le(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Is(n,e,t,r={}){let s=n[e];if(s===void 0)return t;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new le(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(s)})`);if(r.min!==void 0&&s<r.min)throw new le(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(s)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&s>r.max)throw new le(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(s)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return s}function Es(n,e){let t=Array.isArray(n)?n[0]:n,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new le(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let s=r,i=s?.profile,o=!1;if(t!=null){let l=t.trim();if(l==="")throw new le(`the ${Ln} header is empty \u2014 the only profile this lane accepts is "${St}" (omit the header for the ordinary lane)`);if(l!==St)throw new le(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${St}"`);o=!0}if(i!==void 0){if(typeof i!="string"||i!==St)throw new le(`unknown profile ${JSON.stringify(i)} \u2014 the only profile this lane accepts is "${St}"`);o=!0}if(!o)return null;if(e.stream!==!0)throw new le("the voice profile is streaming-only \u2014 send stream: true");let a=s?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new le("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:Is(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:Is(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Cn(u,"sentence_flush",!0),includeReasoning:Cn(u,"include_reasoning",!1),metadata:Cn(u,"metadata",!1)}}var ot=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&&Fo(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let s=e-1;s>0;s--)if($o.test(this.buffer[s]))return s+1;let t=Math.max(1,e),r=this.buffer.charCodeAt(t-1);return r>=55296&&r<=56319?t-1:t}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function Nn(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Uo(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 G(n,e,t,r="invalid_request_error",s){oe(n,e,{error:s?{message:t,type:r,code:s}:{message:t,type:r}})}function Dn(n,e,t){let r=e.error,s=r?.type??"upstream_error",i=t?.operatorError??(d=>console.error(d)),o=Se(r),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=r?.code??null,l=s==="invalid_request_error"?400:u==="queue_timeout"?429:502;l===429&&n.setHeader("retry-after","30"),oe(n,l,{error:{message:a,type:s,code:u}})}function ke(n,e,t,r){oe(n,e,{type:"error",error:{type:t,message:r}})}function at(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 Bo=64*1024*1024,xt=class extends Error{};async function Ts(n,e=Bo){let t=[],r=0;for await(let i of n){if(r+=i.length,r>e)throw new xt(`request body exceeds ${e} bytes`);t.push(i)}let s=Buffer.concat(t).toString("utf8");return s?JSON.parse(s):{}}function Je(n,e,t,r){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:r}]}}function Ms(n){let e=n?.usage;if(!e||typeof e!="object")return{kind:"absent"};let t=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,s=r(t.input_tokens),i=r(t.output_tokens),o=u=>u??0,a=r(t.total_tokens)??o(s)+o(i);if(o(s)>0||o(i)>0){let u={input_tokens:o(s),output_tokens:o(i),total_tokens:a};return s===null||i===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return s===null||i===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Qt(n){let e=Ms(n);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Os(n){let e=Qt(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:jo(n)},completion_tokens_details:{reasoning_tokens:0}}}function jo(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 r=t.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function Ho(n,e){let t=Ms(e);t.kind==="absent"||t.kind==="partial"||(n.promptTokens=t.usage.input_tokens,n.completionTokens=t.usage.output_tokens)}function Jo(n){let e=n?.urun_timing;if(!e||typeof e!="object")return null;let t=e,r=u=>{let l=t[u];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},s=r("queue_ms"),i=r("prefill_ms"),o=r("decode_ms"),a=r("total_ms");return s===null||i===null||o===null||a===null?null:{queue_ms:s,prefill_ms:i,decode_ms:o,total_ms:a}}function Go(n,e){let t=Jo(e);t&&(n.timing=t),n.outputSeconds=Ae(e)}function Ge(n,e){Ho(n,e),Go(n,e)}async function tn(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 r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function Cs(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let s of r.content)s.type==="reasoning_text"&&(t+=String(s.text??""));return t}function Wo(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 Zt=class extends Error{};function Vo(n,e){return Array.isArray(e)?e.map(t=>{let r=t;if(r.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let s=r.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new Zt(`unsupported chat content part type "${String(r.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 r of t.tool_calls){let s=r.function??{};e.push({type:"function_call",call_id:r.id,name:s.name,arguments:s.arguments})}continue}e.push({...t,content:Vo(t.role,t.content)})}return e}function $n(n){return Xe(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 Ko(n,e,t,r,s,i,o){let a=ht(i.id),u=n.stream===!0;if(i.model=ae(n),i.stream=u,await tn(i,e,typeof n.model=="string"?n.model:void 0),u){let _;try{_=await yt({body:n,clients:e,store:t,stats:s,responseId:a,turn:i})}catch(h){if(h instanceof J){at(r,"openai",h);return}if(h instanceof fe){G(r,h.status,h.message);return}if(h instanceof _e||h instanceof ye){r.setHeader("retry-after","2"),G(r,503,h.message,"capacity_error");return}throw h}Nn(r);for await(let h of _.events){if(h.type==="error"){i.streamError=!0;let y=h.error,C=Se(y),T=C??be(i.id);C===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)}`),r.write(`event: error
27
- data: ${JSON.stringify({error:{message:T,type:y?.type??"upstream_error",code:y?.code??null}})}
28
-
29
- `),r.end();return}h.type==="response.completed"&&Ge(i,h.response),r.write(`event: ${String(h.type??"message")}
30
- data: ${JSON.stringify(h)}
31
-
32
- `)}r.write(`data: [DONE]
33
-
34
- `),r.end();return}let l;try{l=Ze(t,n)}catch(_){if(_ instanceof fe){G(r,_.status,_.message);return}throw _}n.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(n.input)));let d=n.store!==!1,c=ae(n);s.model(c);let p=Array.isArray(n.tools)&&n.tools.length>0,m;try{m=await bn(e,n,l,!1,me(i))}catch(_){if(_ instanceof J){at(r,"openai",_);return}if(_ instanceof fe){G(r,_.status,_.message);return}if(_ instanceof _e||_ instanceof ye){r.setHeader("retry-after","2"),G(r,503,_.message,"capacity_error");return}throw _}let f=[],v=null;for await(let _ of s.track(m,c,i)){if(f.push(_),_.type==="error"){Dn(r,_,{inferenceId:i.id,operatorError:o});return}_.type==="response.completed"&&(v=_.response)}if(v==null){G(r,502,"upstream produced no response.completed event","upstream_error");return}Ge(i,v);let S=Qe(f,v),w=Be(p,Xe(v).length,S);if(w){G(r,502,Ue(c,w),"upstream_error");return}d&&t.remember(a,l,vn(v,S),d),oe(r,200,{...v,id:a})}async function Xo(n,e,t,r,s,i,o){let a=n.messages;if(!Array.isArray(a)){G(t,400,"chat/completions requires a messages array");return}let u;try{u=Es(i,n)}catch(g){if(g instanceof le){G(t,g.status,g.message);return}throw g}let l=String(n.model??"urun"),d=wr(s.id),c;try{c=zo(a)}catch(g){if(g instanceof Zt){G(t,400,g.message);return}throw g}let p=ae(n);r.model(p),s.model=p,s.stream=n.stream===!0,await tn(s,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:Wo(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}:{}},me(s))}catch(g){if(g instanceof J){at(t,"openai",g);return}if(g instanceof _e||g instanceof ye){t.setHeader("retry-after","2"),G(t,503,g.message,"capacity_error");return}throw g}if(n.stream===!0){u?Uo(t):Nn(t);let g=[],k=new Me,x="",P=u?new ot(u,q=>{t.write(`data: ${JSON.stringify(Je(d,l,{content:q},null))}
35
-
36
- `)}):null,O=q=>{P?.flush(),t.write(q),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
-
38
- `),t.write(`data: ${JSON.stringify(Je(d,l,{role:"assistant"},null))}
39
-
40
- `);for await(let j of r.track(f,p,s)){g.push(j);let te=Ye(j);if(j.type==="response.output_text.delta"&&typeof j.delta=="string")x+=j.delta,P?P.push(j.delta):t.write(`data: ${JSON.stringify(Je(d,l,{content:j.delta},null))}
41
-
42
- `);else if(j.type==="response.reasoning_text.delta"&&typeof j.delta=="string")(!u||u.includeReasoning)&&t.write(`data: ${JSON.stringify(Je(d,l,{reasoning_content:j.delta},null))}
43
-
44
- `);else if(te){P?.flush();let{call:F,isNew:B}=k.add(te),W=B?{index:te.tool_index,id:F.id??`call_${te.tool_index}`,type:"function",function:{name:F.name??"",arguments:te.delta}}:{index:te.tool_index,function:{arguments:te.delta}};t.write(`data: ${JSON.stringify(Je(d,l,{tool_calls:[W]},null))}
45
-
46
- `)}else if(j.type==="error"){s.streamError=!0;let F=j.error??{},B=Se(F),W=B??be(s.id);B===null&&o(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(j)}`),O(`data: ${JSON.stringify({error:{message:W,type:F.type??"upstream_error",code:F.code??null}})}
47
-
48
- `);return}}let q=$n(xe(g)),M=Be(m,k.size+q.length,x);if(M){s.streamError=!0,O(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Ue(p,M)}})}
49
-
50
- `);return}P?.flush(),k.size===0&&q.length>0&&t.write(`data: ${JSON.stringify(Je(d,l,{tool_calls:q},null))}
51
-
52
- `);let L=k.size>0||q.length>0;t.write(`data: ${JSON.stringify(Je(d,l,{},L?"tool_calls":"stop"))}
53
-
54
- `);let ee=Qt(xe(g));Ge(s,xe(g)),ee&&t.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:Os(xe(g))})}
55
-
56
- `),t.write(`data: [DONE]
57
-
58
- `),t.end();return}finally{P?.flush(),P?.dispose()}}let v="",S="",w=[],_=new Me;for await(let g of r.track(f,p,s)){w.push(g),g.type==="response.output_text.delta"&&typeof g.delta=="string"&&(v+=g.delta),g.type==="response.reasoning_text.delta"&&typeof g.delta=="string"&&(S+=g.delta);let k=Ye(g);if(k&&_.add(k),g.type==="error"){Dn(t,g,{inferenceId:s.id,operatorError:o});return}}let h=xe(w);Ge(s,h);let y=$n(h),C=y.length>0?y:$n({output:_.items()}),T=Be(m,C.length,v);if(T){G(t,502,Ue(p,T),"upstream_error");return}let b=C.map(({index:g,...k})=>k),A={role:"assistant",content:v||null},I=S||Cs(h);I&&(A.reasoning_content=I),b.length>0&&(A.tool_calls=b),oe(t,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:A,finish_reason:b.length>0?"tool_calls":"stop"}],usage:Os(h)})}var Ls="sense-latest";async function Yo(n,e,t,r,s,i){if(n===null||typeof n!="object"||Array.isArray(n)){G(t,400,"systemone requires a JSON object body");return}delete n.key;let o=typeof n.model=="string"&&n.model?n.model:Ls,a=ae({model:o});if(s.model=a,s.stream=!1,n.state===void 0||n.state===null){G(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){G(t,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(n.media!==void 0&&!Array.isArray(n.media)){G(t,400,"systemone media, when present, must be an array");return}let l=await $s(n,o,a,e,t,r,s,i);l!==null&&oe(t,200,l.answer)}async function $s(n,e,t,r,s,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 tn(o,r,e),u.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(n)}],stream:!0},me(o))}catch(w){if(w instanceof J)return at(s,"openai",w),null;if(w instanceof _e||w instanceof ye)return s.setHeader("retry-after","2"),G(s,503,w.message,"capacity_error"),null;throw w}u.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let w of i.track(d,t,o))if(m===null&&(m=performance.now(),u.first_event_ms=Math.round(m-c)),p.push(w),w.type==="error")return Dn(s,w,{inferenceId:o.id,operatorError:a}),null}catch(w){if(w instanceof J)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),at(s,"openai",w),null;if(w instanceof _e||w instanceof ye)return m!==null&&(u.stream_ms=Math.round(performance.now()-m)),s.setHeader("retry-after","2"),G(s,503,w.message,"capacity_error"),null;throw m!==null&&(u.stream_ms=Math.round(performance.now()-m)),w}m!==null&&(u.stream_ms=Math.round(performance.now()-m));let f=xe(p);if(f==null)return G(s,502,"upstream produced no response.completed event","upstream_error"),null;Ge(o,f);let v=Qe(p,f),S;try{S=JSON.parse(v)}catch{return G(s,502,"systemone answer was not valid JSON","upstream_error"),null}if(S===null||typeof S!="object"||Array.isArray(S))return G(s,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let w=S.timing;if(typeof w=="object"&&w!==null&&!Array.isArray(w)&&"question_fwd_ms"in w&&"head_ms"in w){let _=h=>typeof h=="number"&&Number.isFinite(h)&&h>=0?Math.round(h):null;u.question_fwd_ms=_(w.question_fwd_ms),u.head_ms=_(w.head_ms)}}return{answer:S,completed:f}}async function Qo(n,e,t,r,s,i){if(n===null||typeof n!="object"||Array.isArray(n)){G(t,400,"decisions requires a JSON object body");return}let o=typeof n.model=="string"&&n.model?n.model:Ls,a=ae({model:o});s.model=a,s.stream=!1;let u;try{u=Er(n,o)}catch(p){if(p instanceof N){G(t,400,p.message);return}throw p}let l=await $s(u.systemone,o,a,e,t,r,s,i);if(l===null)return;let d;try{d=Pr(u.specs,l.answer)}catch(p){if(p instanceof he){G(t,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;oe(t,200,{model:o,answers:d,...c===void 0?{}:{usage:c}})}function Zo(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Rt=class extends Error{};function en(n){return new Rt(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function ea(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 ta(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 Rt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function na(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw en(typeof n);let e="";for(let t of n){let r=String(t.type??"");if(r!=="text")throw en(`tool_result > ${r}`);e+=String(t.text??"")}return e}function ra(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 en(typeof t);let r=[],s="",i=()=>{s&&(r.push({role:e,content:s}),s="")};for(let o of t){let a=String(o.type??"");if(a==="text")s+=String(o.text??"");else if(a==="tool_use")i(),r.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.input??{})});else if(a==="tool_result")i(),r.push({type:"function_call_output",call_id:o.tool_use_id,output:na(o.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw en(a)}}return i(),r}function Fn(n){return Xe(n).map((e,t)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${t}`,name:e.name??"",input:r}})}async function sa(n,e,t,r,s,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(A=>typeof A!="string"))){ke(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(n.model??"urun"),u=vr(s.id),l=[],d;try{n.system&&l.push({role:"system",content:Zo(n.system)});for(let A of o)l.push(...ra(A));d=ta(n.tool_choice)}catch(A){if(A instanceof Rt){ke(t,400,"invalid_request_error",A.message);return}throw A}let c=ae(n);r.model(c),s.model=c,s.stream=n.stream===!0,await tn(s,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:ea(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences},me(s))}catch(A){if(A instanceof J){at(t,"anthropic",A);return}if(A instanceof _e||A instanceof ye){t.setHeader("retry-after","2"),ke(t,503,"capacity_error",A.message);return}throw A}let f=(A,I)=>{t.destroyed||t.write(`event: ${A}
59
- data: ${JSON.stringify({type:A,...I})}
60
-
61
- `)};if(n.stream===!0){let A=r.track(m,c,s);Nn(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 I=0,g="",k=0,x="none",P=()=>x,O=-1,q=-1,M=new Me,L=[],ee=()=>{x!=="none"&&(x="none",f("content_block_stop",{index:O}))},j=(V,Q)=>{ee(),x=V,O=k++,f("content_block_start",{index:O,content_block:Q})};for await(let V of A){if(t.destroyed)break;L.push(V);let Q=Ye(V);if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")P()!=="thinking"&&j("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:O,delta:{type:"thinking_delta",thinking:V.delta}});else if(V.type==="response.output_text.delta"&&typeof V.delta=="string")P()!=="text"&&j("text",{type:"text",text:""}),I+=1,g+=V.delta,f("content_block_delta",{index:O,delta:{type:"text_delta",text:V.delta}});else if(Q){let{call:ge}=M.add(Q);(P()!=="tool"||Q.tool_index!==q)&&(q=Q.tool_index,j("tool",{type:"tool_use",id:ge.id??`call_${Q.tool_index}`,name:ge.name??"",input:{}})),Q.delta&&f("content_block_delta",{index:O,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(V.type==="error"){s.streamError=!0;let ge=V.error,$e=Se(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(V)}`),f("error",{error:{type:"api_error",message:$e??be(s.id)}}),t.end();return}}if(t.destroyed)return;let te=xe(L),F=Xe(te),B=Be(p,M.size+F.length,g);if(B){s.streamError=!0,f("error",{error:{type:"api_error",message:Ue(c,B)}}),t.end();return}ee();let W=[];if(M.size===0)try{W=Fn(te)}catch(V){s.streamError=!0;let Q=de(V,{inferenceId:s.id});Q.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(V instanceof Error?V.message:V)}`),f("error",{error:{type:"api_error",message:Q.message}}),t.end();return}k===0&&W.length===0&&(j("text",{type:"text",text:""}),ee()),W.forEach(V=>{let Q=k++;f("content_block_start",{index:Q,content_block:{...V,input:{}}}),f("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(V.input??{})}}),f("content_block_stop",{index:Q})});let Le=M.size>0||W.length>0,We=Qt(te);Ge(s,te),f("message_delta",{delta:{stop_reason:Le?"tool_use":"end_turn"},usage:We?{input_tokens:We.input_tokens,output_tokens:We.output_tokens}:{output_tokens:I}}),f("message_stop",{}),t.end();return}let v="",S="",w=[],_=new Me;for await(let A of r.track(m,c,s)){w.push(A),A.type==="response.output_text.delta"&&typeof A.delta=="string"&&(v+=A.delta),A.type==="response.reasoning_text.delta"&&typeof A.delta=="string"&&(S+=A.delta);let I=Ye(A);if(I&&_.add(I),A.type==="error"){let g=A.error,k=g?.type==="invalid_request_error",x=Se(g);x===null&&i(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),ke(t,k?400:502,k?"invalid_request_error":"api_error",x??be(s.id));return}if(t.destroyed)break}if(t.destroyed)return;let h=xe(w);Ge(s,h);let y;try{y=Fn(h),y.length===0&&_.size>0&&(y=Fn({output:_.items()}))}catch(A){let I=de(A,{inferenceId:s.id});I.redacted&&i(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),ke(t,502,"api_error",I.message);return}let C=Be(p,y.length,v);if(C){ke(t,502,"api_error",Ue(c,C));return}let T=[],b=S||Cs(h);b&&T.push({type:"thinking",thinking:b}),(v||y.length===0)&&T.push({type:"text",text:v}),T.push(...y),oe(t,200,{id:u,type:"message",role:"assistant",content:T,model:a,stop_reason:y.length>0?"tool_use":"end_turn",usage:Qt(h)??{input_tokens:0,output_tokens:0}})}function ia(n){Oe(process.stdout,n)}function oa(n){let{clients:e,apiKey:t,identity:r,statusOf:s}=n,i=typeof e=="function"?e:()=>e,o=n.requestLog??ia,a=n.operatorLog??(d=>console.error(d)),u=n.observe,l=new De;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),f=(h,y,C,T,b)=>m?ke(c,h,T,y):G(c,h,y,C,b),v=wn(p.pathname),S=p.pathname.startsWith("/partners/"),w=v||S?{id:ft(),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;w&&(c.setHeader(yr,w.id),c.once("close",()=>{let h=br({turn:w,method:d.method??"",path:p.pathname,res:c});o(kr(h)),u?.(h),As({record:h,ledger:n.ledger??null,req:d})}));let _=()=>_r(p.pathname,w);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){oe(c,200,r?{identity:r,...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===ms?"canonical":p.pathname===Pn?"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 b=n.usage;if(!b){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 A=b.authorize(d),I;try{I=await Ts(d,fs)}catch(x){if(x instanceof xt){f(413,x.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=x=>b.lookup(A,x),k;try{if(h==="canonical"){let x=hs(I),P=await g(x);Xt(P,x),k={requests:P}}else k=await ys(I,g)}catch(x){if(x instanceof Ce){f(x.status,x.message,"invalid_request_error","invalid_request_error");return}throw x}oe(c,200,k);return}if(d.method==="GET"&&p.pathname===ut){let b=await i(d);if(w&&(w.org=b.tenant??null),!b.openRouterModels){f(501,`GET ${ut} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}oe(c,200,await b.openRouterModels());return}if(p.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Pn} and GET ${ut}`,"invalid_request_error","not_found_error");return}let y=await i(d);if(w&&(w.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:ut}),c.end();return}oe(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===Lr){if(!y.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}oe(c,200,await y.listImageModels());return}if(Cr(p.pathname)){if(!y.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 b={clients:y,imageModels:y.supportsImages,stats:l,turn:_(),operatorLog:a};p.pathname===Jt?await Jr(d,c,b):await Hr(d,c,b);return}if(d.method==="GET"&&p.pathname===is){if(!y.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}oe(c,200,await y.listSpeechToTextModels());return}if(ss(p.pathname)){if(!y.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${zt}`,"not_implemented","not_implemented_error");return}let b={clients:y,transcriptionModels:y.supportsTranscription,stats:l,turn:_(),operatorLog:a};await us(d,c,b);return}if(Zr(p.pathname)){if(!y.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${vt}`,"not_implemented","not_implemented_error");return}let b={clients:y,speechModels:y.supportsSpeech,stats:l,turn:_(),operatorLog:a};await rs(d,c,b);return}if(d.method!=="POST"){f(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let C;try{C=await Ts(d)}catch(b){if(b instanceof xt){f(413,b.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let T=Buffer.byteLength(JSON.stringify(C));if(p.pathname==="/v1/responses"){l.request("responses",T,T),await Ko(C,y,gt(y),c,l,_(),a);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",T,T),await Xo(C,y,c,l,_(),d.headers[Ln],a);return}if(p.pathname==="/v1/systemone"){l.request("systemone",T,T),await Yo(C,y,c,l,_(),a);return}if(p.pathname==="/v1/decisions"){l.request("decisions",T,T),await Qo(C,y,c,l,_(),a);return}if(p.pathname==="/v1/messages"){l.request("messages",T,T),await sa(C,y,c,l,_(),a);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",T,T),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 y=String(h instanceof Error?h.message:h);if(!c.headersSent){let b=s?.(h)??null;if(b){b.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${b.operatorDetail}`),f(b.status,y,b.openaiType,b.anthropicType,b.code);return}if(h instanceof Do){let I=Dt(h.code);if(I){let g=h.retryAfterSeconds??(I.status===429?30:void 0);g!==void 0&&c.setHeader("Retry-After",String(g)),f(I.status,mt(I,h.code??void 0),I.openaiType,I.anthropicType,I.code);return}}if(h instanceof qo){let I=qt(h);if(I){let g=I.status===429?30:void 0;g!==void 0&&c.setHeader("Retry-After",String(g)),f(I.status,mt(I,h.status.sessionId?`session ${h.status.sessionId}`:void 0),I.openaiType,I.anthropicType,I.code);return}}if(h instanceof ne){f(502,y,"upstream_error","api_error");return}if(h instanceof we){h.retryable&&c.setHeader("Retry-After","1");let I=de(h,{inferenceId:w?.id??null});I.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}`:pe(h)}`),f(502,I.message,"upstream_error","api_error",h.code);return}if(h instanceof Pe){c.setHeader("Retry-After",String(h.retryAfterSeconds)),f(h.status,y,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}let A=de(h,{inferenceId:w?.id??null});A.redacted&&a(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${h instanceof Error?`${h.name}: ${h.message}`:pe(h)}`),f(500,A.message,"proxy_error","api_error","proxy_error");return}w&&(w.streamError=!0);let C=h instanceof we?h.code:null,T=de(h,{inferenceId:w?.id??null});T.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}`:pe(h)}`),c.destroyed||(m?c.write(`event: error
62
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:T.message}})}
63
-
64
- `):c.write(`data: ${JSON.stringify({error:{message:T.message,type:"upstream_error",code:C}})}
65
-
66
- `)),c.end()})}}function Hl(n){let{clients:e,apiKey:t}=n,r=No(oa(n)),s=Ir(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),i=_n(r,{resolver:Ps(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),o=r.close.bind(r);return r.close=(a=>(s.close(),i(),o(a))),ar(r,{clients:e,apiKey:t}),r}$();var Ee=(n,e)=>Object.assign(new Error(e),{status:n}),la='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Un=(n,e,t)=>new Z(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),qn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof J?Ee(404,t.message):t}};async function Fs(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ee(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${la}`);if(s==="transcription")throw Ee(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ee(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(m){throw m instanceof J?Ee(404,m.message):m}if(!p)throw Ee(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(m){throw m instanceof J?Ee(404,m.message):m}if(p!=="stt")throw Ee(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let i=await qn(n,t.stt),o=await qn(n,e),a=await qn(n,t.tts),u=await n.openAudioOn(i,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,da({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 Z?Un("stt",t.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Ns(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var At=class extends Error{};async function*da(n,e,t,r){let{clients:s,chatHandle:i,ttsHandle:o,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,f=null,v=null,S=[],w=null,_=new Promise((k,x)=>{t&&t.addEventListener("abort",()=>x(new At),{once:!0})}),h=()=>m||t?.aborted===!0,y=async k=>{if(h())return;let x;try{x=await s.createResponseOn(o,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:k}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(O){throw O instanceof Z?Un("tts",u.tts,O):O}let P=x[Symbol.asyncIterator]();v=P;try{for(;;){let O=P.next(),q;try{q=await Promise.race([O,_])}catch(L){if(O.catch(()=>{}),L instanceof At)return;throw L}if(q.done)return;let M=q.value;if(M.type==="error"){let L=M.error&&typeof M.error.message=="string"?M.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${L}`)}if(M.type==="response.completed")return}}finally{v===P&&(v=null)}},C=async()=>{for(;S.length>0&&!h();){let k=S.shift();await y(k)}},T=k=>{if(k===""||h()||(S.push(k),w!==null))return;let x=C();w=x,x.then(()=>{w===x&&(w=null)},P=>{w===x&&(w=null),f??=P})},b=()=>{m=!0,S.length=0;let k=v;if(v=null,k){let x=k.return?.();x&&x.catch(()=>{})}},A=async()=>{for(;S.length>0||w!==null;){let k=w;if(k===null){await y(S.shift());continue}await k}},I=p?new ot({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},k=>T(k)):null,g=null;try{let k;try{k=await s.createResponseOn(i,d)}catch(P){throw P instanceof Z?Un("chat",a,P):P}let x=k[Symbol.asyncIterator]();try{for(;;){let P=x.next(),O;try{O=await Promise.race([P,_])}catch(L){if(P.catch(()=>{}),L instanceof At)break;throw L}if(O.done)break;let q=O.value;if(h())return;let M=q;if(M.type==="error"){yield q;return}if(M.type==="response.output_text.delta"&&typeof M.delta=="string"){yield q,I?.push(M.delta);continue}if(M.type==="response.function_call_arguments.delta"){I?.flush(),yield q;continue}if(M.type==="response.completed"){g=q.response;continue}}}finally{Promise.resolve(x.return?.()).catch(()=>{})}I?.flush(),I?.dispose(),p&&await A(),g!==null&&(yield{type:"response.completed",response:g})}finally{I?.dispose(),b();try{if(f instanceof Z)throw f}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function pa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function ma(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}function od(n){let e=new URL(n.url??"/","http://localhost").searchParams.get("session"),t=n.headers?.["x-urun-session"],r=(e??(typeof t=="string"?t:t?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var fa='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ha(n,e,t,r,s){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let i;try{i=await n.supportsAudio(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(!i){let m=null;if(n.realtimeCompanionsFor)try{m=await n.realtimeCompanionsFor(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(m!==null)return await Fs(n,e,m,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(m){throw m instanceof J?ce(404,m.message):m}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let m;try{m=await n.transcriptStreamFor(e)}catch(f){throw f instanceof J?ce(404,f.message):f}if(m!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${fa}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let a;try{a=n.dedicatedSessionHandle?await n.dedicatedSessionHandle(e):await n.sessionHandle(e)}catch(m){throw m instanceof ye?ce(503,m.message):m}let u=n.realtimeBillingIdentityFor?await n.realtimeBillingIdentityFor(e):null,l=`conn_${ca()}`,c={audio:await n.openAudioOn(a,t,l,s).catch(m=>{throw n.releaseSessionHandle?.(a),m})},p={clients:{createResponse:async m=>await n.createResponseOn(a,m,l)},voice:i,audioSession:c};return n.openVideoOn&&(p.video=()=>n.openVideoOn(a,t)),o&&(p.turns=m=>n.openTurnsOn(a,m)),r==="transcription"&&(p.intent="transcription"),n.releaseSessionHandle&&(p.release=()=>n.releaseSessionHandle(a)),n.endDedicatedSession&&(p.endSession=()=>n.endDedicatedSession(a)),n.onSessionEnd&&(p.onSessionEnd=m=>n.onSessionEnd(a,m)),e!==void 0&&(p.model=e),u!==null&&(p.catalog=u),p}function Ps(n,e,t){let r=Ns(n,t);return{resolve:async(s,i,o)=>{if(e!==void 0){let a=s.headers.authorization,u=typeof a=="string"?a.trim():"",l=u.startsWith("Bearer ")?u.slice(7).trim():"";if(l===""||l!==e)throw ce(401,"invalid local proxy api key")}return ha(r,pa(s),i,ma(s),o)}}}export{Tt as a,ar as b,va as c,ft as d,ur as e,Hs as f,Ia as g,Ea as h,Ri as i,Ir as j,pt as k,yn as l,_n as m,Ns as n,pa as o,ma as p,od as q,ha as r,Ps as s,ms as t,ne as u,tl as v,Pn as w,ul as x,ll as y,dl as z,cl as A,pl as B,As as C,Ls as D,oa as E,Hl as F};