@urun-sh/openai 0.6.1 → 0.6.3

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.
@@ -0,0 +1,62 @@
1
+ import{c as gn,d as L,e as pe,i as Mt}from"./chunk-TMQJY56F.js";import{a as hn,c as yn,d as be,e as st,f as Y,g as _n,h as wn,i as vn,j as bn,k as xn,l as kn,m as Rn,n as Sn,r as En,t as In,u as An,v as On,w as Tn,x as Pn}from"./chunk-3JWYIKHM.js";import{a as Ct}from"./chunk-6M5JK4YC.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{randomUUID as Yr}from"crypto";import{WebSocketServer as Xr}from"ws";var Qr=256,it=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Qr;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Zr="local",qe=t=>t.slice(0,120),at=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),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 L){this.ws.close(yn,qe(e.message));return}if(e instanceof pe){this.ws.close(st,qe(e.message));return}if(e instanceof Y){this.ws.close(e.closeCode,qe(e.message));return}this.ws.close(be,qe(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=_n(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new Y(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Sn(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=In(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:En);return}this.transcript.push(...An(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new Y("setup may only be sent once, as the first client message");let n=xn(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new Y("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",st);if(s.model!==n.model)throw new Y(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new Y("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(n.model),this.proxyHandle!==s.proxyHandle)throw new Y(`sessionResumption.handle named pooled session "${s.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`,st);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(bn(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[wn]=vn(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new Y("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new Y("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",be);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Tn(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new Y("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new Y("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",be);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new Y(`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 Y("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new Y("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(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=Yr();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(kn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Rn(e.timeLeftMs)),this.ws.close(be,qe(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;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}),o,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new Y(`upstream error: ${JSON.stringify(d)}`,be);if(d.type==="response.completed"){o=d.response,s=!0;continue}let c=On(d);c&&this.send(c)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new Y("upstream produced no response.completed event",be);let{messages:i,assistantItems:a}=Pn(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},xe=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function eo(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new xe(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(n&&i!==void 0&&i!=="")throw new xe(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&&n)throw new xe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Cn(t,e){let n=e.authenticate!==void 0;if(n&&(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(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Xr({noServer:!0}),o=new it;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===hn&&(a.on("error",()=>{}),(async()=>{let c=eo(i,d,n),l;if(e.authenticate)l=await e.authenticate(c,i);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new xe(401,"invalid local proxy api key");l={clients:e.clients,scope:Zr}}r.handleUpgrade(i,a,u,v=>{new at(v,l,o)})})().catch(c=>{let l=502;(c instanceof xe||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(l=c.status);let v=l===401?"Unauthorized":l===403?"Forbidden":l===502?"Bad Gateway":"Internal Server Error",p=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${l} ${v}\r
2
+ Connection: close\r
3
+ \r
4
+ ${p}\r
5
+ `),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}function Hi(t,e,n=new it){new at(t,e,n)}A();import no from"os";import ro from"path";import{fileURLToPath as oo}from"url";import{format as so}from"util";var Mn="0.6.3";var Ln=4141,io=Mn,Zi={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ao(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function ea(t,e,n){let r={...t,...ao(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,delete r.URUN_SESSION_TOKEN_SECRET,r}function ta(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(c=>c==="-m"||c==="--model"||c.startsWith("--model=")),a=n[0]==="exec",u=s.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...d]}function na(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ra(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function oa(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=oo(new URL("../pi-extension/standalone.cjs",e));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function Un(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function sa(t){if(t[0]!=="--port")return null;let e=Un(t[1]);return t.splice(0,2),e}function ia(t){let e=t.indexOf("--port");if(e===-1)return Ln;let n=Un(t[e+1]);return t.splice(e,2),n}function aa(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function $t(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function ua(t){let e=uo($t(t,"URUN_BASE_URL")),n=$t(t,"URUN_ORG_ID"),r=$t(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?$n(s,"URUN_API_URL"):gn,a=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"jwt",jwt:u}};let d=(t.URUN_API_KEY??"").trim();if(d){let c=(t.URUN_GATEWAY_URL??"").trim(),l=c?$n(c):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function uo(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function $n(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function da(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:io}}function co(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var lo=250;async function po(t,e=lo){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:a,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:o,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var Nn=2e3;async function fo(t,e=Nn){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ca(t,e,n=Ln,r=Nn){if(t!=null)return{mode:"spawn",port:t};let o=await po(n);if(o!==null&&co(o,e)){let s=await fo(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function la(t,e=no.homedir()){return ro.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Lt=["log","info","warn","error","debug","trace"];function pa(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(a,...u)=>t.write(a,...u);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Lt.map(a=>[a,n[a]]));for(let a of Lt)n[a]=(...u)=>{t.write(`${so(...u)}
6
+ `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let a of Lt)n[a]=i[a]}}var mo=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bn(t){let e=t?.code;return typeof e=="string"&&mo.has(e)}function ye(t,e){try{return t.write(e),!0}catch(n){if(Bn(n))return!1;throw n}}function fa(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Bn(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
7
+ `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ma(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
8
+ `)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
9
+ `)}catch(o){try{t.appendSync(t.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
10
+ `)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function ga(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}A();import{SessionFailedError as wo}from"@urun-sh/core";A();import{randomUUID as go}from"crypto";function R(t){return`${t}_${go().replace(/-/g,"").slice(0,24)}`}var ut=4*1024*1024,Ut=8*1024*1024,dt=512,ct=20*1024*1024;function G(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Pe(t,e){return{type:"server_error",code:t,message:e}}function U(t){return{type:"error",event_id:R("event"),error:t}}function Nt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var I=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},ho={model:!0,instructions:!0,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,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},yo={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},_o={format:!0,voice:!0,speed:!0};function Fn(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new I(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function De(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new I("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in ho));if(o.length>0)throw new I(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new I("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new I("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new I("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new I(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new I('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new I("voice must be a string or null","voice");if(!n.voice)throw new I("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new I(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new I("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new I(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new I("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new I("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new I("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new I("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new I(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new I("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(!a||typeof a!="object"||Array.isArray(a))throw new I("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new I(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new I("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(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new I("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in yo))throw new I(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Fn(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=De({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let c=De({turn_detection:d.turn_detection},s,n);s.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new I("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in _o))throw new I(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Fn(d.format,"audio.output.format"),d.speed!==void 0)throw new I("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 s.voice;else{if(typeof d.voice!="string")throw new I("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new I("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function lt(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Bt(t,e){let n=t;if(!n||typeof n!="object")throw new I("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new I("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:R("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new I('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new I("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new I("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new I(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new I("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new I("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new I(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:R("item"),type:"message",role:r,content:o}}throw new I(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Ft(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var vo=1001,bo=1011,qn=t=>t.slice(0,120),xo=/^[A-Za-z0-9+/=]*$/,ko=2;function Ro(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ko)return!1;return!0}var je=class{id=R("conn");ws;binding;onClosed;config=Nt();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.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()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(U(Pe("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:R("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},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 n=this.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=R("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:s,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.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(G("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>ut){this.fail(G("frame_too_large",`frame exceeds the ${ut}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(G("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(G("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(U({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Pe(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=De(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:R("event"),session:lt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Bt(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(U(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:R("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(U(G("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(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(U(G("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:R("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(U(G("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!xo.test(e.audio)){this.send(U(G("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>ct){this.send(U(G("buffer_full",`uncommitted input audio exceeds the ${ct}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,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.takeTurnTranscript()===null){this.send(U(G("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(U(G("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":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(U(G("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(U(G("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(U({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(U(G("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(S=>S!=="text"&&S!=="audio")){this.send(U(G("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(U(G("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=R("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=Ft(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,c=n.max_output_tokens??this.config.maxOutputTokens,l=c==="inf"||c===void 0?void 0:c,v=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,w={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...l!==void 0?{max_output_tokens:l}:{},...v!==void 0?{tools:v}:{},...p!==void 0?{tool_choice:p}:{}};for(let S of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(S);this.inFlight=(async()=>{let S=[],k=E=>{this.responseFlushed?this.send(E):S.push(E)},f=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:R("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(o,"in_progress")});for(let E of S)this.send(E);S.length=0,this.responseFlushed=!0}},g={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},h=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(w,r)}catch(m){this.upstreamTurnFault(m,o);return}try{for await(let m of E){if(this.cancelled)break;let y=m;if(y.type==="error"){let b=this.upstreamErrorBody(y);this.responseFlushed?this.send(U(b)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(o,b)});return}if(y.type==="response.output_text.delta"&&typeof y.delta=="string"){f(),g.messageOpen||(this.beginMessageItem(o,g.nextOutputIndex++),g.messageOpen=!0),k({type:"response.output_text.delta",event_id:R("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:y.delta}),g.messageText+=y.delta;continue}if(y.type==="response.function_call_arguments.delta"){f();let b=typeof y.delta=="string"?y.delta:"",M=typeof y.call_id=="string"&&y.call_id.length>0?y.call_id:`${o}_fc_${g.nextOutputIndex}`,_=g.tools.get(M);if(!_){let x=typeof y.name=="string"&&y.name.length>0?y.name:void 0;_={outputIndex:g.nextOutputIndex++,name:x,args:""},g.tools.set(M,_),k({type:"response.output_item.added",event_id:R("event"),response_id:o,output_index:_.outputIndex,item:{id:M,object:"realtime.item",type:"function_call",call_id:M,name:x??"",arguments:"",status:"in_progress"}})}typeof y.name=="string"&&y.name.length>0&&(_.name=y.name),_.args+=b,k({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:M,response_id:o,output_index:_.outputIndex,call_id:M,name:_.name??"",delta:b});continue}if(y.type==="response.completed"){h=y.response??null;continue}}}catch(m){this.upstreamTurnFault(m,o);return}if(this.cancelled)return;this.closeOpenItems(o,g,s),f(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(o,s,h)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Ro(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(U({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:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:R("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Pe("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof pe){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof wo&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Pe(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(U(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(U(G("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:R("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>dt&&(this.items.shift(),this.send(U({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${dt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Ut){this.ws.close(vo,qn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(U(e)),this.ws.close(bo,qn(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>Dn(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Dn(this.id,e)}}},qt=[];function Dn(t,e){qt.push({id:t,reason:e}),qt.length>256&&qt.shift()}A();import{SessionFailedError as Ao}from"@urun-sh/core";A();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as So}from"@urun-sh/core";var Eo={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Io={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; 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:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session"};function Dt(t,e){let n=Io[t.code];return e?`${n} (${e})`:n}function pt(t){if(t==null)return null;let e=Eo[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function ft(t){if(t.kind==="create-failed")return pt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=So;return pt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as Oo}from"ws";var Ht="/v1/realtime",To=t=>t.slice(0,120);function Po(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
11
+ Connection: close\r
12
+ Content-Type: text/plain\r
13
+ \r
14
+ ${To(n)}\r
15
+ `),t.destroy()}function Co(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
16
+ `}function Mo(t){ye(process.stdout,t)}function $o(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function jt(t){return t.audioSession?.audio.sessionId??void 0}function Gt(t,e){let n=new Oo({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Ht)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=R("rtup"),d=$o(o),c=m=>{(e.log??Mo)(Co(m))};c({stage:"accept",conn:u,model:d}),s.resume();let l=new AbortController,v=null,p=m=>{v??=m,l.abort(new Error(v))},w=()=>p("client socket closed"),S=()=>p("client socket closed (half-close)"),k=m=>p(`client socket error: ${m.message}`);s.once("close",w),s.once("end",S),s.once("error",k);let f=()=>{s.removeListener("close",w),s.removeListener("end",S),s.removeListener("error",k)},g=m=>{c({stage:"close",conn:u,model:d,...m})},h=m=>{let y=m,b=y.session!=null&&typeof y.session.sendResponseCreate=="function",M=y.clients!=null&&typeof y.clients.createResponse=="function";if(!b&&!M)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((_,x)=>{n.handleUpgrade(o,s,i,P=>{try{new je({ws:P,binding:m,onClosed:(N,z)=>{g({while:"live",reason:z.reason})}}),c({stage:"admit",conn:u,model:d,...jt(m)===void 0?{}:{session:jt(m)}}),_()}catch(N){x(N)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,l.signal).then(async m=>{if(l.signal.aborted){f();let y=jt(m);try{await m.release?.()}catch(b){g({while:"queued",...y===void 0?{}:{session:y},reason:v??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}g({while:"queued",...y===void 0?{}:{session:y},reason:v??"client socket closed",released:!0}),s.destroy();return}f(),await h(m)}).catch(m=>{let y=m instanceof Ao?ft(m):null,b=null;if(m!==null&&typeof m=="object"&&"status"in m){let x=m.status;typeof x=="number"&&(b=x)}let M=b??y?.status??502,_=m instanceof Error?m.message:String(m);g({while:"queued",...l.signal.aborted?{reason:v??"client socket closed"}:{reason:_,status:M}}),s.destroyed||Po(s,M,_)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}A();A();A();import{createServer as mi}from"http";A();import{WebSocketServer as Wo,WebSocket as We}from"ws";A();A();import{randomUUID as Lo}from"crypto";var jn="Inference-Id";function He(){return Lo()}function Jt(t){return t==="/v1"||t.startsWith("/v1/")}function Hn(t,e){if(!Jt(t)||e===null)throw new Error(`no inference turn for ${t}: 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 Ge(t){return`resp_${t}`}function Gn(t){return`chatcmpl-${t}`}function Jn(t){return`msg_${t}`}function oe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Vn(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function Wn(t){return`${JSON.stringify(t)}
17
+ `}var Uo=256,No=128;function te(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,No)}var ke=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Uo?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+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:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.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}}}},Bo=256;function Fo(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Re=class extends Error{},Ce=class{conversations=new Map;thread(e,n){let r=Fo(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Re(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=Bo)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Kn=new WeakMap;function Je(t){let e=Kn.get(t);return e||(e=new Ce,Kn.set(t,e)),e}function Me(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ae(t){return t.find(e=>e.type==="response.completed")?.response??null}function $e(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var _e=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},qo=["<tool_call>","<function="];function Do(t){return qo.find(e=>t.includes(e))}function Se(t,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 "${t}" (see catalog parser_defaults)`}function Ee(t,e,n){if(!(!t||e>0))return Do(n)}function Le(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function jo(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Vt(t,e){let n=jo(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var se=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ue(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Re?new se(n.message,"previous_response_not_found",400,"previous_response_id"):new se(String(n instanceof Error?n.message:n),"invalid_input")}}function zn(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Wt(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new se("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},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}:{},...zn(e)!==void 0?{response_format:zn(e)}:{}},o)}async function Ve(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ue(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=te(e);o.model(d);let c=Array.isArray(e.tools)&&e.tools.length>0,l=t.turn,v=await Wt(n,e,s,!0,l?oe(l):void 0);return{responseId:i,events:Vo({events:v,conversation:s,responseId:i,modelKey:d,requestHadTools:c,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Ho(t,e){let n=[...t].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?Jo(o[i++],u):u),...Go(r,n)]}function Go(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let c=d;return c.type==="message"?!n:c.type==="reasoning"?!r:c.type==="function_call"?!a&&!u.has(o(c)):!0})}function Jo(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*Vo(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,c=[],l=O=>O.response&&typeof O.response=="object"?{...O,response:{...O.response,id:r}}:O,v=`item_${r.slice(5)}`,p=!1,w=!1,S=0;function*k(){p||(p=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let f=[],g=(O,$)=>{f.push({output_index:O,item:$})},h=!1,E=0,m="",y=0,b="";function*M(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:m,output_index:E,content_index:0,text:b};let O={id:m,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:E,item:O},g(E,O),b=""}let _=!1,x=0,P="",N=0,z="",ee="";function*ie(O){if(!_)return;_=!1,yield{type:"response.output_text.done",item_id:P,output_index:x,content_index:0,text:z},yield{type:"response.content_part.done",item_id:P,output_index:x,content_index:0,part:{type:"output_text",text:z}};let $={id:P,type:"message",role:"assistant",status:O,content:[{type:"output_text",text:z}]};yield{type:"response.output_item.done",output_index:x,item:$},g(x,$),z=""}let ge=new _e,q=null,D=-1;function*Q(O){if(!q)return;let $=q;q=null,yield{type:"response.function_call_arguments.done",item_id:$.fcId,output_index:$.outputIndex,arguments:$.args};let W={id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:$.args,status:O};yield{type:"response.output_item.done",output_index:$.outputIndex,item:W},g($.outputIndex,W)}let ve=!1;for await(let O of d.track(e,o,t.turn)){c.push(O);let $=String(O.type??"");if($==="response.created"||$==="response.in_progress"){p=!0,yield l(O);continue}if($==="response.output_item.added"){w=!0,yield l(O);continue}if($==="response.reasoning_text.delta"&&!w){yield*k(),h||(h=!0,E=S++,y+=1,m=y===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${y}`,yield{type:"response.output_item.added",output_index:E,item:{id:m,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(O.delta??""),yield{type:"response.reasoning_text.delta",item_id:m,output_index:E,content_index:0,delta:O.delta};continue}if($==="response.output_text.delta"&&!w){yield*k(),yield*M(),_||(_=!0,x=S++,N+=1,P=N===1?v:`${v}_${N}`,yield{type:"response.output_item.added",output_index:x,item:{id:P,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:P,output_index:x,content_index:0,part:{type:"output_text",text:""}}),z+=String(O.delta??""),ee+=String(O.delta??""),yield{type:$,item_id:P,output_index:x,content_index:0,delta:O.delta};continue}let W=w?null:$e(O);if(W){if(yield*k(),yield*M(),yield*ie("completed"),ge.add(W),W.tool_index!==D){yield*Q("completed"),D=W.tool_index;let le=S++;q={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:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:"",status:"in_progress"}}}q&&(W.call_id&&(q.callId=W.call_id),W.name&&(q.name=W.name),q.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:q.fcId,output_index:q.outputIndex,delta:W.delta});continue}if($==="response.completed"&&!w){let le=Me(O.response),B=Ee(s,ge.size+le.length,ee);if(B){ve=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Se(o,B)}};break}if(yield*M(),yield*ie("completed"),yield*Q("completed"),ge.size===0)for(let he of le){let Te=S++,ot=he.id??he.call_id??`fc_${Te}`,Pt=he.arguments??"",fn={id:ot,type:"function_call",call_id:he.call_id??ot,name:he.name??""};yield{type:"response.output_item.added",output_index:Te,item:{...fn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ot,output_index:Te,delta:Pt},yield{type:"response.function_call_arguments.done",item_id:ot,output_index:Te,arguments:Pt};let mn={...fn,arguments:Pt,status:"completed"};yield{type:"response.output_item.done",output_index:Te,item:mn},g(Te,mn)}let Z=Ho(f,O.response);yield Z.length>0?l({...O,response:{...O.response,output:Z}}):l(O);continue}yield l(O)}if(yield*M(),yield*ie("incomplete"),yield*Q("incomplete"),i&&!ve){let O=ae(c);u.remember(r,n,Vt(O,Le(c,O)),a)}}var Ko="/v1/responses",zo=64*1024*1024,Yo=8*1024*1024,Xo=16,Yn=32,Xn=3600*1e3,Qo=/^[A-Za-z0-9._-]{1,256}$/;function ne(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Zo=ne(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 Yt(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function es(t){for(;t.bufferedAmount>Yo&&t.readyState===We.OPEN;){let{promise:e,resolve:n}=Yt();setTimeout(n,5),await e}}var Kt=class extends Ce{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Re))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},zt=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Kt(Je(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ne(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Xn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Xn).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ne(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(ne(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(ne(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ne(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ne(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 o){this.sendFrame(ne(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Qo.test(o.stream_id)){this.sendFrame(Zo);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Yn){this.sendFrame(ne(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Yn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await Ve({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ge(He())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==We.OPEN)break;this.send(i,n),await es(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=Ge(He());try{let o=Ue(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof se)return ne(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof L)return ne(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof pe)return ne(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?ne(o.status,{type:o.openaiType,message:r},n):ne(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Xo;){let{promise:e,resolve:n}=Yt();this.waiters.push(n),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,n){if(this.closed||this.ws.readyState!==We.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==We.OPEN||this.ws.send(JSON.stringify(e))}};function mt(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
18
+ `;t.end(`HTTP/1.1 ${e} ${r}\r
19
+ Connection: close\r
20
+ Content-Type: text/plain; charset=utf-8\r
21
+ Content-Length: ${Buffer.byteLength(o)}\r
22
+ \r
23
+ ${o}`)}function Qn(t,e){let n=new Wo({noServer:!0,maxPayload:zo}),r=new ke,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(c,l,v)=>{let p;try{p=new URL(c.url??"/","http://localhost")}catch{mt(l,400,"malformed upgrade URL");return}if(l.on("error",()=>l.destroy()),l.on("close",()=>i.delete(l)),p.pathname!==Ko){i.add(l);return}s.add(l);let w=!1;(async()=>{if(e.apiKey&&(c.headers.authorization??"")!==`Bearer ${e.apiKey}`){mt(l,401,"invalid local proxy api key");return}let S;try{S=await a(c)}catch(k){let f=e.statusOf?.(k)??null;mt(l,f?.status??500,"upstream resolver rejected the connection");return}u||l.destroyed||(w=!0,n.handleUpgrade(c,l,v,k=>{s.delete(l),o.add(k),k.on("close",()=>o.delete(k));try{new zt(k,S,r,e.statusOf)}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!w&&!l.destroyed&&mt(l,500,"responses websocket upgrade failed")}).finally(()=>s.delete(l))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:c,resolve:l}=Yt();if(u)return l(),c;u=!0,t.off("upgrade",d);for(let p of s)p.destroy();s.clear();for(let p of i)p.destroy();i.clear();for(let p of o)p.close(1001,"server shutting down");let v=setTimeout(()=>{for(let p of o)p.readyState!==We.CLOSED&&p.terminate()},2e3);return v.unref?.(),n.close(()=>{clearTimeout(v),l()}),c}}}A();A();var X=class extends Error{};async function gt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new X(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new X(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function ht(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new X(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,c]of Object.entries(t.headers))if(typeof c=="string")i.set(d,c);else if(Array.isArray(c))for(let l of c)i.append(d,l);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof X?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Zn="/v1/images/generations",yt="/v1/images/edits";function er(t){return t===Zn||t===yt}var tr="/v1/images/models";async function nr(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.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(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var C=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ts=16*1024*1024,rr=64*1024*1024;function or(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function Ke(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function sr(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let l of o){if(l.type==="error"){let v=l.error??{};throw new C(502,`image upstream error: ${String(v.message??"upstream reported an error")}`)}if(l.type==="response.completed"){s=l.response??null;break}}if(s===null)throw new C(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new C(502,`image upstream returned ${Array.isArray(i)?i.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 a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(or(d)===null)throw new C(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function ir(t){return t instanceof C?t:t instanceof L?new C(404,t.message):new C(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function ar(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Ke(r,new C(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function ur(t,e){t&&(t.outputUnits=e.images.length)}function dr(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var ns={model:!0,prompt:!0,response_format:!0,n:!0};async function cr(t,e,n){let r=n.maxBodyBytes??rr;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${Zn}`);let o;try{o=JSON.parse((await gt(t,r)).toString("utf8")||"{}")}catch(l){throw l instanceof X?new C(413,l.message):new C(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new C(400,"request body must be a JSON object");let s=o;for(let l of Object.keys(s))if(!ns[l])throw new C(400,`request field "${l}" 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.`,l);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new C(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new C(400,"model must be a string","model");await nr(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new C(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new C(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(n.stats?.request("images_generations",i.length,i.length),!await ar(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:i}];try{let l=await sr(n.clients,a,c,n.turn?oe(n.turn):void 0);ur(n.turn,l),dr(e,l)}catch(l){throw ir(l)}}catch(o){if(o instanceof X){Ke(e,new C(413,o.message));return}if(o instanceof C){Ke(e,o);return}throw o}}var rs={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function lr(t,e,n){let r=n.maxBodyBytes??rr,o=n.maxImagePartBytes??ts;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${yt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new C(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await ht(t,r)}catch(p){throw p instanceof X?new C(413,p.message):new C(400,String(p instanceof Error?p.message:p))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new C(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new C(400,"model must be a string field","model");let d=u===null?void 0:u;await nr(n.turn,n.clients,d);let c=i.get("response_format")??"b64_json";if(c!=="b64_json")throw new C(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 p of i.keys())if(!rs[p])throw new C(400,`form field "${p}" 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[]).`,p);let l=[];for(let p of["image","image[]"])for(let w of i.getAll(p)){if(!(w instanceof File))throw new C(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(w.size>o)throw new C(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let S=new Uint8Array(await w.arrayBuffer()),k=or(S);if(k===null)throw new C(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);l.push({bytes:S,mime:k})}if(l.length===0)throw new C(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await ar(n.imageModels,d,"edit",e))return;let v=[{type:"input_text",text:a}];for(let{bytes:p,mime:w}of l)v.push({type:"input_image",image_url:`data:${w};base64,${Buffer.from(p).toString("base64")}`});try{let p=await sr(n.clients,d,v,n.turn?oe(n.turn):void 0);ur(n.turn,p),dr(e,p)}catch(p){throw ir(p)}}catch(s){if(s instanceof X){Ke(e,new C(413,s.message));return}if(s instanceof C){Ke(e,s);return}throw s}}A();var Ye="/v1/audio/speech";function hr(t){return t===Ye}var pr=4096,os=18e4,ss=5e3,is=64*1024*1024,fr=8,mr=5,wt="voice_applied",as="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Xt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.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 T{constructor(e){super(502,e)}};async function us(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.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(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function ds(t,e){t&&(t.outputUnits=e/(24e3*2))}var cs=2;function ls(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>cs)return!1;return!0}function ps(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var gr=new WeakMap,_t=new WeakMap;function fs(t,e){let n=_t.get(t)??0;if(n>=fr)throw new T(503,`this model's speech queue is full \u2014 ${fr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${mr}s`,void 0,mr);_t.set(t,n+1);let r=gr.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return gr.set(t,s),(async()=>{await r;try{return await e()}finally{_t.set(t,(_t.get(t)??1)-1),o()}})()}async function ms(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new T(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 t.evictSpeechSession(e)}catch(i){if(!(i instanceof pe))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function ze(t){return t instanceof T?t:t instanceof L?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function gs(t,e,n,r,o,s,i){return fs(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,c=!1,l=!1,v,p=new Promise(E=>{v=E}),w=()=>{c&&!l&&d>=o.quietRunFrames&&(l=!0,v())},S=e.onOutputAudio(E=>{let m=Buffer.from(E,"base64");if(m.byteLength===0)return;let y=ls(m);if(!u){if(y)return;u=!0}a.push(m),d=y?d+1:0,w()}),k=null,f,g,h;try{h=(await t.createResponseOn(n,{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 m=new Promise(_=>{g=setTimeout(_,s.capMs)}),y=!1;for(;;){let _=h.next(),x=await Promise.race([_,m]);if(x===void 0){y=!0,_.catch(()=>{});break}if(x.done)break;let P=x.value;if(P.type==="error"){let N=P.error??{};throw await h.return?.(),new T(502,`speech upstream error: ${String(N.message??"upstream reported an error")}`)}if(P.type==="response.completed"){k=P.response??null,c=!0,w(),await h.return?.();break}}if(clearTimeout(g),y)throw new T(504,`the speech turn produced no terminal event within ${s.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(k===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let b=!1;if(await Promise.race([p,new Promise(_=>{f=setTimeout(()=>{b=!0,_()},o.capMs)})]),f!==void 0&&clearTimeout(f),r.voice!==void 0){let _=k[wt];if(typeof _!="string"||_!==r.voice){let x=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof _=="string"?`${wt} ${JSON.stringify(_)}`:`no ${wt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw l?new vt(x):new T(502,x)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(b&&!l&&d<1)throw new T(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);let M=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(M),completed:k}}catch(E){throw E instanceof vt||await ms(t,n,h,s.returnBoundMs),E}finally{f!==void 0&&clearTimeout(f),g!==void 0&&clearTimeout(g),S()}})}async function hs(t,e,n){let r;try{r=await t(e)}catch(o){throw ze(o)}return r?!0:(Xt(n,new T(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 ys={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},_s="wav, pcm";async function yr(t,e,n){let r=n.maxBodyBytes??is,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Ye}`);let i;try{i=JSON.parse((await gt(t,r)).toString("utf8")||"{}")}catch(h){throw h instanceof X?new T(413,h.message):new T(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new T(400,"request body must be a JSON object");let a=i;for(let h of Object.keys(a))if(!ys[h])throw new T(400,`request field "${h}" 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.`,h);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(u.length>pr)throw new T(400,`input is ${u.length} chars \u2014 over the ${pr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new T(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new T(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new T(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 ${Ye} against a stale copy of the list`);let l;try{l=await n.clients.speechVoices(d)}catch(h){throw ze(h)}if(l.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${l.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let v=typeof c=="string"?c:void 0;if(v!==void 0&&l.published.length>0&&!l.published.includes(v))throw new T(400,`voice ${JSON.stringify(v)} is not one of the voices this model publishes \u2014 accepted voices: ${l.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new T(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${_s} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new T(400,"stream_format, when present, must be a string","stream_format");let w=a.speed;if(w!==void 0){if(typeof w!="number"||!Number.isFinite(w))throw new T(400,"speed, when present, must be a number","speed");if(w!==1)throw new T(400,`speed=${JSON.stringify(w)} 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=a.instructions;if(S!==void 0){if(typeof S!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new T(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 us(n.turn,n.clients,d);let k=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",k,k),!await hs(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new T(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 n.clients.speechSessionHandle!="function")throw new T(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 n.clients.evictSpeechSession!="function")throw new T(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(s())return;let f;try{f=await n.clients.speechSessionHandle(d)}catch(h){throw ze(h)}let g;try{g=await n.clients.openAudioOn(f)}catch(h){throw ze(h)}n.turn&&(n.turn.sessionId=g.sessionId);try{let h=await gs(n.clients,g,f,{model:d,text:u,...v!==void 0?{voice:v}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??os,returnBoundMs:n.turnReturnBoundMs??ss},s);if(h===null||s())return;if(ds(n.turn,h.pcm.byteLength),e.statusCode=200,v===void 0){let E=h.completed[wt];typeof E=="string"&&e.setHeader(as,E)}p==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([ps(h.pcm.byteLength),h.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(h.pcm))}catch(h){throw ze(h)}}catch(i){if(i instanceof X){Xt(e,new T(413,i.message));return}if(i instanceof T){Xt(e,i);return}throw i}}A();var bt="/v1/audio/transcriptions";function _r(t){return t===bt}var wr="/v1/audio/models",ws=16*1024*1024,vs=64*1024*1024,F=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Qt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function vr(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function bs(t){if(!vr(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,d=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,c=t[a+14]|t[a+15]<<8;n={sampleRate:d,channels:u,bitsPerSample:c}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function xs(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.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(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function ks(t,e){t&&(t.outputUnits=e.seconds)}async function Rs(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],a=null;for await(let u of s){if(i.push(u),u.type==="error"){let d=u.error??{},c=typeof d.type=="string"?d.type:"upstream_error",l=String(d.message??"upstream reported an error");throw new F(c==="invalid_request_error"?400:502,`transcription upstream error: ${l}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new F(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Le(i,a)}function br(t){return t instanceof F?t:t instanceof L?new F(404,t.message):new F(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ss(t,e,n){let r;try{r=await t(e)}catch(o){throw br(o)}return r?!0:(Qt(n,new F(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 Es=new Set(["file","model","language","response_format"]);async function xr(t,e,n){let r=n.maxBodyBytes??vs,o=n.maxAudioPartBytes??ws;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${bt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await ht(t,r)}catch(f){throw f instanceof X?new F(413,f.message):new F(400,String(f instanceof Error?f.message:f))}let a=new Map;for(let f of i.keys()){if(!Es.has(f))throw new F(400,`form field "${f}" 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.`,f);a.set(f,(a.get(f)??0)+1)}for(let[f,g]of a)if(g>1)throw new F(400,`form field "${f}" appears ${g} 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`,f);let u=i.get("model");if(u!==null&&typeof u!="string")throw new F(400,"model must be a string field","model");let d=u===null?void 0:u,c=i.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new F(400,"language, when present, must be a non-empty string","language");let l=c===null?void 0:c,v=i.get("response_format")??"json";if(v!=="json")throw new F(400,`response_format ${JSON.stringify(v)} 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 p=i.get("file");if(!(p instanceof File))throw new F(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(p.size>o)throw new F(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let w=new Uint8Array(await p.arrayBuffer());if(!vr(w))throw new F(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=bs(w);if(S===null)throw new F(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 xs(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",w.length,w.length),!await Ss(n.transcriptionModels,d,e))return;let k=[{type:"input_audio",input_audio:{data:Buffer.from(w).toString("base64"),format:"wav"}}];try{let f=await Rs(n.clients,d,k,l,n.turn?oe(n.turn):void 0);ks(n.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw br(f)}}catch(s){if(s instanceof X){Qt(e,new F(413,s.message));return}if(s instanceof F){Qt(e,s);return}throw s}}A();var Ir="/v1/usage/requests",kr=1e4,Is=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,we=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},K=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},xt=class extends K{constructor(e){super(e),this.name="UsageWithholdingError"}},Ar=1024*1024;function tn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new we(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new we(`"${e}" must be an array of uuid strings`);if(n.length>kr)throw new we(`"${e}" carries ${n.length} ids; at most ${kr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Is.test(s))throw new we(`"${e}" contains ${JSON.stringify(s)}, 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`);o.has(s)||(o.add(s),r.push(s))}return r}function Or(t){return tn(t,"inference_ids")}var As=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","cost_nano_usd","price_version","priced_at"];function Ne(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new K(`${n}: ${e} is not a non-empty string (got ${Be(r)})`);return r}function Zt(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new K(`${n}: ${e} is neither null nor a non-empty string (got ${Be(r)})`);return r}function Xe(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new K(`${n}: ${e} is not a number (got ${Be(o)})`);if(r&&!Number.isSafeInteger(s))throw new K(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new K(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Os=40,Rr=64,Sr=600;function Tr(t){let e=Object.keys(t).sort(),r=e.slice(0,Os).map(o=>o.length>Rr?`${o.slice(0,Rr)}\u2026`:o).join(", ");return r.length>Sr&&(r=`${r.slice(0,Sr)}\u2026`),`${e.length} keys present: [${r}]`}function Be(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function en(t){ye(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
24
+ `)}function Ts(t,e){let n;try{n=t(e)}catch{Er(t,e);return}Ps(n)&&Promise.resolve(n).catch(()=>{Er(t,e)})}function Ps(t){return typeof t?.then=="function"}function Er(t,e){if(t!==en)try{en(e)}catch{}}function xu(t,e=en){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Tr(t):Be(t);throw new K(`the usage surface answered without a "requests" array: got ${Be(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Cs(n[o],s))}catch(i){if(i instanceof xt||!(i instanceof K))throw i;Ts(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new K(`the usage surface returned ${n.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 Cs(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new K(`${e} is not an object: got ${Be(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new xt(`${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 o of As)if(!Object.hasOwn(n,o))throw new K(`${e} has no "${o}" column (${Tr(n)})`);let r=Xe(n,"http_status",e,!0);if(r===null)throw new K(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Ne(n,"inference_id",e),model_id:Ne(n,"model_id",e),identity_kind:Ne(n,"identity_kind",e),variant:Zt(n,"variant",e),task:Ne(n,"task",e),http_status:r,started_at:Ne(n,"started_at",e),completed_at:Ne(n,"completed_at",e),prompt_tokens:Xe(n,"prompt_tokens",e,!0),completion_tokens:Xe(n,"completion_tokens",e,!0),output_units:Xe(n,"output_units",e,!1),cost_nano_usd:Xe(n,"cost_nano_usd",e,!0),price_version:Zt(n,"price_version",e),priced_at:Zt(n,"priced_at",e)}}function kt(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new K(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new K(`the usage surface returned ${s.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(s.inference_id)}}import{SessionAllocationError as gi,SessionFailedError as hi}from"@urun-sh/core";A();var nn="/partners/huggingface/v1/billing/requests";function Ms(t){return tn(t,"requestIds")}function $s(t){return t>=200&&t<=399}function Ls(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&$s(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Pr(t,e){let n=Ms(t),r=await e(n);return kt(r,n),Ls(r)}A();var Us={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"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"};function Ns(t){return Us[t]??null}var $r=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Bs(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Fs(t){return t==="surface"}function qs(t){let e=t?.ledgerFailureReason;return $r.includes(e)?e:"unknown"}var Ds=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Cr=["priced","unpriced"],js={written:Cr,already_written:Cr,skipped:Ds,failed:$r},Ou=Object.entries(js).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Hs(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Gs(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Js=256,Mr=4096,Qe=12e4,Vs=250,Ws=8e3,fe=[],rn=new Set,Ze=0,Fe=!1;function Tu(){return fe.length}function Pu(t=Date.now()){let e=fe[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Rt=new Set;function Lr(){return Ze===0&&fe.length===0}function Ur(){if(Lr()){Fe=!1;for(let t of[...Rt])t()}}async function Cu(t=Nr){return Lr()?!0:await new Promise(e=>{let n=null,r=()=>{Rt.delete(r),n&&clearTimeout(n),e(!0)};Rt.add(r),n=setTimeout(()=>{Rt.delete(r),e(!1)},t),n.unref?.()})}function Mu(){Fe=!0;let t=[...fe.splice(0,fe.length),...rn];for(let e of t)e.settled||Ie(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 ${Nr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Ur(),t.length}var Nr=5e3;function Br(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
25
+ `}function Ks(t){ye(process.stdout,t)}function Fr(t,e){try{t(e)}catch{}}function qr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Ks,o=Ns(e.path);if(o===null)return;let s=c=>{try{n.observe(c)}catch{}},i=(c,l)=>{s({outcome:"skipped",reason:c}),Fr(r,Br("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:c,detail:l}))};if(e.status===null){i("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){i("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"){i("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){i("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 d={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:Gs(e),completed_at:e.ts,billable_outcome:Hs(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,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(fe.length>=Mr){i("queue_full",`${fe.length} ledger writes are already waiting (capacity ${Mr}, ${Ze} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}fe.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Ze<Js&&(Ze+=1,zs())}async function zs(){try{for(;;){let t=Ys();if(t===void 0)return;rn.add(t);try{await Xs(t)}finally{rn.delete(t)}}}finally{Ze-=1,Ur()}}function Ys(){let t=Date.now();for(;;){let e=fe.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Qe)return e;Ie(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${Qe}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 Xs(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Ie(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Bs(o);if(s!==null){Ie(t,{outcome:"already_written",reason:s.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:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=qs(o),a=Date.now()-t.queuedAt;if(Fe){Ie(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.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: ${o instanceof Error?o.message:String(o)}`});return}if(Fs(i)&&a<Qe){if(await Zs(Qs(t.attempts)),Fe||Date.now()-t.queuedAt>=Qe){let u=Date.now()-t.queuedAt;Ie(t,{outcome:"failed",reason:Fe?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Fe?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${Qe}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}Ie(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Qs(t){return Math.min(Ws,Vs*2**Math.max(0,t-1))}function Zs(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ie(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Fr(t.report,Br(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}A();var sn="x-urun-profile",et="voice";var re=class extends Error{status=400},ei=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,ti=/\s/;function ni(t){return ei.test(t)}function on(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Dr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function jr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let d=n.trim();if(d==="")throw new re(`the ${sn} header is empty \u2014 the only profile this lane accepts is "${et}" (omit the header for the ordinary lane)`);if(d!==et)throw new re(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${et}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==et)throw new re(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${et}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new re("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new re("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:Dr(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:Dr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:on(u,"sentence_flush",!0),includeReasoning:on(u,"include_reasoning",!1),metadata:on(u,"metadata",!1)}}var St=class{constructor(e,n){this.config=e;this.sink=n}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 n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&ni(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(ti.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};A();import*as an from"crypto";var ri="urun-runtime-key-v1";function oi(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return an.createHmac("sha256",t).update(`${ri}|${e}`,"ascii").digest("base64url")}var si="decision-intake",Et=6e4,ii=Et/1e3+5,Hr=3,un=15;function ai(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:si,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=an.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function ui(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function di(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(Et)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new ue(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${Et}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!ui(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=un)}var ci=un*1e3,li=un*500,pi=256,Gr=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new ue("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new ue(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let c=null;for(let l=0;l<Hr;l++){let v=this.pick(d);if(v===null)throw new ue(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let p=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,w=ai(oi(this.opts.secret,p),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},ii);try{return{...await this.post(v,e,w),target:{...r,fnName:s}}}catch(S){if(S instanceof Ae)throw S;c=S;let k=this.replicas.get(v)??{outstanding:0,cooldownUntil:0};k.cooldownUntil=this.nowMs()+5e3,this.replicas.set(v,k);let f=this.presenceCache.get(u);f&&(f.rows=f.rows.filter(g=>g.address!==v),f.rows.length===0&&this.presenceCache.delete(u))}}throw new ue(`no runtime for app=${o} answered within ${Hr} attempts: ${String(c instanceof Error?c.message:c)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>ci)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>li&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=pi;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return di({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??Et)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new Ae(s.status,i);return{status:s.status,body:i,completed:fi(i)}}finally{o.outstanding-=1}}};function fi(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var Ae=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},ue=class extends Error{};function ln(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function yi(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function J(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function V(t,e,n,r="invalid_request_error",o){J(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function pn(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);J(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function de(t,e,n,r){J(t,e,{type:"error",error:{type:n,message:r}})}function ce(t,e,n){if(e==="anthropic"){J(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}J(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var _i=64*1024*1024,tt=class extends Error{};async function Jr(t,e=_i){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new tt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Oe(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Kr(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function It(t){let e=Kr(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Vr(t){let e=It(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function wi(t,e){let n=Kr(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function vi(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function bi(t,e){let n=vi(e);n&&(t.timing=n)}function me(t,e){wi(t,e),bi(t,e)}async function Tt(t,e,n){if(typeof e.catalogIdentity!="function"){t.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(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function zr(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function xi(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var At=class extends Error{};function ki(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new At(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Ri(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:ki(n.role,n.content)})}return e}function dn(t){return Me(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Si(t,e,n,r,o,s){let i=Ge(s.id),a=t.stream===!0;if(s.model=te(t),s.stream=a,await Tt(s,e,typeof t.model=="string"?t.model:void 0),a){let f;try{f=await Ve({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(g){if(g instanceof L){ce(r,"openai",g);return}if(g instanceof se){V(r,g.status,g.message);return}throw g}ln(r);for await(let g of f.events)g.type==="error"&&(s.streamError=!0),g.type==="response.completed"&&me(s,g.response),r.write(`event: ${String(g.type??"message")}
26
+ data: ${JSON.stringify(g)}
27
+
28
+ `);r.write(`data: [DONE]
29
+
30
+ `),r.end();return}let u;try{u=Ue(n,t)}catch(f){if(f instanceof se){V(r,f.status,f.message);return}throw f}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=te(t);o.model(c);let l=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await Wt(e,t,u,!1,oe(s))}catch(f){if(f instanceof L){ce(r,"openai",f);return}if(f instanceof se){V(r,f.status,f.message);return}throw f}let p=[],w=null;for await(let f of o.track(v,c,s)){if(p.push(f),f.type==="error"){pn(r,f);return}f.type==="response.completed"&&(w=f.response)}if(w==null){V(r,502,"upstream produced no response.completed event","upstream_error");return}me(s,w);let S=Le(p,w),k=Ee(l,Me(w).length,S);if(k){V(r,502,Se(c,k),"upstream_error");return}d&&n.remember(i,u,Vt(w,S),d),J(r,200,{...w,id:i})}async function Ei(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){V(n,400,"chat/completions requires a messages array");return}let a;try{a=jr(s,t)}catch(_){if(_ instanceof re){V(n,_.status,_.message);return}throw _}let u=String(t.model??"urun"),d=Gn(o.id),c;try{c=Ri(i)}catch(_){if(_ instanceof At){V(n,400,_.message);return}throw _}let l=te(t);r.model(l),o.model=l,o.stream=t.stream===!0,await Tt(o,e,typeof t.model=="string"?t.model:void 0);let v=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let _;try{_=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(x){if(x instanceof L){ce(n,"openai",x);return}throw x}if(_!==null){try{let x=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);o.catalog=Mt(x.target),me(o,x.completed),J(n,200,{...x.body,id:d})}catch(x){if(x instanceof L){ce(n,"openai",x);return}if(x instanceof Ae){J(n,x.status,x.body);return}if(x instanceof ue){V(n,503,x.message,"upstream_error");return}throw x}return}}let p;try{p=await e.createResponse({model:t.model,input:c,stream:!0,tools:xi(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},oe(o))}catch(_){if(_ instanceof L){ce(n,"openai",_);return}throw _}if(t.stream===!0){a?yi(n):ln(n);let _=[],x=new _e,P="",N=a?new St(a,ee=>{n.write(`data: ${JSON.stringify(Oe(d,u,{content:ee},null))}
31
+
32
+ `)}):null,z=ee=>{N?.flush(),n.write(ee),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
33
+
34
+ `),n.write(`data: ${JSON.stringify(Oe(d,u,{role:"assistant"},null))}
35
+
36
+ `);for await(let D of r.track(p,l,o)){_.push(D);let Q=$e(D);if(D.type==="response.output_text.delta"&&typeof D.delta=="string")P+=D.delta,N?N.push(D.delta):n.write(`data: ${JSON.stringify(Oe(d,u,{content:D.delta},null))}
37
+
38
+ `);else if(D.type==="response.reasoning_text.delta"&&typeof D.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Oe(d,u,{reasoning_content:D.delta},null))}
39
+
40
+ `);else if(Q){N?.flush();let{call:ve,isNew:O}=x.add(Q),$=O?{index:Q.tool_index,id:ve.id??`call_${Q.tool_index}`,type:"function",function:{name:ve.name??"",arguments:Q.delta}}:{index:Q.tool_index,function:{arguments:Q.delta}};n.write(`data: ${JSON.stringify(Oe(d,u,{tool_calls:[$]},null))}
41
+
42
+ `)}else if(D.type==="error"){o.streamError=!0,z(`data: ${JSON.stringify({error:D})}
43
+
44
+ `);return}}let ee=dn(ae(_)),ie=Ee(v,x.size+ee.length,P);if(ie){o.streamError=!0,z(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Se(l,ie)}})}
45
+
46
+ `);return}N?.flush(),x.size===0&&ee.length>0&&n.write(`data: ${JSON.stringify(Oe(d,u,{tool_calls:ee},null))}
47
+
48
+ `);let ge=x.size>0||ee.length>0;n.write(`data: ${JSON.stringify(Oe(d,u,{},ge?"tool_calls":"stop"))}
49
+
50
+ `);let q=It(ae(_));me(o,ae(_)),q&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Vr(ae(_))})}
51
+
52
+ `),n.write(`data: [DONE]
53
+
54
+ `),n.end();return}finally{N?.flush(),N?.dispose()}}let w="",S="",k=[],f=new _e;for await(let _ of r.track(p,l,o)){k.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(w+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(S+=_.delta);let x=$e(_);if(x&&f.add(x),_.type==="error"){pn(n,_);return}}let g=ae(k);me(o,g);let h=dn(g),E=h.length>0?h:dn({output:f.items()}),m=Ee(v,E.length,w);if(m){V(n,502,Se(l,m),"upstream_error");return}let y=E.map(({index:_,...x})=>x),b={role:"assistant",content:w||null},M=S||zr(g);M&&(b.reasoning_content=M),y.length>0&&(b.tool_calls=y),J(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:b,finish_reason:y.length>0?"tool_calls":"stop"}],usage:Vr(g)})}var Ii="reflex-latest";async function Ai(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){V(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:Ii,i=te({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){V(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){V(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){V(n,400,"systemone media, when present, must be an array");return}if(r.model(i),await Tt(o,e,s),e.stateless?.enabled){let p;try{p=await e.stateless.targetFor(s)}catch(w){if(w instanceof L){ce(n,"openai",w);return}throw w}if(p!==null){try{let w=await e.stateless.decide(t,s);o.catalog=Mt(w.target),me(o,w.completed),J(n,200,w.body)}catch(w){if(w instanceof L){ce(n,"openai",w);return}if(w instanceof Ae){J(n,w.status,w.body);return}if(w instanceof ue){V(n,503,w.message,"upstream_error");return}throw w}return}}let u;try{u=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},oe(o))}catch(p){if(p instanceof L){ce(n,"openai",p);return}throw p}let d=[];try{for await(let p of r.track(u,i,o))if(d.push(p),p.type==="error"){pn(n,p);return}}catch(p){if(p instanceof L){ce(n,"openai",p);return}throw p}let c=ae(d);if(c==null){V(n,502,"upstream produced no response.completed event","upstream_error");return}me(o,c);let l=Le(d,c),v;try{v=JSON.parse(l)}catch{V(n,502,"systemone answer was not valid JSON","upstream_error");return}if(v===null||typeof v!="object"||Array.isArray(v)){V(n,502,"systemone answer was not a JSON object","upstream_error");return}J(n,200,v)}function Oi(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var nt=class extends Error{};function Ot(t){return new nt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ti(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function Pi(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new nt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Ci(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Ot(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Ot(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Mi(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Ot(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Ci(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Ot(a)}}return s(),r}function cn(t){return Me(t).map((e,n)=>{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_${n}`,name:e.name??"",input:r}})}async function $i(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){de(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){de(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){de(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(b=>typeof b!="string"))){de(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=Jn(o.id),u=[],d;try{t.system&&u.push({role:"system",content:Oi(t.system)});for(let b of s)u.push(...Mi(b));d=Pi(t.tool_choice)}catch(b){if(b instanceof nt){de(n,400,"invalid_request_error",b.message);return}throw b}let c=te(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Tt(o,e,typeof t.model=="string"?t.model:void 0);let l=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await e.createResponse({model:t.model,input:u,stream:!0,tools:Ti(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},oe(o))}catch(b){if(b instanceof L){ce(n,"anthropic",b);return}throw b}let p=(b,M)=>{n.destroyed||n.write(`event: ${b}
55
+ data: ${JSON.stringify({type:b,...M})}
56
+
57
+ `)};if(t.stream===!0){let b=r.track(v,c,o);ln(n),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let M=0,_="",x=0,P="none",N=()=>P,z=-1,ee=-1,ie=new _e,ge=[],q=()=>{P!=="none"&&(P="none",p("content_block_stop",{index:z}))},D=(B,Z)=>{q(),P=B,z=x++,p("content_block_start",{index:z,content_block:Z})};for await(let B of b){if(n.destroyed)break;ge.push(B);let Z=$e(B);if(B.type==="response.reasoning_text.delta"&&typeof B.delta=="string")N()!=="thinking"&&D("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:z,delta:{type:"thinking_delta",thinking:B.delta}});else if(B.type==="response.output_text.delta"&&typeof B.delta=="string")N()!=="text"&&D("text",{type:"text",text:""}),M+=1,_+=B.delta,p("content_block_delta",{index:z,delta:{type:"text_delta",text:B.delta}});else if(Z){let{call:he}=ie.add(Z);(N()!=="tool"||Z.tool_index!==ee)&&(ee=Z.tool_index,D("tool",{type:"tool_use",id:he.id??`call_${Z.tool_index}`,name:he.name??"",input:{}})),Z.delta&&p("content_block_delta",{index:z,delta:{type:"input_json_delta",partial_json:Z.delta}})}else if(B.type==="error"){o.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(B)}}),n.end();return}}if(n.destroyed)return;let Q=ae(ge),ve=Me(Q),O=Ee(l,ie.size+ve.length,_);if(O){o.streamError=!0,p("error",{error:{type:"api_error",message:Se(c,O)}}),n.end();return}q();let $=[];if(ie.size===0)try{$=cn(Q)}catch(B){o.streamError=!0,p("error",{error:{type:"api_error",message:String(B instanceof Error?B.message:B)}}),n.end();return}x===0&&$.length===0&&(D("text",{type:"text",text:""}),q()),$.forEach(B=>{let Z=x++;p("content_block_start",{index:Z,content_block:{...B,input:{}}}),p("content_block_delta",{index:Z,delta:{type:"input_json_delta",partial_json:JSON.stringify(B.input??{})}}),p("content_block_stop",{index:Z})});let W=ie.size>0||$.length>0,le=It(Q);me(o,Q),p("message_delta",{delta:{stop_reason:W?"tool_use":"end_turn"},usage:le?{input_tokens:le.input_tokens,output_tokens:le.output_tokens}:{output_tokens:M}}),p("message_stop",{}),n.end();return}let w="",S="",k=[],f=new _e;for await(let b of r.track(v,c,o)){k.push(b),b.type==="response.output_text.delta"&&typeof b.delta=="string"&&(w+=b.delta),b.type==="response.reasoning_text.delta"&&typeof b.delta=="string"&&(S+=b.delta);let M=$e(b);if(M&&f.add(M),b.type==="error"){let _=b.error,x=_?.type==="invalid_request_error";de(n,x?400:502,x?"invalid_request_error":"api_error",_?.message??JSON.stringify(b));return}if(n.destroyed)break}if(n.destroyed)return;let g=ae(k);me(o,g);let h;try{h=cn(g),h.length===0&&f.size>0&&(h=cn({output:f.items()}))}catch(b){de(n,502,"api_error",String(b instanceof Error?b.message:b));return}let E=Ee(l,h.length,w);if(E){de(n,502,"api_error",Se(c,E));return}let m=[],y=S||zr(g);y&&m.push({type:"thinking",thinking:y}),(w||h.length===0)&&m.push({type:"text",text:w}),m.push(...h),J(n,200,{id:a,type:"message",role:"assistant",content:m,model:i,stop_reason:h.length>0?"tool_use":"end_turn",usage:It(g)??{input_tokens:0,output_tokens:0}})}function Li(t){ye(process.stdout,t)}function Ui(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Li,a=t.observe,u=new ke;return(d,c)=>{let l=new URL(d.url??"/","http://localhost"),v=l.pathname==="/v1/messages"||l.pathname.startsWith("/v1/messages/"),p=(g,h,E,m,y)=>v?de(c,g,m,h):V(c,g,h,E,y),w=Jt(l.pathname),S=l.pathname.startsWith("/partners/"),k=w||S?{id:He(),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,sessionId:null,timing:null}:null;k&&(c.setHeader(jn,k.id),c.once("close",()=>{let g=Vn({turn:k,method:d.method??"",path:l.pathname,res:c});i(Wn(g)),a?.(g),qr({record:g,ledger:t.ledger??null,req:d})}));let f=()=>Hn(l.pathname,k);(async()=>{if(d.method==="GET"&&l.pathname==="/healthz"){J(c,200,{ok:!0});return}if(d.method==="GET"&&l.pathname==="/stats"){J(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let g=l.pathname===Ir?"canonical":l.pathname===nn?"huggingface":null;if(g){if(d.method!=="POST"){p(405,`${l.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let y=t.usage;if(!y){p(501,`${l.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 b=y.authorize(d),M;try{M=await Jr(d,Ar)}catch(P){if(P instanceof tt){p(413,P.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=P=>y.lookup(b,P),x;try{if(g==="canonical"){let P=Or(M),N=await _(P);kt(N,P),x={requests:N}}else x=await Pr(M,_)}catch(P){if(P instanceof we){p(P.status,P.message,"invalid_request_error","invalid_request_error");return}throw P}J(c,200,x);return}if(l.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${d.method} ${l.pathname} \u2014 the partner surface currently carries ${nn}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(k&&(k.org=h.tenant??null),d.method==="GET"&&l.pathname==="/v1/models"){if(l.searchParams.get("format")==="openrouter"){if(!h.openRouterModels){p(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}J(c,200,await h.openRouterModels());return}J(c,200,await h.listModels());return}if(d.method==="GET"&&l.pathname===tr){if(!h.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}J(c,200,await h.listImageModels());return}if(er(l.pathname)){if(!h.supportsImages){p(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${l.pathname}`,"not_implemented","not_implemented_error");return}let y={clients:h,imageModels:h.supportsImages,stats:u,turn:f()};l.pathname===yt?await lr(d,c,y):await cr(d,c,y);return}if(d.method==="GET"&&l.pathname===wr){if(!h.listSpeechToTextModels){p(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}J(c,200,await h.listSpeechToTextModels());return}if(_r(l.pathname)){if(!h.supportsTranscription){p(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${bt}`,"not_implemented","not_implemented_error");return}let y={clients:h,transcriptionModels:h.supportsTranscription,stats:u,turn:f()};await xr(d,c,y);return}if(hr(l.pathname)){if(!h.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Ye}`,"not_implemented","not_implemented_error");return}let y={clients:h,speechModels:h.supportsSpeech,stats:u,turn:f()};await yr(d,c,y);return}if(d.method!=="POST"){p(404,`no route for ${d.method} ${l.pathname}`,"invalid_request_error","not_found_error");return}let E;try{E=await Jr(d)}catch(y){if(y instanceof tt){p(413,y.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let m=Buffer.byteLength(JSON.stringify(E));if(l.pathname==="/v1/responses"){u.request("responses",m,m),await Si(E,h,Je(h),c,u,f());return}if(l.pathname==="/v1/chat/completions"){u.request("chat_completions",m,m),await Ei(E,h,c,u,f(),d.headers[sn]);return}if(l.pathname==="/v1/systemone"){u.request("systemone",m,m),await Ai(E,h,c,u,f());return}if(l.pathname==="/v1/messages"){u.request("messages",m,m),await $i(E,h,c,u,f());return}if(l.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",m,m),de(c,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}p(404,`no route for POST ${l.pathname}`,"invalid_request_error","not_found_error")})().catch(g=>{let h=String(g instanceof Error?g.message:g);if(!c.headersSent){let E=o?.(g)??null;if(E){p(E.status,h,E.openaiType,E.anthropicType);return}if(g instanceof gi){let m=pt(g.code);if(m){let y=g.retryAfterSeconds??(m.status===429?30:void 0);y!==void 0&&c.setHeader("Retry-After",String(y)),p(m.status,Dt(m,g.code??void 0),m.openaiType,m.anthropicType,m.code);return}}if(g instanceof hi){let m=ft(g);if(m){let y=m.status===429?30:void 0;y!==void 0&&c.setHeader("Retry-After",String(y)),p(m.status,Dt(m,g.status.sessionId?`session ${g.status.sessionId}`:void 0),m.openaiType,m.anthropicType,m.code);return}}if(g instanceof K){p(502,h,"upstream_error","api_error");return}p(500,h,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0),c.destroyed||(v?c.write(`event: error
58
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
59
+
60
+ `):c.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
61
+
62
+ `)),c.end()})}}function id(t){let{clients:e,apiKey:n}=t,r=mi(Ui(t)),o=Qn(r,{clients:e,apiKey:n,statusOf:t.statusOf}),s=Gt(r,{resolver:Wr(e,n)}),i=r.close.bind(r);return r.close=(a=>(o.close(),s(),i(a))),Cn(r,{clients:e,apiKey:n}),r}var rt=(t,e)=>Object.assign(new Error(e),{status:t});function Ni(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function Bi(t,e,n){if(!t.supportsAudio)throw rt(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 r;try{r=await t.supportsAudio(e)}catch(a){throw a instanceof L?rt(404,a.message):a}if(!r)throw rt(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw rt(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=await t.sessionHandle(e),s={audio:await t.openAudioOn(o,n)},i={clients:{createResponse:async a=>await t.createResponseOn(o,a)},voice:r,audioSession:s};return e!==void 0&&(i.model=e),i}function Wr(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,s=typeof o=="string"?o.trim():"",i=s.startsWith("Bearer ")?s.slice(7).trim():"";if(i===""||i!==e)throw rt(401,"invalid local proxy api key")}return Bi(t,Ni(n),r)}}}export{it as a,Cn as b,Hi as c,Ko as d,Qn as e,Zi as f,ao as g,ea as h,ta as i,na as j,ra as k,oa as l,sa as m,ia as n,aa as o,ua as p,uo as q,$n as r,da as s,po as t,ca as u,la as v,pa as w,ye as x,fa as y,ma as z,ga as A,je as B,Ht as C,Gt as D,Ni as E,Bi as F,Wr as G,Ir as H,K as I,xu as J,nn as K,Ou as L,Tu as M,Pu as N,Cu as O,Mu as P,Gr as Q,Ui as R,id as S};
@@ -1,4 +1,4 @@
1
- import{a as j,b as W}from"./chunk-X3GLH2HQ.js";import{C as re,D as oe,E as se,F as ie,H as ae,I as A,J as le,K as ce,L as ue,M as de,N as he,O as pe,P as ge,Q as fe,R as me,b as Z,d as ee,e as te,q as ne,r as O}from"./chunk-WEBOBE7Z.js";import{e as Q,g as z}from"./chunk-TMQJY56F.js";import{a as X}from"./chunk-3JWYIKHM.js";import{c as p}from"./chunk-YSFSRI3D.js";p();import{Counter as S,Gauge as ye,Histogram as we,Registry as Ue,collectDefaultMetrics as Pe}from"@prometheus-io/client";import{createServer as $e}from"http";var It=9464,be="/metrics",I="(other)",Le="(none)",He=64,Me=128,De=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",ae,ce],Fe=new Set(De);function Ke(t){return Fe.has(t)?t:I}function Ge(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var T=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Le:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,I):(this.admitted.add(e),e):I}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},N=class{registry=new Ue;modelLabel=new T(He);orgLabel=new T(Me);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new S({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new we({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new we({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new S({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new S({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new S({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of ue)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ye({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},de()),this.ledgerQueue.set({measure:"oldest_age_seconds"},he()/1e3)}}),this.labelCardinality=new ye({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new S({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&Pe({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=Ke(e.path),o=e.status!==null&&!(e.status>=400&&e.status<500),r=this.modelLabel.overflowCount+this.orgLabel.overflowCount,a=this.modelLabel.of(e.model,o),s=this.orgLabel.of(e.org,o);this.modelLabel.overflowCount+this.orgLabel.overflowCount-r>0&&(this.modelLabel.overflowCount>r?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?I:e.method,status_class:Ge(e.status),stream:l,model:a,org:s}),this.duration.observe({lane:n,stream:l,model:a,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:a,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:a}),e.delivered||this.undelivered.inc({lane:n,model:a})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function ve(t){return $e((e,n)=>{(async()=>{let o=(e.url??"/").split("?")[0];if(e.method!=="GET"||o!==be){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${o} \u2014 this port serves only GET ${be}
1
+ import{a as j,b as W}from"./chunk-X3GLH2HQ.js";import{C as re,D as oe,E as se,F as ie,H as ae,I as A,J as le,K as ce,L as ue,M as de,N as he,O as pe,P as ge,Q as fe,R as me,b as Z,d as ee,e as te,q as ne,r as O}from"./chunk-6AHEIDYF.js";import{e as Q,g as z}from"./chunk-TMQJY56F.js";import{a as X}from"./chunk-3JWYIKHM.js";import{c as p}from"./chunk-YSFSRI3D.js";p();import{Counter as S,Gauge as ye,Histogram as we,Registry as Ue,collectDefaultMetrics as Pe}from"@prometheus-io/client";import{createServer as $e}from"http";var It=9464,be="/metrics",I="(other)",Le="(none)",He=64,Me=128,De=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",ae,ce],Fe=new Set(De);function Ke(t){return Fe.has(t)?t:I}function Ge(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var T=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Le:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,I):(this.admitted.add(e),e):I}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},N=class{registry=new Ue;modelLabel=new T(He);orgLabel=new T(Me);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new S({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new we({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new we({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new S({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new S({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new S({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of ue)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ye({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},de()),this.ledgerQueue.set({measure:"oldest_age_seconds"},he()/1e3)}}),this.labelCardinality=new ye({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new S({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),e.defaultMetrics!==!1&&Pe({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=Ke(e.path),o=e.status!==null&&!(e.status>=400&&e.status<500),r=this.modelLabel.overflowCount+this.orgLabel.overflowCount,a=this.modelLabel.of(e.model,o),s=this.orgLabel.of(e.org,o);this.modelLabel.overflowCount+this.orgLabel.overflowCount-r>0&&(this.modelLabel.overflowCount>r?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?I:e.method,status_class:Ge(e.status),stream:l,model:a,org:s}),this.duration.observe({lane:n,stream:l,model:a,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:a,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:a}),e.delivered||this.undelivered.inc({lane:n,model:a})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function ve(t){return $e((e,n)=>{(async()=>{let o=(e.url??"/").split("?")[0];if(e.method!=="GET"||o!==be){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${o} \u2014 this port serves only GET ${be}
2
2
  `);return}let r=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(r)})().catch(o=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(o instanceof Error?o.message:o)}
3
3
  `);return}n.end()})})}p();import{createHash as Ee}from"crypto";import{createServer as Be}from"http";var $t=9465,ze="x-urun-key-id",je="x-urun-key-fingerprint",We="urun-ratelimit-bucket:",Je="urun-ratelimit-tier:",_e="anonymous",qe=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Ve(t){return Ee("sha256").update(`${We}${t}`).digest("hex")}function Ye(t){return Ee("sha256").update(`${Je}${t}`).digest("hex")}function Qe(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return qe.test(n)?n:null}function Se(){return Be((t,e)=>{let n=Qe(t.headers.authorization);e.setHeader(ze,n===null?_e:Ve(n)),e.setHeader(je,n===null?_e:Ye(n)),e.writeHead(200),e.end()})}p();import{createClientToken as Xe,ClientTokenError as Ze}from"@urun-sh/core";var m=class extends Error{constructor(n,o=401){super(n);this.status=o;this.name="ProxyAuthError"}status},_=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function R(t){let e=(t??"").trim();if(e==="")throw new m("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new m("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var et=60,tt=6e4,nt=4096;function rt(t){return t===401||t===403}var U=class{constructor(e){this.opts=e;this.mint=e.mint??Xe,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new m("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<tt)return{apiKey:e,orgId:n.orgId};let o;try{o=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:et})).orgId}catch(r){throw r instanceof Ze&&rt(r.status)?(this.cache.delete(e),new m("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new _(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${r instanceof Error?r.message:String(r)}`)}if(!o)throw new _("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=nt){let r=this.cache.keys().next();r.done||this.cache.delete(r.value)}return this.cache.set(e,{orgId:o,at:this.now()}),{apiKey:e,orgId:o}}clear(){this.cache.clear()}};p();var ot=8080,P="serve",Gt="0.0.0.0";function st(t,e,n){let o=(t[e]??"").trim();if(!o)throw new Error(`${e} is not set \u2014 ${n}`);return o}function Bt(t=process.env){let e=(t.PORT??"").trim(),n=e===""?ot:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let o=ne(O(st(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),r=(t.URUN_API_URL??"").trim(),a=r?O(r,"URUN_API_URL"):`${o.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),i=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!i)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=s?{catalogUrl:O(s,"URUN_CATALOG_URL"),anonKey:i}:null,u=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),f=(t.URUN_SHARED_ORG_API_KEY??"").trim(),x=(t.URUN_SHARED_ORG_ID??"").trim();if(!!f!=!!x)throw new Error("URUN_SHARED_ORG_API_KEY and URUN_SHARED_ORG_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would silently leave the shared endpoints on the session lane");return{port:n,baseUrl:o,apiUrl:a,catalog:l,decisionSecret:u,sharedOrgKey:f,sharedOrgId:x}}p();import{createHash as it,randomUUID as at}from"crypto";var lt=512;function M(t){return`urun-inference-proxy-${it("sha256").update(t).digest("hex").slice(0,32)}`}var $=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let i=this.opts.build(e);return{router:i.router,clients:this.label(i.clients,e)}}let n=0,o=M(e.apiKey),r=()=>{n+=1},a=j({baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:P,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:()=>n===0?o:`${o}#${n}`,onPoolWedged:r,release:"end"}),s=this.opts.decisionIntake?new fe({targetFor:i=>a.targetFor(i),apiUrl:this.opts.apiUrl,apiKey:e.apiKey,orgId:e.orgId,fnName:P,secret:this.opts.decisionIntake.secret,...this.opts.decisionIntake.shared?{shared:this.opts.decisionIntake.shared}:{}}):void 0;return{router:a,clients:this.label(W(a,void 0,r,s),e)}}clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=lt;){let r=this.tenants.entries().next();if(r.done)break;let[a,s]=r.value;this.tenants.delete(a),s.router.closeAll().catch(()=>{})}let o=this.build(e);return this.tenants.set(e.apiKey,o),o.clients}get size(){return this.tenants.size}async closeAll(){let e=[...this.tenants.values()].map(o=>o.router);this.tenants.clear();let n=[];if(await Promise.all(e.map(async o=>{try{await o.closeAll()}catch(r){n.push(String(r instanceof Error?r.message:r))}})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Re=512,ct=1024,L=class extends Error{constructor(){super(`conversation capacity reached (${Re} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function ut(t){return{sessionStartOptions:e=>{if(e.startsWith(z))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(z)||t.set(e,n)}}}function dt(t,e,n,o){let r=j({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:P,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...ut(o)});return{clients:W(r),release:async()=>{await r.closeAll()}}}var H=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let o={id:n,subject:`${M(e.apiKey)}:live:${n}`},r=new Map,a=this.opts.build?this.opts.build(e,o):dt(this.opts,e,o,r);return{id:n,backhaul:a,attachments:0,nativeRefs:r}}attachEntry(e,n){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let r=o.get(n);if(r!==void 0)return o.delete(n),o.set(n,r),r.attachments+=1,r;this.evictOverflow();let a=this.build(e,n);return a.attachments=1,o.set(n,a),a}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Re;){let e=this.byCaller.keys().next();if(e.done)throw new L;let n=e.value,o=this.byCaller.get(n),r=!1;for(let[a,s]of o)if(!(s.attachments>0)){o.delete(a),this.dropHandleIndexFor(n,a),s.backhaul.release().catch(()=>{}),r=!0;break}if(!r)throw o.size===0&&this.byCaller.delete(n),new L;o.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[o,r]of this.byHandle)r.apiKey===e&&r.conversationId===n&&this.byHandle.delete(o)}connectionFor(e){let n=null,o=!1,r=()=>(n===null&&(n=this.attachEntry(e,at())),n),a={createResponse:(s,i)=>r().backhaul.clients.createResponse(s,i),catalogIdentity:s=>r().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let i=r().backhaul.clients.servingAppSlug;if(i===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return i(s)},listModels:()=>r().backhaul.clients.listModels(),sessionHandle:s=>r().backhaul.clients.sessionHandle(s),createResponseOn:(s,i)=>r().backhaul.clients.createResponseOn(s,i),onSessionEnd:(s,i)=>r().backhaul.clients.onSessionEnd(s,i)};return a.openAudio=async(s,i)=>{let l=r().backhaul.clients.openAudio;if(l===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return l(s,i)},a.openVideo=async s=>{let i=r().backhaul.clients.openVideo;if(i===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return i(s)},a.openVideoOut=async s=>{let i=r().backhaul.clients.openVideoOut;if(i===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return i(s)},a.supportsAudio=async s=>{let i=r().backhaul.clients.supportsAudio;if(i===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return i(s)},a.supportsSpeech=async s=>{let i=r().backhaul.clients.supportsSpeech;if(i===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return i(s)},a.speechVoices=async s=>{let i=r().backhaul.clients.speechVoices;if(i===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return i(s)},a.speechSessionHandle=async s=>{let i=r().backhaul.clients.speechSessionHandle;if(i===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return i(s)},a.openAudioOn=async(s,i)=>{let l=r().backhaul.clients.openAudioOn;if(l===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return l(s,i)},a.evictSpeechSession=async s=>{let i=r().backhaul.clients.evictSpeechSession;if(i===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return i(s)},a.supportsTranscription=async s=>{let i=r().backhaul.clients.supportsTranscription;if(i===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return i(s)},a.listSpeechToTextModels=async()=>{let s=r().backhaul.clients.listSpeechToTextModels;if(s===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return s()},{clients:a,bindResumeHandle:s=>{let i=n;if(i===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=ct;){let l=this.byHandle.keys().next();if(l.done)break;this.byHandle.delete(l.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:i.id})},clientsForResume:async s=>{let i=this.byHandle.get(s),l=i===void 0?void 0:this.byCaller.get(i.apiKey),u=i===void 0||l===void 0?void 0:l.get(i.conversationId);if(i===void 0||u===void 0||i.apiKey!==e.apiKey)throw new Q("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=u,u.attachments+=1,u.backhaul.clients},release:async()=>{if(o)return;o=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let o of this.byCaller.values())for(let r of o.values())e.push(r.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async o=>{try{await o}catch(r){n.push(String(r instanceof Error?r.message:r))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};p();var ht="/inference-ledger",pt=1e4,D=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},q=class extends Error{constructor(n,o){super(o);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},g=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},V=class extends m{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},gt=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",xe],["cost_nano_usd",xe],["price_version",t=>t===null||typeof t=="string"]];function ft(t){for(let[e,n]of gt){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function mt(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let o=e.existing;return o===null||typeof o!="object"||Array.isArray(o)?{status:"unavailable"}:ft(o)!==null?{status:"unavailable"}:{status:"found",row:o}}function xe(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function J(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Ce(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),o=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(o)&&n===o}function yt(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Ce(t.started_at,n.started_at)&&Ce(t.completed_at,n.completed_at)&&J(t.prompt_tokens,n.prompt_tokens)&&J(t.completion_tokens,n.completion_tokens)&&J(t.output_units,n.output_units)}function wt(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new g(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,o=n.inference_id;if(typeof o!="string"||o==="")throw new g(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new g(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let r=n.cost_nano_usd;if(r!=null&&!(typeof r=="number"&&Number.isInteger(r)&&r>=0))throw new g(`${e} answered cost_nano_usd ${JSON.stringify(r)}, which is neither a non-negative integer nor null`);let a=u=>{if(!(u in n))throw new g(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let f=n[u];if(f===null)return null;if(typeof f!="string")throw new g(`${e} answered a non-string ${u}: ${JSON.stringify(f)}`);if(!/[^\s]/.test(f))throw new g(`${e} answered a BLANK ${u} (${JSON.stringify(f)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return f},s=a("price_version"),i=a("unpriced_reason"),l=r!=null;if(l&&(s===null||i!==null))throw new g(`${e} answered a PRICED row (cost_nano_usd ${String(r)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(i)}`);if(!l&&(s!==null||i===null))throw new g(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(i)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:o,cost_nano_usd:r===void 0?null:r,price_version:s,unpriced_reason:i}}var F=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let o=`${this.opts.apiUrl.replace(/\/+$/,"")}${ht}`,r;try{r=await this.fetchImpl(o,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(pt)})}catch(l){throw new g(`the uRun ledger surface at ${o} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(r.status===409){let l=await r.text().catch(()=>""),u=mt(l);throw u.status==="found"&&yt(n,u.row)?new q(u.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):u.status==="not_in_this_org"?new D(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new D(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${u.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${l.slice(0,400)}`)}if(r.status===401||r.status===403)throw await r.text().catch(()=>{}),new V("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!r.ok){let l=await r.text().catch(u=>`<body unreadable: ${u instanceof Error?u.message:String(u)}>`);throw new g(`the uRun ledger surface at ${o} answered HTTP ${r.status}: ${l.slice(0,400)}`)}let a;try{a=await r.json()}catch(l){throw new g(`the uRun ledger surface at ${o} answered a body that is not JSON: ${l instanceof Error?l.message:String(l)}`)}let s=a?.recorded;if(s===void 0)throw new g(`the uRun ledger surface at ${o} answered a body with no "recorded" field`);let i=wt(s,`the uRun ledger surface at ${o}`);if(i.inference_id!==n.inference_id)throw new g(`the uRun ledger surface at ${o} answered for inference_id ${i.inference_id} when asked about ${n.inference_id}`);return i}};p();import{createServer as vt}from"http";p();var K="/inference-usage",ke=25e3;var bt=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Oe(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=bt.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var G=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let o=`${this.opts.apiUrl.replace(/\/+$/,"")}${K}`,r;try{r=await this.fetchImpl(o,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(ke)})}catch(s){throw new A(`the uRun usage surface (POST ${K}) could not be reached within ${ke}ms: ${Oe(s)}`)}if(r.status===401||r.status===403)throw await r.text().catch(()=>{}),new m("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!r.ok){let s=await r.text().catch(()=>null),i=s===null?"body unreadable":`${s.length}-character body`;throw new A(`the uRun usage surface (POST ${K}) answered HTTP ${r.status} (${i})`)}let a;try{a=await r.json()}catch(s){throw new A(`the uRun usage surface (POST ${K}) answered HTTP ${r.status} with a body that is not JSON: ${Oe(s)}`)}return le(a,this.opts.onRejectedRow)}};var _t=5e3,Et=3e3,St="/api/client-tokens";function Y(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Ae(t,e,n,o){Y(t,e,{error:{message:n,type:o}})}async function Rt(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${St}`;try{let o=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Et)});return o.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:o.status>=500?{ready:!1,detail:`${n} answered HTTP ${o.status}`}:{ready:!0,detail:`${n} answered HTTP ${o.status}`}}catch(o){return{ready:!1,detail:`${n} unreachable: ${o instanceof Error?o.message:String(o)}`}}}function _n(t){let e=t.resolver??new U({gatewayUrl:t.baseUrl}),n=t.decisionSecret??"",o=t.sharedOrgKey&&t.sharedOrgId?{apiKey:t.sharedOrgKey}:void 0,r=t.registry??new $({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog,...n!==""?{decisionIntake:{secret:n,...o?{shared:o}:{}}}:{}});n!==""&&process.stderr.write(`inference-proxy: stateless direct path ENABLED \u2014 caller-org decisions dial ready runtimes directly (no session mint)
4
4
  `);let a=t.probeControlPlane??(()=>Rt(t.baseUrl)),s=t.usageClient??new G({apiUrl:t.apiUrl}),i=t.ledgerClient??new F({apiUrl:t.apiUrl}),l=new N(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),u=async c=>e.resolve(R(c.headers.authorization)),f=c=>c instanceof m?{status:c.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:c instanceof _?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,x=me({clients:async c=>r.clientsFor(await u(c)),usage:{authorize:c=>R(c.headers.authorization),lookup:(c,d)=>s.lookup(c,d)},statusOf:f,...t.requestLog?{requestLog:t.requestLog}:{},observe:c=>l.observe(c),ledger:{write:(c,d)=>i.write(R(c.headers.authorization),d),observe:c=>l.observeLedger(c),...t.ledgerLog?{report:t.ledgerLog}:{}}}),v=null,E=vt((c,d)=>{let h=new URL(c.url??"/","http://localhost");(async()=>{if(c.method==="GET"&&h.pathname==="/healthz"){Y(d,200,{ok:!0});return}if(c.method==="GET"&&h.pathname==="/readyz"){let k=Date.now();if(!v||k-v.at>=_t){let Ne=await a();v={at:k,...Ne}}Y(d,v.ready?200:503,{ok:v.ready,control_plane:v.detail});return}let y=h.pathname==="/v1"||h.pathname.startsWith("/v1/"),C=h.pathname.startsWith("/partners/");if(!y&&!C){Ae(d,404,`no route for ${c.method} ${h.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz and /readyz`,"invalid_request_error");return}x(c,d)})().catch(y=>{if(!d.headersSent){Ae(d,500,String(y instanceof Error?y.message:y),"proxy_error");return}d.end()})}),B=t.conversations??new H({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),Ie=[Z(E,{authenticate:async c=>{let d=await e.resolve(c),h=B.connectionFor(d);return{clients:h.clients,scope:M(d.apiKey),onBindResumeHandle:h.bindResumeHandle,clientsForResume:h.clientsForResume,release:h.release}}}),te(E,{clients:async c=>r.clientsFor(await u(c)),statusOf:f}).close,oe(E,{resolver:{resolve:async(c,d)=>{let h=await e.resolve(R(c.headers.authorization)),y=B.connectionFor(h),C;try{C=await ie(y.clients,se(c),d)}catch(k){throw y.release().catch(()=>{}),k}return{...C,release:y.release}}}})];E.on("upgrade",(c,d)=>{let h=new URL(c.url??"/","http://localhost");h.pathname===X||h.pathname===ee||h.pathname===re||d.destroyed||(d.write(`HTTP/1.1 404 Not Found\r