@urun-sh/openai 0.6.19 → 0.6.21

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 je,e as cn,f as F,g as ce}from"./chunk-BAKPG5S3.js";import{a as pn,c as mn,d as we,e as ot,f as z,g as fn,h as hn,i as gn,j as yn,k as _n,l as wn,m as vn,n as bn,r as xn,t as kn,u as Sn,v as Rn,w as En,x as In}from"./chunk-3JWYIKHM.js";import{a as Pt}from"./chunk-6M5JK4YC.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{randomUUID as Qr}from"crypto";import{WebSocketServer as Zr}from"ws";var es=256,it=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>es;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},ts="local",He=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",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof F){this.ws.close(mn,He(e.message));return}if(e instanceof ce){this.ws.close(ot,He(e.message));return}if(e instanceof z){this.ws.close(e.closeCode,He(e.message));return}this.ws.close(we,He(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=fn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(s=>this.fail(s));return}if(!this.config)throw new z(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:s,turnComplete:o}=bn(n.clientContent);this.transcript.push(...s),o&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let s=kn(n.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:xn);return}this.transcript.push(...Sn(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new z("setup may only be sent once, as the first client message");let n=_n(e),r=n.sessionResumption.handle;if(r!==null){let o=this.registry.get(this.scope,r);if(!o)throw new z("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",ot);if(o.model!==n.model)throw new z(`sessionResumption.handle was issued for model "${o.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 z("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!==o.proxyHandle)throw new z(`sessionResumption.handle named pooled session "${o.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`,ot);this.unsubscribeEnd=await this.clients.onSessionEnd(o.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...o.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript.push(...n.systemItems);this.config=n;let s={};if(n.videoOut){let o=this.clients.openVideoOut;if(o){let i=await o.call(this.clients,n.model),a=i.onOutputFrame(u=>this.send(yn(u))),d=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),d()},s[hn]=gn(i.codec)}}this.send({setupComplete:s}),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 z("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new z("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",we);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(En(s))),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 z("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new z("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",we);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 z(`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 z("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 z("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=Qr();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(wn(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(vn(e.timeLeftMs)),this.ws.close(we,He(`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}),s,o=!1;for await(let d of r){if(n.interrupted)break;let u=d;if(u.type==="error")throw new z(`upstream error: ${JSON.stringify(u)}`,we);if(u.type==="response.completed"){s=u.response,o=!0;continue}let l=Rn(u);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!o)throw new z("upstream produced no response.completed event",we);let{messages:i,assistantItems:a}=In(s);this.transcript.push(...a);for(let d of i)this.send(d);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},ve=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function ns(t,e,n){let r=new Set;(d=>{if(typeof d=="string")d!==""&&r.add(d);else if(Array.isArray(d))for(let u of d)u!==""&&r.add(u)})(t.headers["x-goog-api-key"]);let o=t.headers.authorization;typeof o=="string"&&o.startsWith("Bearer ")&&o.length>7&&r.add(o.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new ve(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 ve(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 d of r)a=d;if(a===void 0&&n)throw new ve(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function An(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 Zr({noServer:!0}),s=new it;t.on("upgrade",(i,a,d)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===pn&&(a.on("error",()=>{}),(async()=>{let l=ns(i,u,n),c;if(e.authenticate)c=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new ve(401,"invalid local proxy api key");c={clients:e.clients,scope:ts}}r.handleUpgrade(i,a,d,v=>{new at(v,c,s)})})().catch(l=>{let c=502;(l instanceof ve||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(c=l.status);let v=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",p=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${c} ${v}\r
2
+ Connection: close\r
3
+ \r
4
+ ${p}\r
5
+ `),a.destroy())}))});let o=null;return()=>(o??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(d=>d===void 0?i():a(d)))})(),o)}function Ci(t,e,n=new it){new at(t,e,n)}A();import ss from"os";import os from"path";import{fileURLToPath as is}from"url";import{format as as}from"util";var On="0.6.21";var Pn=4141,us=On,ji={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 ds(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 Hi(t,e,n){let r={...t,...ds(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Gi(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"'],s=n.indexOf("--"),o=s===-1?n:n.slice(0,s),i=o.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",d=o.includes("--skip-git-repo-check"),u=a&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...u]}function Ji(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Vi(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Wi(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 s=is(new URL("../pi-extension/standalone.cjs",e));if(!n(s))throw new Error(`pi extension entry not found at ${s} \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 s}function Cn(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 zi(t){if(t[0]!=="--port")return null;let e=Cn(t[1]);return t.splice(0,2),e}function Yi(t){let e=t.indexOf("--port");if(e===-1)return Pn;let n=Cn(t[e+1]);return t.splice(e,2),n}function Xi(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 Ct(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 Ki(t){let e=ls(Ct(t,"URUN_BASE_URL")),n=Ct(t,"URUN_ORG_ID"),r=Ct(t,"URUN_APP"),s=(t.URUN_FUNCTION??"serve").trim()||"serve",o=(t.URUN_API_URL??"").trim(),i=o?Tn(o,"URUN_API_URL"):cn,a=(t.URUN_JWT??"").trim();if(a)return{baseUrl:e,orgId:n,appId:r,fnName:s,apiUrl:i,auth:{lane:"jwt",jwt:a}};let d=(t.URUN_API_KEY??"").trim();if(d){let u=(t.URUN_GATEWAY_URL??"").trim(),l=u?Tn(u):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:s,apiUrl:i,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 ls(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 Tn(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 Qi(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:us}}function cs(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 ps=250;async function ms(t,e=ps){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:s,org:o,fn:i,base_url:a,proxy_version:d}=r;return typeof s!="string"||typeof o!="string"||typeof i!="string"||typeof a!="string"||typeof d!="string"?null:{app:s,org:o,fn:i,base_url:a,proxy_version:d}}catch{return null}}var Ln=2e3;async function fs(t,e=Ln){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 Zi(t,e,n=Pn,r=Ln){if(t!=null)return{mode:"spawn",port:t};let s=await ms(n);if(s!==null&&cs(s,e)){let o=await fs(n,r);return o===null?{mode:"reuse",port:n,identity:s}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${o}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function ea(t,e=ss.homedir()){return os.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Lt=["log","info","warn","error","debug","trace"];function ta(t,e=process,n=console){let r=e.stdout.write,s=e.stderr.write,o=(a,...d)=>t.write(a,...d);e.stdout.write=o,e.stderr.write=o;let i=Object.fromEntries(Lt.map(a=>[a,n[a]]));for(let a of Lt)n[a]=(...d)=>{t.write(`${as(...d)}
6
+ `)};return()=>{e.stdout.write=r,e.stderr.write=s;for(let a of Lt)n[a]=i[a]}}var hs=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Mn(t){let e=t?.code;return typeof e=="string"&&hs.has(e)}function he(t,e){try{return t.write(e),!0}catch(n){if(Mn(n))return!1;throw n}}function na(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let s=t.streams[r],o=i=>{Mn(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{}};s.on("error",o),n.push([s,o])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,s]of n)r.off("error",s)}}}function ra(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(s){try{t.appendSync(t.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(s?.code??s)}) \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 sa(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 vs}from"@urun-sh/core";A();import{randomUUID as gs}from"crypto";function b(t){return`${t}_${gs().replace(/-/g,"").slice(0,24)}`}var ut=4*1024*1024,Mt=8*1024*1024,dt=512,lt=20*1024*1024;function q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Te(t,e){return{type:"server_error",code:t,message:e}}function $(t){return{type:"error",event_id:b("event"),error:t}}function $t(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var R=class extends Error{constructor(n,r,s="invalid_value"){super(n);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},ys={type:!0,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},_s={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},ws={format:!0,voice:!0,speed:!0};function $n(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new R(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Ge(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new R("session must be an object","session","invalid_request");let r=t,s=Object.keys(r).filter(i=>!(i in ys));if(s.length>0)throw new R(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");let o={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"type":{if(a!=="realtime"&&a!=="transcription")throw new R(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new R(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new R('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");o.type=a;break}case"model":if(a!==null&&typeof a!="string")throw new R("model must be a string or null","model");o.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new R("instructions must be a string or null","instructions");o.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new R("modalities must be a non-empty array","modalities");let d=[];for(let u of a){if(u!=="text"&&u!=="audio")throw new R(`modality ${JSON.stringify(u)} is not "text" or "audio"`,"modalities");if(u==="audio"&&!n.voice)throw new R('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");d.includes(u)||d.push(u)}o.outputModalities=d;break}case"voice":if(a===null){delete o.voice;break}if(typeof a!="string")throw new R("voice must be a string or null","voice");if(!n.voice)throw new R("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");o.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new R(`${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 R("temperature must be a finite number or null","temperature");o.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 R(`${i} must be a positive integer, "inf" or null`,i);o.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new R("tools must be an array","tools");o.tools=a;break;case"tool_choice":o.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new R("metadata must be an object or null","metadata");o.metadata=a??null;break;case"turn_detection":{if(a===null){o.turnDetection=null;break}if(!n.turns)throw new R("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 d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new R("turn_detection must be an object or null","turn_detection");let u=String(d.type??"");if(u!=="server_vad"&&u!=="semantic_vad")throw new R(`turn_detection.type ${JSON.stringify(d.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");o.turnDetection={createResponse:d.create_response!==!1,interruptResponse:d.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){o.inputAudioTranscription=!1;break}if(!n.turns)throw new R("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 R("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 R(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");let d=a.model;if(d!=null){let u=typeof d=="string"?d:JSON.stringify(d);if(typeof d!="string"||d!==n.model)throw new R(`input_audio_transcription.model ${JSON.stringify(u)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}o.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new R("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 d=a;if(!d||typeof d!="object"||Array.isArray(d))throw new R("audio must be an object or null","audio");if(d.input!==void 0&&d.input!==null){let u=d.input;if(!u||typeof u!="object"||Array.isArray(u))throw new R("audio.input must be an object","audio.input");for(let l of Object.keys(u))if(!(l in _s))throw new R(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(u.format!==void 0&&$n(u.format,"audio.input.format"),u.transcription!==null&&u.transcription!==void 0){let l=Ge({input_audio_transcription:u.transcription},o,n);o.inputAudioTranscription=l.inputAudioTranscription}if(u.turn_detection!==null&&u.turn_detection!==void 0){let l=Ge({turn_detection:u.turn_detection},o,n);o.turnDetection=l.turnDetection}if(u.noise_reduction!==null&&u.noise_reduction!==void 0)throw new R("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(d.output!==void 0&&d.output!==null){let u=d.output;if(!u||typeof u!="object"||Array.isArray(u))throw new R("audio.output must be an object","audio.output");for(let l of Object.keys(u))if(!(l in ws))throw new R(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(u.format!==void 0&&$n(u.format,"audio.output.format"),u.speed!==void 0)throw new R("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(u.voice!==void 0)if(u.voice===null)delete o.voice;else{if(typeof u.voice!="string")throw new R("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new R("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");o.voice=u.voice}u.format!==void 0&&!o.outputModalities.includes("audio")&&(o.outputModalities=["text","audio"])}break}default:break}return o}function ct(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",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 Ut(t,e){let n=t;if(!n||typeof n!="object")throw new R("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 R("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:b("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 R('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new R("message item content must be an array","item.content","invalid_request");let s=[];for(let o of n.content){let i=o;if(!i||typeof i!="object")throw new R("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 R(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");s.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new R("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 R("input_audio part requires base64 audio","item.content.audio","invalid_request");s.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new R(`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:b("item"),type:"message",role:r,content:s}}throw new R(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Nt(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 s=[];for(let o of r.content??[]){if(o.type==="input_text"||o.type==="output_text"){s.push({type:o.type,text:o.text});continue}if(o.type==="input_audio"){let i=o.transcript;if(typeof i=="string"&&i.trim().length>0){s.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:s})}return{input:e,sawAudioOnlyItem:n}}var bs=1001,xs=1011,Un=t=>t.slice(0,120),ks=/^[A-Za-z0-9+/=]*$/,Ss=2;function Rs(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Ss)return!1;return!0}var Je=class{id=b("conn");ws;binding;onClosed;config=$t();sessionId=b("sess");conversationId=b("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;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),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:b("event"),session:ct(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:b("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(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){!this.closed&&!e.signal.aborted&&this.send($(Te("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:b("event"),item_id:e,content_index:0,transcript:n})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:b("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:b("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.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:b("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:b("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let s=this.turnTranscript.text.trim(),o=s.length>0?s:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=o,this.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:b("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=b("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...o!==null?{transcript:o}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:b("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.created",event_id:b("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:b("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&o!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:b("event"),item_id:i,content_index:0,transcript:o}),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>ut){this.fail(q("frame_too_large",`frame exceeds the ${ut}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(q("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(s){let o=s;if(o&&typeof o=="object"&&o.name==="SessionUpdateError"){this.send($({type:"invalid_request_error",code:o.code??"invalid_value",message:o.message,param:o.param??null}));return}this.fail(Te(null,s instanceof Error?s.message:String(s)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Ge(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:b("event"),session:ct(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Ut(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:b("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($(q("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:b("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($(q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:b("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($(q("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:b("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($(q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ks.test(e.audio)){this.send($(q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>lt){this.send($(q("buffer_full",`uncommitted input audio exceeds the ${lt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;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.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:b("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send($(q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=b("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:b("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.created",event_id:b("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:b("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let o=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:b("event"),item_id:r,content_index:0,transcript:o}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send($(q("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send($(q("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send($(q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send($(q("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,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($({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 o=e.response??e;return r.sendResponseCreate({type:"response.create",response:o},e.input??[],n)}let s=this.binding.clients;if(s&&typeof s.createResponse=="function"){let{response:o,input:i,...a}=e;return await s.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($(q("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(E=>E!=="text"&&E!=="audio")){this.send($(q("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($(q("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=b("req"),s=`resp_${r}`;this.activeResponseId=s;let o=this.items.length,{input:i,sawAudioOnlyItem:a}=Nt(this.items),d=typeof n.instructions=="string"?n.instructions:this.config.instructions,u=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,v=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,x={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...d!==void 0?{instructions:d}:{},...u!==void 0?{temperature:u}:{},...c!==void 0?{max_output_tokens:c}:{},...v!==void 0?{tools:v}:{},...p!==void 0?{tool_choice:p}:{}};for(let E of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(E);this.inFlight=(async()=>{let E=[],k=S=>{this.responseFlushed?this.send(S):E.push(S)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:b("event"),response:this.responseObject(s,"in_progress")}),this.send({type:"response.in_progress",event_id:b("event"),response:this.responseObject(s,"in_progress")});for(let S of E)this.send(S);E.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},g=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let S;try{S=await this.upstreamStream(x,r)}catch(m){this.upstreamTurnFault(m,s);return}try{for await(let m of S){if(this.cancelled)break;let f=m;if(f.type==="error"){let w=this.upstreamErrorBody(f);this.responseFlushed?this.send($(w)):this.send({type:"response.failed",event_id:b("event"),response:this.failedResponse(s,w)});return}if(f.type==="response.output_text.delta"&&typeof f.delta=="string"){y(),h.messageOpen||(this.beginMessageItem(s,h.nextOutputIndex++),h.messageOpen=!0),k({type:"response.output_text.delta",event_id:b("event"),item_id:`${s}_msg_0`,response_id:s,output_index:0,content_index:0,delta:f.delta}),h.messageText+=f.delta;continue}if(f.type==="response.function_call_arguments.delta"){y();let w=typeof f.delta=="string"?f.delta:"",P=typeof f.call_id=="string"&&f.call_id.length>0?f.call_id:`${s}_fc_${h.nextOutputIndex}`,_=h.tools.get(P);if(!_){let I=typeof f.name=="string"&&f.name.length>0?f.name:void 0;_={outputIndex:h.nextOutputIndex++,name:I,args:""},h.tools.set(P,_),k({type:"response.output_item.added",event_id:b("event"),response_id:s,output_index:_.outputIndex,item:{id:P,object:"realtime.item",type:"function_call",call_id:P,name:I??"",arguments:"",status:"in_progress"}})}typeof f.name=="string"&&f.name.length>0&&(_.name=f.name),_.args+=w,k({type:"response.function_call_arguments.delta",event_id:b("event"),item_id:P,response_id:s,output_index:_.outputIndex,call_id:P,name:_.name??"",delta:w});continue}if(f.type==="response.completed"){g=f.response??null;continue}}}catch(m){this.upstreamTurnFault(m,s);return}if(this.cancelled)return;this.closeOpenItems(s,h,o),y(),this.send({type:"response.done",event_id:b("event"),response:this.doneResponse(s,o,g)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Rs(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send($({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:b("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:b("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:b("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:b("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:b("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:b("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:b("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 s=`${e}_msg_0`,o=this.messageItemOpenForAudio;o&&this.send({type:"response.output_audio.done",event_id:b("event"),item_id:s,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:b("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:b("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:o?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];o&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:s,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:b("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[s,o]of n.tools){let i=o.args.length>0?o.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:b("event"),item_id:s,response_id:e,output_index:o.outputIndex,call_id:s,name:o.name??"",arguments:i});let a={id:s,type:"function_call",callId:s,name:o.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:b("event"),response_id:e,output_index:o.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 s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,o=[];for(let i=n;i<this.items.length;i++)o.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:o,usage:s?{input_tokens:typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0,output_tokens:typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0,total_tokens:typeof s.total_tokens=="number"&&Number.isFinite(s.total_tokens)?s.total_tokens:(typeof s.input_tokens=="number"&&Number.isFinite(s.input_tokens)?s.input_tokens:0)+(typeof s.output_tokens=="number"&&Number.isFinite(s.output_tokens)?s.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let 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(Te("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 ce){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof vs&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Te(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send($(r)):this.send({type:"response.failed",event_id:b("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send($(q("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:b("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>dt&&(this.items.shift(),this.send($({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(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...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>Mt){this.ws.close(bs,Un("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send($(e)),this.ws.close(xs,Un(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Nn(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Nn(this.id,e)}},Bt=[];function Nn(t,e){Bt.push({id:t,reason:e}),Bt.length>256&&Bt.shift()}A();import{SessionFailedError as Os}from"@urun-sh/core";A();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Es}from"@urun-sh/core";var Is={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},As={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 Ft(t,e){let n=As[t.code];return e?`${n} (${e})`:n}function pt(t){if(t==null)return null;let e=Is[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 mt(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)>=Es;return pt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as Ts}from"ws";var Dt="/v1/realtime",Ps=t=>t.slice(0,120);function Cs(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
+ ${Ps(n)}\r
15
+ `),t.destroy()}function Ls(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
16
+ `}function Ms(t){he(process.stdout,t)}function $s(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function qt(t){return t.audioSession?.audio.sessionId??void 0}function jt(t,e){let n=new Ts({noServer:!0}),r=new Set;return t.on("upgrade",(s,o,i)=>{if(new URL(s.url??"/","http://localhost").pathname!==Dt)return;r.add(o),o.on("close",()=>{r.delete(o)});let d=b("rtup"),u=$s(s),l=m=>{(e.log??Ms)(Ls(m))};l({stage:"accept",conn:d,model:u}),o.resume();let c=new AbortController,v=null,p=m=>{v??=m,c.abort(new Error(v))},x=()=>p("client socket closed"),E=()=>p("client socket closed (half-close)"),k=m=>p(`client socket error: ${m.message}`);o.once("close",x),o.once("end",E),o.once("error",k);let y=()=>{o.removeListener("close",x),o.removeListener("end",E),o.removeListener("error",k)},h=m=>{l({stage:"close",conn:d,model:u,...m})},g=m=>{let f=m,w=f.session!=null&&typeof f.session.sendResponseCreate=="function",P=f.clients!=null&&typeof f.clients.createResponse=="function";if(!w&&!P)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((_,I)=>{n.handleUpgrade(s,o,i,C=>{try{new Je({ws:C,binding:m,onClosed:(U,W)=>{h({while:"live",reason:W.reason})}}),l({stage:"admit",conn:d,model:u,...qt(m)===void 0?{}:{session:qt(m)}}),_()}catch(U){I(U)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(s,c.signal).then(async m=>{if(c.signal.aborted){y();let f=qt(m);try{await m.release?.()}catch(w){h({while:"queued",...f===void 0?{}:{session:f},reason:v??"client socket closed",release_failed:w instanceof Error?w.message:String(w)});return}h({while:"queued",...f===void 0?{}:{session:f},reason:v??"client socket closed",released:!0}),o.destroy();return}y(),await g(m)}).catch(m=>{let f=m instanceof Os?mt(m):null,w=null;if(m!==null&&typeof m=="object"&&"status"in m){let I=m.status;typeof I=="number"&&(w=I)}let P=w??f?.status??502,_=m instanceof Error?m.message:String(m);h({while:"queued",...c.signal.aborted?{reason:v??"client socket closed"}:{reason:_,status:P}}),o.destroyed||Cs(o,P,_)}).finally(()=>{r.delete(o)})}),async()=>{let s=Date.now()+5e3;for(;r.size>0&&Date.now()<s;)await new Promise(o=>setTimeout(o,25));await new Promise(o=>n.close(()=>o()))}}A();A();A();import{createServer as ti}from"http";A();import{WebSocketServer as zs,WebSocket as Xe}from"ws";A();A();import{randomUUID as Us}from"crypto";var Bn="Inference-Id";function Ve(){return Us()}function Ht(t){return t==="/v1"||t.startsWith("/v1/")}function Fn(t,e){if(!Ht(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 We(t){return`resp_${t}`}function qn(t){return`chatcmpl-${t}`}function Dn(t){return`msg_${t}`}function se(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function jn(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,output_minutes:t.turn.outputMinutes,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 Hn(t){return`${JSON.stringify(t)}
17
+ `}var Ns=256,Bs=128;function te(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Bs)}var be=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>=Ns?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let s=this,o=performance.now(),i=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),s.ttftMs.push(i-o),s.ttftMs.length>512&&s.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,s.tokensOut+=1,s.charsOut+=u.delta.length,n!==void 0&&(s.modelEntry(n).tokens_out+=1)),yield u;let d=(performance.now()-(i??o))/1e3;a>0&&d>0&&(s.tokRates.push(a/d),s.tokRates.length>512&&s.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,s)=>r-s);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}}}},Fs=256;function qs(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 xe=class extends Error{},Pe=class{conversations=new Map;thread(e,n){let r=qs(n);if(e==null)return r;let s=this.conversations.get(String(e));if(!s)throw new xe(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...r]}remember(e,n,r,s=!0){this.conversations.set(e,[...n,...r]);for(let o of this.conversations.keys()){if(this.conversations.size<=Fs)break;this.conversations.delete(o)}}forget(e){this.conversations.delete(e)}},Gn=new WeakMap;function ze(t){let e=Gn.get(t);return e||(e=new Pe,Gn.set(t,e)),e}function Ce(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ue(t){return t.find(e=>e.type==="response.completed")?.response??null}function Le(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 ge=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}))}},Ds=["<tool_call>","<function="];function js(t){return Ds.find(e=>t.includes(e))}function ke(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 Se(t,e,n){if(!(!t||e>0))return js(n)}function Me(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 Hs(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 s=r;s.type==="message"?n.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&n.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return n}function Gt(t,e){let n=Hs(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var oe=class extends Error{constructor(n,r,s=400,o){super(n);this.code=r;this.status=s;this.param=o}code;status;param};function $e(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof xe?new oe(n.message,"previous_response_not_found",400,"previous_response_id"):new oe(String(n instanceof Error?n.message:n),"invalid_input")}}function Jn(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Jt(t,e,n,r,s){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new oe("instructions must be a string","invalid_instructions");let o=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,...o!==void 0?{instructions:o}:{},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}:{},...Jn(e)!==void 0?{response_format:Jn(e)}:{}},s)}async function Ye(t){let{body:e,clients:n,store:r,stats:s}=t,o=$e(r,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(o))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,d=e.store!==!1,u=te(e);s.model(u);let l=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,v=await Jt(n,e,o,!0,c?se(c):void 0);return{responseId:i,events:Ws({events:v,conversation:o,responseId:i,modelKey:u,requestHadTools:l,remember:a,persist:d,store:r,stats:s,turn:t.turn})}}function Gs(t,e){let n=[...t].sort((d,u)=>d.output_index-u.output_index).map(({item:d})=>d),r=Array.isArray(e?.output)?e.output:[],s=r.filter(d=>d!==null&&typeof d=="object"&&d.type==="message"),o=n.filter(d=>d.type==="message").length===s.length,i=0;return[...n.map(d=>d.type==="message"&&o?Vs(s[i++],d):d),...Js(r,n)]}function Js(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),s=u=>String(u.call_id??u.id??""),o=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=o.length===i,d=new Set(o.map(s));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let l=u;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!d.has(s(l)):!0})}function Vs(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 o=(Array.isArray(e.content)?e.content:[]).find(n);if(o===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:o.text}:a),i}async function*Ws(t){let{events:e,conversation:n,responseId:r,modelKey:s,requestHadTools:o,remember:i,persist:a,store:d,stats:u}=t,l=[],c=O=>O.response&&typeof O.response=="object"?{...O,response:{...O.response,id:r}}:O,v=`item_${r.slice(5)}`,p=!1,x=!1,E=0;function*k(){p||(p=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let y=[],h=(O,M)=>{y.push({output_index:O,item:M})},g=!1,S=0,m="",f=0,w="";function*P(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:m,output_index:S,content_index:0,text:w};let O={id:m,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:w}],status:"completed"};yield{type:"response.output_item.done",output_index:S,item:O},h(S,O),w=""}let _=!1,I=0,C="",U=0,W="",ee="";function*ie(O){if(!_)return;_=!1,yield{type:"response.output_text.done",item_id:C,output_index:I,content_index:0,text:W},yield{type:"response.content_part.done",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:W}};let M={id:C,type:"message",role:"assistant",status:O,content:[{type:"output_text",text:W}]};yield{type:"response.output_item.done",output_index:I,item:M},h(I,M),W=""}let me=new ge,D=null,j=-1;function*K(O){if(!D)return;let M=D;D=null,yield{type:"response.function_call_arguments.done",item_id:M.fcId,output_index:M.outputIndex,arguments:M.args};let J={id:M.fcId,type:"function_call",call_id:M.callId??M.fcId,name:M.name??"",arguments:M.args,status:O};yield{type:"response.output_item.done",output_index:M.outputIndex,item:J},h(M.outputIndex,J)}let _e=!1;for await(let O of u.track(e,s,t.turn)){l.push(O);let M=String(O.type??"");if(M==="response.created"||M==="response.in_progress"){p=!0,yield c(O);continue}if(M==="response.output_item.added"){x=!0,yield c(O);continue}if(M==="response.reasoning_text.delta"&&!x){yield*k(),g||(g=!0,S=E++,f+=1,m=f===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${f}`,yield{type:"response.output_item.added",output_index:S,item:{id:m,type:"reasoning",summary:[],content:[],status:"in_progress"}}),w+=String(O.delta??""),yield{type:"response.reasoning_text.delta",item_id:m,output_index:S,content_index:0,delta:O.delta};continue}if(M==="response.output_text.delta"&&!x){yield*k(),yield*P(),_||(_=!0,I=E++,U+=1,C=U===1?v:`${v}_${U}`,yield{type:"response.output_item.added",output_index:I,item:{id:C,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:""}}),W+=String(O.delta??""),ee+=String(O.delta??""),yield{type:M,item_id:C,output_index:I,content_index:0,delta:O.delta};continue}let J=x?null:Le(O);if(J){if(yield*k(),yield*P(),yield*ie("completed"),me.add(J),J.tool_index!==j){yield*K("completed"),j=J.tool_index;let le=E++;D={fcId:`fc_${r.slice(5)}_${J.tool_index}`,outputIndex:le,callId:J.call_id,name:J.name,args:""},yield{type:"response.output_item.added",output_index:le,item:{id:D.fcId,type:"function_call",call_id:D.callId??D.fcId,name:D.name??"",arguments:"",status:"in_progress"}}}D&&(J.call_id&&(D.callId=J.call_id),J.name&&(D.name=J.name),D.args+=J.delta,yield{type:"response.function_call_arguments.delta",item_id:D.fcId,output_index:D.outputIndex,delta:J.delta});continue}if(M==="response.completed"&&!x){let le=Ce(O.response),N=Se(o,me.size+le.length,ee);if(N){_e=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ke(s,N)}};break}if(yield*P(),yield*ie("completed"),yield*K("completed"),me.size===0)for(let fe of le){let Oe=E++,st=fe.id??fe.call_id??`fc_${Oe}`,Tt=fe.arguments??"",dn={id:st,type:"function_call",call_id:fe.call_id??st,name:fe.name??""};yield{type:"response.output_item.added",output_index:Oe,item:{...dn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:st,output_index:Oe,delta:Tt},yield{type:"response.function_call_arguments.done",item_id:st,output_index:Oe,arguments:Tt};let ln={...dn,arguments:Tt,status:"completed"};yield{type:"response.output_item.done",output_index:Oe,item:ln},h(Oe,ln)}let Q=Gs(y,O.response);yield Q.length>0?c({...O,response:{...O.response,output:Q}}):c(O);continue}yield c(O)}if(yield*P(),yield*ie("incomplete"),yield*K("incomplete"),i&&!_e){let O=ue(l);d.remember(r,n,Gt(O,Me(l,O)),a)}}var Ys="/v1/responses",Xs=64*1024*1024,Ks=8*1024*1024,Qs=16,Vn=32,Wn=3600*1e3,Zs=/^[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 eo=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 zt(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}async function to(t){for(;t.bufferedAmount>Ks&&t.readyState===Xe.OPEN;){let{promise:e,resolve:n}=zt();setTimeout(n,5),await e}}var Vt=class extends Pe{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(s){if(!(s instanceof xe))throw s;return this.shared.thread(n,r)}}remember(n,r,s,o=!0){o?this.shared.remember(n,r,s):super.remember(n,r,s)}forget(n){super.forget(n),this.shared.forget(n)}},Wt=class{constructor(e,n,r,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=s;this.store=new Vt(ze(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 (${Wn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Wn).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 s=r;if(s.type!=="response.create"){this.sendFrame(ne(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(s.type??null)}; only "response.create" is supported`}));return}if("stream"in s){this.sendFrame(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 s){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 o;if(s.stream_id!==void 0){if(typeof s.stream_id!="string"||!Zs.test(s.stream_id)){this.sendFrame(eo);return}if(o=s.stream_id,!this.lanes.has(o)&&this.namedLaneCount()>=Vn){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 (${Vn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},o));return}}let i=s.generate===!1?()=>this.runWarmup(s,o):()=>this.runTurn(s,o),a=o??"",d=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,d.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 s;try{s=await Ye({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:We(Ve())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(s.responseId,n??null);let o=s.events;this.activeTurns.add(o);try{for await(let i of o){if(this.closed||this.ws.readyState!==Xe.OPEN)break;this.send(i,n),await to(this.ws)}}finally{this.activeTurns.delete(o)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=We(Ve());try{let s=$e(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,s,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof oe)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 F)return ne(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof ce)return ne(503,{type:"upstream_error",code:"session_gone",message:r},n);let s=this.statusOf?.(e)??null;return s?ne(s.status,{type:s.openaiType,message:r},n):ne(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Qs;){let{promise:e,resolve:n}=zt();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!==Xe.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!==Xe.OPEN||this.ws.send(JSON.stringify(e))}};function ft(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",s=`${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(s)}\r
22
+ \r
23
+ ${s}`)}function zn(t,e){let n=new zs({noServer:!0,maxPayload:Xs}),r=new be,s=new Set,o=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,d=!1,u=(l,c,v)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{ft(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),p.pathname!==Ys){i.add(c);return}o.add(c);let x=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){ft(c,401,"invalid local proxy api key");return}let E;try{E=await a(l)}catch(k){let y=e.statusOf?.(k)??null;ft(c,y?.status??500,"upstream resolver rejected the connection");return}d||c.destroyed||(x=!0,n.handleUpgrade(l,c,v,k=>{o.delete(c),s.add(k),k.on("close",()=>s.delete(k));try{new Wt(k,E,r,e.statusOf)}catch{s.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!x&&!c.destroyed&&ft(c,500,"responses websocket upgrade failed")}).finally(()=>o.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:l,resolve:c}=zt();if(d)return c(),l;d=!0,t.off("upgrade",u);for(let p of o)p.destroy();o.clear();for(let p of i)p.destroy();i.clear();for(let p of s)p.close(1001,"server shutting down");let v=setTimeout(()=>{for(let p of s)p.readyState!==Xe.CLOSED&&p.terminate()},2e3);return v.unref?.(),n.close(()=>{clearTimeout(v),c()}),l}}}A();A();var Y=class extends Error{};async function ht(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Y(`request body exceeds the ${e}-byte limit`);let r=[],s=0;for await(let o of t){let i=o;if(s+=i.length,s>e)throw new Y(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function gt(t,e){let n=t[Symbol.asyncIterator](),r=0,s=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 Y(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),o;try{let i=new Headers;for(let[u,l]of Object.entries(t.headers))if(typeof l=="string")i.set(u,l);else if(Array.isArray(l))for(let c of l)i.append(u,c);let a={method:"POST",headers:i,body:s,duplex:"half"};o=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof Y?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return o}var Yn="/v1/images/generations",yt="/v1/images/edits";function Xn(t){return t===Yn||t===yt}var Kn="/v1/images/models";async function Qn(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 s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:s??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 L=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},no=16*1024*1024,Zn=64*1024*1024;function er(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 tr(t,e,n,r){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),o=null;for await(let c of s){if(c.type==="error"){let v=c.error??{};throw new L(502,`image upstream error: ${String(v.message??"upstream reported an error")}`)}if(c.type==="response.completed"){o=c.response??null;break}}if(o===null)throw new L(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=o.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new L(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=[],d=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],u=Buffer.from(d,"base64");if(er(u)===null)throw new L(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${u.length} bytes) \u2014 refusing to pass it through`);return a.push(d),{images:a}}function nr(t){return t instanceof L?t:t instanceof F?new L(404,t.message):new L(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function rr(t,e,n,r){if(await t(e,n))return!0;let s=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Ke(r,new L(404,e===void 0?`no image-capable default model is configured for this caller (${s}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${s}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function sr(t,e){t&&(t.outputUnits=e.images.length)}function or(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 ro={model:!0,prompt:!0,response_format:!0,n:!0};async function ir(t,e,n){let r=n.maxBodyBytes??Zn;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${Yn}`);let s;try{s=JSON.parse((await ht(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof Y?new L(413,c.message):new L(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new L(400,"request body must be a JSON object");let o=s;for(let c of Object.keys(o))if(!ro[c])throw new L(400,`request field "${c}" 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.`,c);let i=o.prompt;if(typeof i!="string"||i.trim().length===0)throw new L(400,"prompt is required and must be a non-empty string","prompt");let a=o.model===void 0?void 0:o.model;if(a!==void 0&&typeof a!="string")throw new L(400,"model must be a string","model");await Qn(n.turn,n.clients,a);let d=o.n??1;if(d!==1)throw new L(400,`n=${JSON.stringify(d)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let u=o.response_format??"b64_json";if(u!=="b64_json")throw new L(400,`response_format ${JSON.stringify(u)} 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 rr(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await tr(n.clients,a,l,n.turn?se(n.turn):void 0);sr(n.turn,c),or(e,c)}catch(c){throw nr(c)}}catch(s){if(s instanceof Y){Ke(e,new L(413,s.message));return}if(s instanceof L){Ke(e,s);return}throw s}}var so={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ar(t,e,n){let r=n.maxBodyBytes??Zn,s=n.maxImagePartBytes??no;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${yt}`);let o=String(t.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new L(400,`the edit endpoint consumes multipart/form-data, got ${o||"none"}`);let i;try{i=await gt(t,r)}catch(p){throw p instanceof Y?new L(413,p.message):new L(400,String(p instanceof Error?p.message:p))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new L(400,"prompt is required and must be a non-empty string field","prompt");let d=i.get("model");if(d!==null&&typeof d!="string")throw new L(400,"model must be a string field","model");let u=d===null?void 0:d;await Qn(n.turn,n.clients,u);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new L(400,`response_format ${JSON.stringify(l)} 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(!so[p])throw new L(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 c=[];for(let p of["image","image[]"])for(let x of i.getAll(p)){if(!(x instanceof File))throw new L(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(x.size>s)throw new L(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let E=new Uint8Array(await x.arrayBuffer()),k=er(E);if(k===null)throw new L(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);c.push({bytes:E,mime:k})}if(c.length===0)throw new L(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await rr(n.imageModels,u,"edit",e))return;let v=[{type:"input_text",text:a}];for(let{bytes:p,mime:x}of c)v.push({type:"input_image",image_url:`data:${x};base64,${Buffer.from(p).toString("base64")}`});try{let p=await tr(n.clients,u,v,n.turn?se(n.turn):void 0);sr(n.turn,p),or(e,p)}catch(p){throw nr(p)}}catch(o){if(o instanceof Y){Ke(e,new L(413,o.message));return}if(o instanceof L){Ke(e,o);return}throw o}}A();var Qe="/v1/audio/speech";function gr(t){return t===Qe}var ur=4096,dr=18e4,lr=5e3,oo=64*1024*1024,cr=8,pr=5,mr=1024*1024,Ue="voice_applied",wt="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,s){super(n),this.status=e,this.param=r,this.retryAfterSeconds=s}};function Yt(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)}};function yr(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function _r(t){return new T(502,`the runtime's ${Ue} receipt ${JSON.stringify(t)} cannot be relayed as the ${wt} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function io(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 s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:s??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 wr(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var ao=2;function uo(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>ao)return!1;return!0}function lo(t){let e=24e3,n=2,r=1,s=Buffer.alloc(44);return s.write("RIFF",0,"ascii"),s.writeUInt32LE(36+t,4),s.write("WAVE",8,"ascii"),s.write("fmt ",12,"ascii"),s.writeUInt32LE(16,16),s.writeUInt16LE(1,20),s.writeUInt16LE(r,22),s.writeUInt32LE(e,24),s.writeUInt32LE(e*r*n,28),s.writeUInt16LE(r*n,32),s.writeUInt16LE(16,34),s.write("data",36,"ascii"),s.writeUInt32LE(t,40),s}var fr=new WeakMap,_t=new WeakMap;function co(t,e){let n=_t.get(t)??0;if(n>=cr)throw new T(503,`this model's speech queue is full \u2014 ${cr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${pr}s`,void 0,pr);_t.set(t,n+1);let r=fr.get(t)??Promise.resolve(),s,o=new Promise(i=>{s=i});return fr.set(t,o),(async()=>{await r;try{return await e()}finally{_t.set(t,(_t.get(t)??1)-1),s()}})()}async function po(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 ce))throw i}if(n?.return===void 0)return;let s=Promise.resolve(n.return()).then(()=>{},()=>{}),o;await Promise.race([s,new Promise(i=>{o=setTimeout(i,r)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}function Re(t){return t instanceof T?t:t instanceof F?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function hr(t,e,n,r,s,o,i,a){let d=a??(()=>{});return co(e,async()=>{if(i?.()===!0)return null;let u=!1,l=!1,c=!1,v,p=new Promise(m=>{v=m}),x=[],E=()=>{l&&!c&&x.length>=s.quietRunFrames&&(c=!0,v())},k=e.onOutputAudio(m=>{let f=Buffer.from(m,"base64");if(f.byteLength===0)return;let w=uo(f);if(!u){if(w)return;u=!0}if(w){x.push(f),E();return}for(let P of x)d(P);x.length=0,d(f),E()}),y=null,h,g,S;try{S=(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 f=new Promise(_=>{g=setTimeout(_,o.capMs)}),w=!1;for(;;){let _=S.next(),I=await Promise.race([_,f]);if(I===void 0){w=!0,_.catch(()=>{});break}if(I.done)break;let C=I.value;if(C.type==="error"){let U=C.error??{};throw await S.return?.(),new T(502,`speech upstream error: ${String(U.message??"upstream reported an error")}`)}if(C.type==="response.completed"){y=C.response??null,l=!0,E(),await S.return?.();break}}if(clearTimeout(g),w)throw new T(504,`the speech turn produced no terminal event within ${o.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(y===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=!1;if(await Promise.race([p,new Promise(_=>{h=setTimeout(()=>{P=!0,_()},s.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let _=y[Ue];if(typeof _!="string"||_!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof _=="string"?`${Ue} ${JSON.stringify(_)}`:`no ${Ue} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new vt(I):new T(502,I)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(P&&!c&&x.length<1)throw new T(502,`the upstream audio stream did not quiesce within ${s.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(m){throw m instanceof vt||await po(t,n,S,o.returnBoundMs),m}finally{h!==void 0&&clearTimeout(h),g!==void 0&&clearTimeout(g),k()}})}function mo(t,e,n,r){let s=!1,o=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(s||(s=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",wt)),t.write(a,d=>{d||(o+=a.byteLength,wr(e,o))}),t.writableLength>mr&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${mr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>s,async finish(a){if(!n()){if(r){let d=a[Ue];if(typeof d=="string"){if(!yr(d))throw _r(d);t.addTrailers({[wt]:d})}}await new Promise(d=>{t.end(()=>d())})}},fail:i}}async function fo(t,e,n){let r;try{r=await t(e)}catch(s){throw Re(s)}return r?!0:(Yt(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 ho={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},go="wav, pcm";async function vr(t,e,n){let r=n.maxBodyBytes??oo,s=!1;e.once("close",()=>{s=!0});let o=()=>s||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Qe}`);let i;try{i=JSON.parse((await ht(t,r)).toString("utf8")||"{}")}catch(g){throw g instanceof Y?new T(413,g.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 g of Object.keys(a))if(!ho[g])throw new T(400,`request field "${g}" 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.`,g);let d=a.input;if(typeof d!="string"||d.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(d.length>ur)throw new T(400,`input is ${d.length} chars \u2014 over the ${ur}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let u=a.model===void 0?void 0:a.model;if(u!==void 0&&typeof u!="string")throw new T(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.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 ${Qe} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(u)}catch(g){throw Re(g)}if(c.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let v=typeof l=="string"?l:void 0;if(v!==void 0&&c.published.length>0&&!c.published.includes(v))throw new T(400,`voice ${JSON.stringify(v)} is not one of the voices this model publishes \u2014 accepted voices: ${c.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 ${go} \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 x=a.speed;if(x!==void 0){if(typeof x!="number"||!Number.isFinite(x))throw new T(400,"speed, when present, must be a number","speed");if(x!==1)throw new T(400,`speed=${JSON.stringify(x)} 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 E=a.instructions;if(E!==void 0){if(typeof E!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(E.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 io(n.turn,n.clients,u);let k=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",k,k),!await fo(n.speechModels,u,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(o())return;let y;try{y=await n.clients.speechSessionHandle(u)}catch(g){throw Re(g)}let h;try{h=await n.clients.openAudioOn(y)}catch(g){throw Re(g)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(p==="wav"){let g=[],S=await hr(n.clients,h,y,{model:u,text:d,...v!==void 0?{voice:v}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??dr,returnBoundMs:n.turnReturnBoundMs??lr},o,f=>g.push(f));if(S===null||o())return;let m=Buffer.concat(g);if(v===void 0){let f=S[Ue];if(typeof f=="string"){if(!yr(f))throw _r(f);e.setHeader(wt,f)}}wr(n.turn,m.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([lo(m.byteLength),m]))}else{let g=mo(e,n.turn,o,v===void 0),S;try{S=await hr(n.clients,h,y,{model:u,text:d,...v!==void 0?{voice:v}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??dr,returnBoundMs:n.turnReturnBoundMs??lr},o,g.sink)}catch(m){let f=Re(m);if(!g.started())throw f;n.turn&&(n.turn.streamError=!0),g.fail(f);return}if(S===null)return;try{await g.finish(S)}catch(m){let f=Re(m);n.turn&&(n.turn.streamError=!0),g.fail(f);return}}}catch(g){throw Re(g)}}catch(i){if(i instanceof Y){Yt(e,new T(413,i.message));return}if(i instanceof T){Yt(e,i);return}throw i}}A();var bt="/v1/audio/transcriptions";function br(t){return t===bt}var xr="/v1/audio/models",yo=16*1024*1024,_o=64*1024*1024,B=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Xt(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 kr(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 wo(t){if(!kr(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let o=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(o==="fmt "&&a+16<=t.length){let d=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:d,bitsPerSample:l}}else if(o==="data"){let d=t.length-a;r=Math.min(i===0||i===4294967295?d:i,d)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let s=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(s)||s<0?null:{seconds:s,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function vo(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 s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:s??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 bo(t,e){t&&(t.outputUnits=e.seconds)}async function xo(t,e,n,r,s){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},s),i=[],a=null;for await(let d of o){if(i.push(d),d.type==="error"){let u=d.error??{},l=typeof u.type=="string"?u.type:"upstream_error",c=String(u.message??"upstream reported an error");throw new B(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(d.type==="response.completed"){a=d.response??null;break}}if(a===null)throw new B(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Me(i,a)}function Sr(t){return t instanceof B?t:t instanceof F?new B(404,t.message):new B(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function ko(t,e,n){let r;try{r=await t(e)}catch(s){throw Sr(s)}return r?!0:(Xt(n,new B(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 So=new Set(["file","model","language","response_format"]);async function Rr(t,e,n){let r=n.maxBodyBytes??_o,s=n.maxAudioPartBytes??yo;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${bt}`);let o=String(t.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new B(400,`the transcriptions endpoint consumes multipart/form-data, got ${o||"none"}`);let i;try{i=await gt(t,r)}catch(y){throw y instanceof Y?new B(413,y.message):new B(400,String(y instanceof Error?y.message:y))}let a=new Map;for(let y of i.keys()){if(!So.has(y))throw new B(400,`form field "${y}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,y);a.set(y,(a.get(y)??0)+1)}for(let[y,h]of a)if(h>1)throw new B(400,`form field "${y}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let d=i.get("model");if(d!==null&&typeof d!="string")throw new B(400,"model must be a string field","model");let u=d===null?void 0:d,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new B(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,v=i.get("response_format")??"json";if(v!=="json")throw new B(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 B(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>s)throw new B(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let x=new Uint8Array(await p.arrayBuffer());if(!kr(x))throw new B(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 E=wo(x);if(E===null)throw new B(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 vo(n.turn,n.clients,u),n.stats?.request("audio_transcriptions",x.length,x.length),!await ko(n.transcriptionModels,u,e))return;let k=[{type:"input_audio",input_audio:{data:Buffer.from(x).toString("base64"),format:"wav"}}];try{let y=await xo(n.clients,u,k,c,n.turn?se(n.turn):void 0);bo(n.turn,E),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw Sr(y)}}catch(o){if(o instanceof Y){Xt(e,new B(413,o.message));return}if(o instanceof B){Xt(e,o);return}throw o}}A();var Tr="/v1/usage/requests",Er=1e4,Ro=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ye=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},V=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},xt=class extends V{constructor(e){super(e),this.name="UsageWithholdingError"}},Pr=1024*1024;function Zt(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ye(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ye(`"${e}" must be an array of uuid strings`);if(n.length>Er)throw new ye(`"${e}" carries ${n.length} ids; at most ${Er} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],s=new Set;for(let o of n){if(typeof o!="string"||!Ro.test(o))throw new ye(`"${e}" contains ${JSON.stringify(o)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);s.has(o)||(s.add(o),r.push(o))}return r}function Cr(t){return Zt(t,"inference_ids")}var Eo=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function Ne(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new V(`${n}: ${e} is not a non-empty string (got ${Fe(r)})`);return r}function Kt(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new V(`${n}: ${e} is neither null nor a non-empty string (got ${Fe(r)})`);return r}function Be(t,e,n,r){let s=t[e];if(s===null)return null;let o=typeof s=="number"?s:typeof s=="string"&&/^-?\d+(\.\d+)?$/.test(s.trim())?Number(s.trim()):NaN;if(!Number.isFinite(o))throw new V(`${n}: ${e} is not a number (got ${Fe(s)})`);if(r&&!Number.isSafeInteger(o))throw new V(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(o<0)throw new V(`${n}: ${e} is negative`);return Object.is(o,-0)?0:o}var Io=40,Ir=64,Ar=600;function Lr(t){let e=Object.keys(t).sort(),r=e.slice(0,Io).map(s=>s.length>Ir?`${s.slice(0,Ir)}\u2026`:s).join(", ");return r.length>Ar&&(r=`${r.slice(0,Ar)}\u2026`),`${e.length} keys present: [${r}]`}function Fe(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Qt(t){he(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
24
+ `)}function Ao(t,e){let n;try{n=t(e)}catch{Or(t,e);return}Oo(n)&&Promise.resolve(n).catch(()=>{Or(t,e)})}function Oo(t){return typeof t?.then=="function"}function Or(t,e){if(t!==Qt)try{Qt(e)}catch{}}function cu(t,e=Qt){let n=t?.requests;if(!Array.isArray(n)){let s=t!==null&&typeof t=="object"&&!Array.isArray(t)?Lr(t):Fe(t);throw new V(`the usage surface answered without a "requests" array: got ${Fe(n)} (${s})`)}let r=[];for(let s=0;s<n.length;s++){let o=`usage.requests[${s}]`;try{r.push(To(n[s],o))}catch(i){if(i instanceof xt||!(i instanceof V))throw i;Ao(e,{where:o,reason:i.message})}}if(n.length>0&&r.length===0)throw new V(`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 To(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new V(`${e} is not an object: got ${Fe(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 s of Eo)if(!Object.hasOwn(n,s))throw new V(`${e} has no "${s}" column (${Lr(n)})`);let r=Be(n,"http_status",e,!0);if(r===null)throw new V(`${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:Kt(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:Be(n,"prompt_tokens",e,!0),completion_tokens:Be(n,"completion_tokens",e,!0),output_units:Be(n,"output_units",e,!1),output_minutes:Be(n,"output_minutes",e,!1),cost_nano_usd:Be(n,"cost_nano_usd",e,!0),price_version:Kt(n,"price_version",e),priced_at:Kt(n,"priced_at",e)}}function kt(t,e){let n=new Set(e),r=new Set;for(let s=0;s<t.length;s++){let o=t[s];if(!n.has(o.inference_id))throw new V(`the usage surface returned an id at validated answer position ${s} 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(o.inference_id))throw new V(`the usage surface returned ${o.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(o.inference_id)}}import{SessionAllocationError as ni,SessionFailedError as ri}from"@urun-sh/core";A();var en="/partners/huggingface/v1/billing/requests";function Po(t){return Zt(t,"requestIds")}function Co(t){return t>=200&&t<=399}function Lo(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Co(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Mr(t,e){let n=Po(t),r=await e(n);return kt(r,n),Lo(r)}A();var Mo={"/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 $o(t){return Mo[t]??null}var Nr=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Uo(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function No(t){return t==="surface"}function Bo(t){let e=t?.ledgerFailureReason;return Nr.includes(e)?e:"unknown"}var Fo=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],$r=["priced","unpriced"],qo={written:$r,already_written:$r,skipped:Fo,failed:Nr},_u=Object.entries(qo).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Do(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function jo(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 Ho=256,Ur=4096,Ze=12e4,Go=250,Jo=8e3,pe=[],tn=new Set,et=0,qe=!1;function wu(){return pe.length}function vu(t=Date.now()){let e=pe[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var St=new Set;function Br(){return et===0&&pe.length===0}function Fr(){if(Br()){qe=!1;for(let t of[...St])t()}}async function bu(t=qr){return Br()?!0:await new Promise(e=>{let n=null,r=()=>{St.delete(r),n&&clearTimeout(n),e(!0)};St.add(r),n=setTimeout(()=>{St.delete(r),e(!1)},t),n.unref?.()})}function xu(){qe=!0;let t=[...pe.splice(0,pe.length),...tn];for(let e of t)e.settled||Ee(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 ${qr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Fr(),t.length}var qr=5e3;function Dr(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
25
+ `}function Vo(t){he(process.stdout,t)}function jr(t,e){try{t(e)}catch{}}function Hr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Vo,s=$o(e.path);if(s===null)return;let o=l=>{try{n.observe(l)}catch{}},i=(l,c)=>{o({outcome:"skipped",reason:l}),jr(r,Dr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};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 d;if(a.kind==="catalog")d={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}d={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...d,task:s,http_status:e.status,started_at:jo(e),completed_at:e.ts,billable_outcome:Do(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,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(pe.length>=Ur){i("queue_full",`${pe.length} ledger writes are already waiting (capacity ${Ur}, ${et} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}pe.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),et<Ho&&(et+=1,Wo())}async function Wo(){try{for(;;){let t=zo();if(t===void 0)return;tn.add(t);try{await Yo(t)}finally{tn.delete(t)}}}finally{et-=1,Fr()}}function zo(){let t=Date.now();for(;;){let e=pe.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Ze)return e;Ee(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 ${Ze}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 Yo(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let s=await r.write(t.req,e);Ee(t,{outcome:"written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:s.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:s.cost_nano_usd,price_version:s.price_version,unpriced_reason:s.unpriced_reason,attempts:t.attempts});return}catch(s){let o=Uo(s);if(o!==null){Ee(t,{outcome:"already_written",reason:o.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:o.cost_nano_usd,price_version:o.price_version,attempts:t.attempts});return}let i=Bo(s),a=Date.now()-t.queuedAt;if(qe){Ee(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: ${s instanceof Error?s.message:String(s)}`});return}if(No(i)&&a<Ze){if(await Ko(Xo(t.attempts)),qe||Date.now()-t.queuedAt>=Ze){let d=Date.now()-t.queuedAt;Ee(t,{outcome:"failed",reason:qe?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:qe?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:d,error:`this row's backoff outlived the ${Ze}ms dwell bound (waited ${d}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${s instanceof Error?s.message:String(s)}`});return}continue}Ee(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:s instanceof Error?s.message:String(s)});return}}}function Xo(t){return Math.min(Jo,Go*2**Math.max(0,t-1))}function Ko(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ee(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...s}=n;jr(t.report,Dr(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...s}))}A();var rn="x-urun-profile",tt="voice";var re=class extends Error{status=400},Qo=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Zo=/\s/;function ei(t){return Qo.test(t)}function nn(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 Gr(t,e,n,r={}){let s=t[e];if(s===void 0)return n;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(s)})`);if(r.min!==void 0&&s<r.min)throw new re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(s)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&s>r.max)throw new re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(s)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return s}function 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 s=r,o=s?.profile,i=!1;if(n!=null){let u=n.trim();if(u==="")throw new re(`the ${rn} header is empty \u2014 the only profile this lane accepts is "${tt}" (omit the header for the ordinary lane)`);if(u!==tt)throw new re(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${tt}"`);i=!0}if(o!==void 0){if(typeof o!="string"||o!==tt)throw new re(`unknown profile ${JSON.stringify(o)} \u2014 the only profile this lane accepts is "${tt}"`);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=s?.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 d=a??{};return{flushMaxChars:Gr(d,"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:Gr(d,"flush_max_ms",250,{max:2147483647}),sentenceFlush:nn(d,"sentence_flush",!0),includeReasoning:nn(d,"include_reasoning",!1),metadata:nn(d,"metadata",!1)}}var Rt=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&&ei(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let s=e-1;s>0;s--)if(Zo.test(this.buffer[s]))return s+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)}};function an(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function si(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 Z(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function X(t,e,n,r="invalid_request_error",s){Z(t,e,{error:s?{message:n,type:r,code:s}:{message:n,type:r}})}function un(t,e){let n=e.error,r=n?.type??"upstream_error",s=n?.message??JSON.stringify(e);Z(t,r==="invalid_request_error"?400:502,{error:{message:s,type:r,code:n?.code??null}})}function de(t,e,n,r){Z(t,e,{type:"error",error:{type:n,message:r}})}function De(t,e,n){if(e==="anthropic"){Z(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}Z(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var oi=64*1024*1024,nt=class extends Error{};async function Vr(t,e=oi){let n=[],r=0;for await(let o of t){if(r+=o.length,r>e)throw new nt(`request body exceeds ${e} bytes`);n.push(o)}let s=Buffer.concat(n).toString("utf8");return s?JSON.parse(s):{}}function Ie(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 Yr(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=d=>typeof d=="number"&&Number.isFinite(d)&&d>=0?d:null,s=r(n.input_tokens),o=r(n.output_tokens),i=d=>d??0,a=r(n.total_tokens)??i(s)+i(o);if(i(s)>0||i(o)>0){let d={input_tokens:i(s),output_tokens:i(o),total_tokens:a};return s===null||o===null?{kind:"partial",usage:d}:{kind:"counts",usage:d}}return s===null||o===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Et(t){let e=Yr(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Wr(t){let e=Et(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 ii(t,e){let n=Yr(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function ai(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=d=>{let u=n[d];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},s=r("queue_ms"),o=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return s===null||o===null||i===null||a===null?null:{queue_ms:s,prefill_ms:o,decode_ms:i,total_ms:a}}function ui(t,e){let n=ai(e);n&&(t.timing=n)}function Ae(t,e){ii(t,e),ui(t,e)}async function Ot(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 s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:s??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 Xr(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 s of r.content)s.type==="reasoning_text"&&(n+=String(s.text??""));return n}function di(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 It=class extends Error{};function li(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 s=r.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new It(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function ci(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 s=r.function??{};e.push({type:"function_call",call_id:r.id,name:s.name,arguments:s.arguments})}continue}e.push({...n,content:li(n.role,n.content)})}return e}function sn(t){return Ce(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 pi(t,e,n,r,s,o){let i=We(o.id),a=t.stream===!0;if(o.model=te(t),o.stream=a,await Ot(o,e,typeof t.model=="string"?t.model:void 0),a){let y;try{y=await Ye({body:t,clients:e,store:n,stats:s,responseId:i,turn:o})}catch(h){if(h instanceof F){De(r,"openai",h);return}if(h instanceof oe){X(r,h.status,h.message);return}throw h}an(r);for await(let h of y.events)h.type==="error"&&(o.streamError=!0),h.type==="response.completed"&&Ae(o,h.response),r.write(`event: ${String(h.type??"message")}
26
+ data: ${JSON.stringify(h)}
27
+
28
+ `);r.write(`data: [DONE]
29
+
30
+ `),r.end();return}let d;try{d=$e(n,t)}catch(y){if(y instanceof oe){X(r,y.status,y.message);return}throw y}t.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(d))-Buffer.byteLength(JSON.stringify(t.input)));let u=t.store!==!1,l=te(t);s.model(l);let c=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await Jt(e,t,d,!1,se(o))}catch(y){if(y instanceof F){De(r,"openai",y);return}if(y instanceof oe){X(r,y.status,y.message);return}throw y}let p=[],x=null;for await(let y of s.track(v,l,o)){if(p.push(y),y.type==="error"){un(r,y);return}y.type==="response.completed"&&(x=y.response)}if(x==null){X(r,502,"upstream produced no response.completed event","upstream_error");return}Ae(o,x);let E=Me(p,x),k=Se(c,Ce(x).length,E);if(k){X(r,502,ke(l,k),"upstream_error");return}u&&n.remember(i,d,Gt(x,E),u),Z(r,200,{...x,id:i})}async function mi(t,e,n,r,s,o){let i=t.messages;if(!Array.isArray(i)){X(n,400,"chat/completions requires a messages array");return}let a;try{a=Jr(o,t)}catch(_){if(_ instanceof re){X(n,_.status,_.message);return}throw _}let d=String(t.model??"urun"),u=qn(s.id),l;try{l=ci(i)}catch(_){if(_ instanceof It){X(n,400,_.message);return}throw _}let c=te(t);r.model(c),s.model=c,s.stream=t.stream===!0,await Ot(s,e,typeof t.model=="string"?t.model:void 0);let v=Array.isArray(t.tools)&&t.tools.length>0,p;try{p=await e.createResponse({model:t.model,input:l,stream:!0,tools:di(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}:{}},se(s))}catch(_){if(_ instanceof F){De(n,"openai",_);return}throw _}if(t.stream===!0){a?si(n):an(n);let _=[],I=new ge,C="",U=a?new Rt(a,ee=>{n.write(`data: ${JSON.stringify(Ie(u,d,{content:ee},null))}
31
+
32
+ `)}):null,W=ee=>{U?.flush(),n.write(ee),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:u,model:d,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
33
+
34
+ `),n.write(`data: ${JSON.stringify(Ie(u,d,{role:"assistant"},null))}
35
+
36
+ `);for await(let j of r.track(p,c,s)){_.push(j);let K=Le(j);if(j.type==="response.output_text.delta"&&typeof j.delta=="string")C+=j.delta,U?U.push(j.delta):n.write(`data: ${JSON.stringify(Ie(u,d,{content:j.delta},null))}
37
+
38
+ `);else if(j.type==="response.reasoning_text.delta"&&typeof j.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Ie(u,d,{reasoning_content:j.delta},null))}
39
+
40
+ `);else if(K){U?.flush();let{call:_e,isNew:O}=I.add(K),M=O?{index:K.tool_index,id:_e.id??`call_${K.tool_index}`,type:"function",function:{name:_e.name??"",arguments:K.delta}}:{index:K.tool_index,function:{arguments:K.delta}};n.write(`data: ${JSON.stringify(Ie(u,d,{tool_calls:[M]},null))}
41
+
42
+ `)}else if(j.type==="error"){s.streamError=!0,W(`data: ${JSON.stringify({error:j})}
43
+
44
+ `);return}}let ee=sn(ue(_)),ie=Se(v,I.size+ee.length,C);if(ie){s.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ke(c,ie)}})}
45
+
46
+ `);return}U?.flush(),I.size===0&&ee.length>0&&n.write(`data: ${JSON.stringify(Ie(u,d,{tool_calls:ee},null))}
47
+
48
+ `);let me=I.size>0||ee.length>0;n.write(`data: ${JSON.stringify(Ie(u,d,{},me?"tool_calls":"stop"))}
49
+
50
+ `);let D=Et(ue(_));Ae(s,ue(_)),D&&n.write(`data: ${JSON.stringify({id:u,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:d,choices:[],usage:Wr(ue(_))})}
51
+
52
+ `),n.write(`data: [DONE]
53
+
54
+ `),n.end();return}finally{U?.flush(),U?.dispose()}}let x="",E="",k=[],y=new ge;for await(let _ of r.track(p,c,s)){k.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(x+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(E+=_.delta);let I=Le(_);if(I&&y.add(I),_.type==="error"){un(n,_);return}}let h=ue(k);Ae(s,h);let g=sn(h),S=g.length>0?g:sn({output:y.items()}),m=Se(v,S.length,x);if(m){X(n,502,ke(c,m),"upstream_error");return}let f=S.map(({index:_,...I})=>I),w={role:"assistant",content:x||null},P=E||Xr(h);P&&(w.reasoning_content=P),f.length>0&&(w.tool_calls=f),Z(n,200,{id:u,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:d,choices:[{index:0,message:w,finish_reason:f.length>0?"tool_calls":"stop"}],usage:Wr(h)})}var fi="reflex-latest";async function hi(t,e,n,r,s){if(t===null||typeof t!="object"||Array.isArray(t)){X(n,400,"systemone requires a JSON object body");return}delete t.key;let o=typeof t.model=="string"&&t.model?t.model:fi,i=te({model:o});if(s.model=i,s.stream=!1,t.state===void 0||t.state===null){X(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){X(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){X(n,400,"systemone media, when present, must be an array");return}r.model(i),await Ot(s,e,o);let d;try{d=await e.createResponse({model:o,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},se(s))}catch(p){if(p instanceof F){De(n,"openai",p);return}throw p}let u=[];try{for await(let p of r.track(d,i,s))if(u.push(p),p.type==="error"){un(n,p);return}}catch(p){if(p instanceof F){De(n,"openai",p);return}throw p}let l=ue(u);if(l==null){X(n,502,"upstream produced no response.completed event","upstream_error");return}Ae(s,l);let c=Me(u,l),v;try{v=JSON.parse(c)}catch{X(n,502,"systemone answer was not valid JSON","upstream_error");return}if(v===null||typeof v!="object"||Array.isArray(v)){X(n,502,"systemone answer was not a JSON object","upstream_error");return}Z(n,200,v)}function gi(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var rt=class extends Error{};function At(t){return new rt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function yi(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 _i(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 rt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function wi(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw At(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw At(`tool_result > ${r}`);e+=String(n.text??"")}return e}function vi(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 At(typeof n);let r=[],s="",o=()=>{s&&(r.push({role:e,content:s}),s="")};for(let i of n){let a=String(i.type??"");if(a==="text")s+=String(i.text??"");else if(a==="tool_use")o(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")o(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:wi(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw At(a)}}return o(),r}function on(t){return Ce(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 bi(t,e,n,r,s){let o=t.messages;if(!Array.isArray(o)){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(w=>typeof w!="string"))){de(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=Dn(s.id),d=[],u;try{t.system&&d.push({role:"system",content:gi(t.system)});for(let w of o)d.push(...vi(w));u=_i(t.tool_choice)}catch(w){if(w instanceof rt){de(n,400,"invalid_request_error",w.message);return}throw w}let l=te(t);r.model(l),s.model=l,s.stream=t.stream===!0,await Ot(s,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await e.createResponse({model:t.model,input:d,stream:!0,tools:yi(t.tools),tool_choice:u,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},se(s))}catch(w){if(w instanceof F){De(n,"anthropic",w);return}throw w}let p=(w,P)=>{n.destroyed||n.write(`event: ${w}
55
+ data: ${JSON.stringify({type:w,...P})}
56
+
57
+ `)};if(t.stream===!0){let w=r.track(v,l,s);an(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 P=0,_="",I=0,C="none",U=()=>C,W=-1,ee=-1,ie=new ge,me=[],D=()=>{C!=="none"&&(C="none",p("content_block_stop",{index:W}))},j=(N,Q)=>{D(),C=N,W=I++,p("content_block_start",{index:W,content_block:Q})};for await(let N of w){if(n.destroyed)break;me.push(N);let Q=Le(N);if(N.type==="response.reasoning_text.delta"&&typeof N.delta=="string")U()!=="thinking"&&j("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:N.delta}});else if(N.type==="response.output_text.delta"&&typeof N.delta=="string")U()!=="text"&&j("text",{type:"text",text:""}),P+=1,_+=N.delta,p("content_block_delta",{index:W,delta:{type:"text_delta",text:N.delta}});else if(Q){let{call:fe}=ie.add(Q);(U()!=="tool"||Q.tool_index!==ee)&&(ee=Q.tool_index,j("tool",{type:"tool_use",id:fe.id??`call_${Q.tool_index}`,name:fe.name??"",input:{}})),Q.delta&&p("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(N.type==="error"){s.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(N)}}),n.end();return}}if(n.destroyed)return;let K=ue(me),_e=Ce(K),O=Se(c,ie.size+_e.length,_);if(O){s.streamError=!0,p("error",{error:{type:"api_error",message:ke(l,O)}}),n.end();return}D();let M=[];if(ie.size===0)try{M=on(K)}catch(N){s.streamError=!0,p("error",{error:{type:"api_error",message:String(N instanceof Error?N.message:N)}}),n.end();return}I===0&&M.length===0&&(j("text",{type:"text",text:""}),D()),M.forEach(N=>{let Q=I++;p("content_block_start",{index:Q,content_block:{...N,input:{}}}),p("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(N.input??{})}}),p("content_block_stop",{index:Q})});let J=ie.size>0||M.length>0,le=Et(K);Ae(s,K),p("message_delta",{delta:{stop_reason:J?"tool_use":"end_turn"},usage:le?{input_tokens:le.input_tokens,output_tokens:le.output_tokens}:{output_tokens:P}}),p("message_stop",{}),n.end();return}let x="",E="",k=[],y=new ge;for await(let w of r.track(v,l,s)){k.push(w),w.type==="response.output_text.delta"&&typeof w.delta=="string"&&(x+=w.delta),w.type==="response.reasoning_text.delta"&&typeof w.delta=="string"&&(E+=w.delta);let P=Le(w);if(P&&y.add(P),w.type==="error"){let _=w.error,I=_?.type==="invalid_request_error";de(n,I?400:502,I?"invalid_request_error":"api_error",_?.message??JSON.stringify(w));return}if(n.destroyed)break}if(n.destroyed)return;let h=ue(k);Ae(s,h);let g;try{g=on(h),g.length===0&&y.size>0&&(g=on({output:y.items()}))}catch(w){de(n,502,"api_error",String(w instanceof Error?w.message:w));return}let S=Se(c,g.length,x);if(S){de(n,502,"api_error",ke(l,S));return}let m=[],f=E||Xr(h);f&&m.push({type:"thinking",thinking:f}),(x||g.length===0)&&m.push({type:"text",text:x}),m.push(...g),Z(n,200,{id:a,type:"message",role:"assistant",content:m,model:i,stop_reason:g.length>0?"tool_use":"end_turn",usage:Et(h)??{input_tokens:0,output_tokens:0}})}function xi(t){he(process.stdout,t)}function ki(t){let{clients:e,apiKey:n,identity:r,statusOf:s}=t,o=typeof e=="function"?e:()=>e,i=t.requestLog??xi,a=t.observe,d=new be;return(u,l)=>{let c=new URL(u.url??"/","http://localhost"),v=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),p=(h,g,S,m,f)=>v?de(l,h,m,g):X(l,h,g,S,f),x=Ht(c.pathname),E=c.pathname.startsWith("/partners/"),k=x||E?{id:Ve(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,sessionId:null,timing:null}:null;k&&(l.setHeader(Bn,k.id),l.once("close",()=>{let h=jn({turn:k,method:u.method??"",path:c.pathname,res:l});i(Hn(h)),a?.(h),Hr({record:h,ledger:t.ledger??null,req:u})}));let y=()=>Fn(c.pathname,k);(async()=>{if(u.method==="GET"&&c.pathname==="/healthz"){Z(l,200,{ok:!0});return}if(u.method==="GET"&&c.pathname==="/stats"){Z(l,200,r?{identity:r,...d.snapshot()}:d.snapshot());return}if(n&&(u.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=c.pathname===Tr?"canonical":c.pathname===en?"huggingface":null;if(h){if(u.method!=="POST"){p(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let f=t.usage;if(!f){p(501,`${c.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 w=f.authorize(u),P;try{P=await Vr(u,Pr)}catch(C){if(C instanceof nt){p(413,C.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=C=>f.lookup(w,C),I;try{if(h==="canonical"){let C=Cr(P),U=await _(C);kt(U,C),I={requests:U}}else I=await Mr(P,_)}catch(C){if(C instanceof ye){p(C.status,C.message,"invalid_request_error","invalid_request_error");return}throw C}Z(l,200,I);return}if(u.method==="GET"&&c.pathname===je){let f=await o(u);if(k&&(k.org=f.tenant??null),!f.openRouterModels){p(501,`GET ${je} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}Z(l,200,await f.openRouterModels());return}if(c.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${u.method} ${c.pathname} \u2014 the partner surface currently carries ${en} and GET ${je}`,"invalid_request_error","not_found_error");return}let g=await o(u);if(k&&(k.org=g.tenant??null),u.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){l.writeHead(308,{location:je}),l.end();return}Z(l,200,await g.listModels());return}if(u.method==="GET"&&c.pathname===Kn){if(!g.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}Z(l,200,await g.listImageModels());return}if(Xn(c.pathname)){if(!g.supportsImages){p(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let f={clients:g,imageModels:g.supportsImages,stats:d,turn:y()};c.pathname===yt?await ar(u,l,f):await ir(u,l,f);return}if(u.method==="GET"&&c.pathname===xr){if(!g.listSpeechToTextModels){p(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}Z(l,200,await g.listSpeechToTextModels());return}if(br(c.pathname)){if(!g.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 f={clients:g,transcriptionModels:g.supportsTranscription,stats:d,turn:y()};await Rr(u,l,f);return}if(gr(c.pathname)){if(!g.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Qe}`,"not_implemented","not_implemented_error");return}let f={clients:g,speechModels:g.supportsSpeech,stats:d,turn:y()};await vr(u,l,f);return}if(u.method!=="POST"){p(404,`no route for ${u.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let S;try{S=await Vr(u)}catch(f){if(f instanceof nt){p(413,f.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(S));if(c.pathname==="/v1/responses"){d.request("responses",m,m),await pi(S,g,ze(g),l,d,y());return}if(c.pathname==="/v1/chat/completions"){d.request("chat_completions",m,m),await mi(S,g,l,d,y(),u.headers[rn]);return}if(c.pathname==="/v1/systemone"){d.request("systemone",m,m),await hi(S,g,l,d,y());return}if(c.pathname==="/v1/messages"){d.request("messages",m,m),await bi(S,g,l,d,y());return}if(c.pathname==="/v1/messages/count_tokens"){d.request("count_tokens",m,m),de(l,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 ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let g=String(h instanceof Error?h.message:h);if(!l.headersSent){let S=s?.(h)??null;if(S){p(S.status,g,S.openaiType,S.anthropicType);return}if(h instanceof ni){let m=pt(h.code);if(m){let f=h.retryAfterSeconds??(m.status===429?30:void 0);f!==void 0&&l.setHeader("Retry-After",String(f)),p(m.status,Ft(m,h.code??void 0),m.openaiType,m.anthropicType,m.code);return}}if(h instanceof ri){let m=mt(h);if(m){let f=m.status===429?30:void 0;f!==void 0&&l.setHeader("Retry-After",String(f)),p(m.status,Ft(m,h.status.sessionId?`session ${h.status.sessionId}`:void 0),m.openaiType,m.anthropicType,m.code);return}}if(h instanceof V){p(502,g,"upstream_error","api_error");return}p(500,g,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0),l.destroyed||(v?l.write(`event: error
58
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:g}})}
59
+
60
+ `):l.write(`data: ${JSON.stringify({error:{message:g,type:"upstream_error"}})}
61
+
62
+ `)),l.end()})}}function Wu(t){let{clients:e,apiKey:n}=t,r=ti(ki(t)),s=zn(r,{clients:e,apiKey:n,statusOf:t.statusOf}),o=jt(r,{resolver:zr(e,n)}),i=r.close.bind(r);return r.close=(a=>(s.close(),o(),i(a))),An(r,{clients:e,apiKey:n}),r}var ae=(t,e)=>Object.assign(new Error(e),{status:t});function Si(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Ri(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Ei='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Ii(t,e,n,r){if(!t.supportsAudio)throw ae(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 s;try{s=await t.supportsAudio(e)}catch(u){throw u instanceof F?ae(404,u.message):u}if(!s)throw ae(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 ae(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(t.supportsTranscription)try{o=await t.supportsTranscription(e)}catch(u){throw u instanceof F?ae(404,u.message):u}if(o&&!t.openTurnsOn)throw ae(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&t.transcriptStreamFor){let u;try{u=await t.transcriptStreamFor(e)}catch(l){throw l instanceof F?ae(404,l.message):l}if(u!=="stt")throw ae(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(u)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ae(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Ei}`);if(r==="transcription"&&!o)throw ae(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i=await t.sessionHandle(e),a={audio:await t.openAudioOn(i,n)},d={clients:{createResponse:async u=>await t.createResponseOn(i,u)},voice:s,audioSession:a};return o&&(d.turns=u=>t.openTurnsOn(i,u)),r==="transcription"&&(d.intent="transcription"),e!==void 0&&(d.model=e),d}function zr(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let s=n.headers.authorization,o=typeof s=="string"?s.trim():"",i=o.startsWith("Bearer ")?o.slice(7).trim():"";if(i===""||i!==e)throw ae(401,"invalid local proxy api key")}return Ii(t,Si(n),r,Ri(n))}}}export{it as a,An as b,Ci as c,Ys as d,zn as e,ji as f,ds as g,Hi as h,Gi as i,Ji as j,Vi as k,Wi as l,zi as m,Yi as n,Xi as o,Ki as p,ls as q,Tn as r,Qi as s,ms as t,Zi as u,ea as v,ta as w,he as x,na as y,ra as z,sa as A,Je as B,Dt as C,jt as D,Si as E,Ri as F,Ii as G,zr as H,Tr as I,V as J,cu as K,en as L,_u as M,wu as N,vu as O,bu as P,xu as Q,ki as R,Wu as S};
@@ -0,0 +1 @@
1
+ import{a as T}from"./chunk-K23AZPI4.js";import{a as x}from"./chunk-76BZLCGT.js";import{a as G,b as M,d as U,g as b,h as _,j as D,k as H}from"./chunk-BAKPG5S3.js";import{c as R,f as C,g as F,p as I}from"./chunk-6M5JK4YC.js";import{c as S}from"./chunk-YSFSRI3D.js";S();import{App as B,createClientToken as Z,DEFAULT_WHEN_LIVE_TIMEOUT_MS as ee}from"@urun-sh/core";S();import{SessionFailedError as K}from"@urun-sh/core";var P=2;function J(n){let t=n?.type;return t==="response.created"||t==="response.in_progress"}function Q(n){let t=n?.type;return t==="response.completed"||t==="error"}function N(n){return async function(r,c){return(async function*(){for(let a=1;a<=P;a++){let{app:d,entry:i,identity:u}=await n.sessionFor(r.model);c?.({sessionId:n.sessionIdOf?.(i)??null,identity:u});let m=!1,l=!1;try{let f=await n.createStream(i,r);for await(let e of f){if(Q(e)&&(m=!0),J(e)){if(a>1)continue}else l=!0;yield e}}catch(f){if(f instanceof K&&(f.kind==="never-live"||f.kind==="create-failed")){try{n.onAdmissionVerdict?.(d,i,f)}catch{}throw f}if(a<P&&!l){await n.evict(d,i);continue}throw f}if(m)return;if(a<P&&!l){await n.evict(d,i);continue}return}})()}}S();var Y=3,z="llm",X=new Set(["paused","error"]);function W(n,t){let r=n.doc(z),c=typeof r.onConnectionState=="function",p=typeof n.onPhase=="function";if(!c&&!p)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let a=null,d=!1,i=new Set,u=[],m=l=>{if(!a){a=l;for(let f of[...i])f(l);i.clear()}};return c&&u.push(r.onConnectionState(l=>{d&&(l.consecutiveFailures<Y||m(new b(`the pooled session for app "${t}" is gone: its doc backhaul failed ${l.consecutiveFailures} consecutive times (last close ${l.lastCloseCode===null?"by provider liveness reap":`code ${l.lastCloseCode}`}${l.lastCloseReason?`, reason ${JSON.stringify(l.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),p&&u.push(n.onPhase(l=>{if(l.name==="live"){d=!0;return}d&&X.has(l.name)&&m(new b(`the pooled session for app "${t}" lost its compute binding (phase "${l.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>a,onGone(l){return a?(l(a),()=>{}):(i.add(l),()=>i.delete(l))},dispose(){i.clear();for(let l of u.splice(0))l()}}}async function*O(n,t){let r=t.gone();if(r)throw r;let c=n[Symbol.asyncIterator](),p,a=new Promise((d,i)=>{p=t.onGone(u=>i(u))});a.catch(()=>{});try{for(;;){let d=await Promise.race([c.next(),a]);if(d.done)return;yield d.value}}finally{p?.(),c.return?.(void 0)}}function j(n,t,r,c){let p=n[r];if(typeof p!="function")throw new Error(`app "${t}" has no function "${r}" (set URUN_FUNCTION)`);let a=c?p(void 0,c):p();if(typeof a.end!="function")throw new Error(`app "${t}" function "${r}" returned a session without end()`);return a}function ne(n,t,r){let{baseUrl:c,orgId:p,auth:a}=n,d=t.fnName??n.fnName,i=n.sessionStartOptions?.(r),u=t.sharedApp?{sharedApp:!0,...i}:i,m=o=>({session:o,responses:new x(o),gone:W(o,r)});if(a.lane==="jwt"){let o=B(t.appSlug,{baseUrl:c,orgId:p,jwt:a.jwt});return m(j(o,t.appSlug,d,u))}let{apiKey:l,gatewayUrl:f}=a,e=B(t.appSlug,{baseUrl:c,orgId:p,getAccessToken:async()=>(await Z(l,{baseUrl:f,expiresIn:300,allowedFunctions:[`${t.appSlug}/${d}`],...t.sharedApp?{sharedApp:!0}:{}})).token});return m(j(e,t.appSlug,d,u))}function oe(n){let t=n.session.id;if(typeof t!="string"||t.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return t}function se(n){if(n.kind==="never-live")return!0;if(n.kind!=="create-failed")return!1;let t=n.status.error?.httpStatus,r=n.status.error?.code;return t===410||t===409&&(r==="cancelled"||r==="expired")?!0:r==="client_ended"}var te=new Set(["error","paused"]);function Pe(n){let{auth:t,catalog:r}=n,c=null,p=(d,i)=>{let u=ne(n,d,i);return n.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&n.onSessionOpen(i,u.session.id),u.gone.onGone(()=>{c?.evict(i,u)}),u},a=new H({sharedOnlyListing:n.sharedOnlyListing===!0,defaultApp:n.defaultApp,fnName:n.fnName,openSession:p,closeSession:async d=>{if(d.gone.dispose(),n.release==="detach"){if(typeof d.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');d.session.detach();return}await d.session.end()},listApps:t.lane==="api-key"?()=>_({apiUrl:n.apiUrl,apiKey:t.apiKey}):null,listCatalog:r?()=>T(r):null,listPrices:r?()=>M(r):null,shared:t.lane==="api-key"?()=>G({apiUrl:n.apiUrl,apiKey:t.apiKey}):null,sessionKey:oe});return c=a,n.defaultApp!==null&&a.seed(n.defaultApp,p({appSlug:n.defaultApp},D({appSlug:n.defaultApp}))),a}async function E(n,t){let r=n.whenLive;if(typeof r!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await r.call(n,{timeout:ee,signal:t})}async function q(n){if(typeof n.cancel=="function")try{await n.cancel();return}catch{}if(typeof n.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");n.detach()}function v(n){return n.reason instanceof Error?n.reason:new Error("the client socket closed")}function Oe(n,t=F,r){let c=new WeakMap,p=new WeakMap,a=new WeakMap,d=new WeakMap,i=new WeakMap,u=e=>{let o=e.session.id;return typeof o=="string"&&o.length>0?o:null},m=e=>{let o=c.get(e);if(!o){let s={waiting:0,gone:new AbortController};i.set(e,s),o=(async()=>{if(await E(e.session,s.gone.signal),s.gone.signal.aborted)throw v(s.gone.signal);i.get(e)===s&&i.delete(e);let h=await R(e.session,await t());return Object.assign(h,{sessionId:e.session.id})})(),c.set(e,o),o.catch(()=>{c.get(e)===o&&c.delete(e)}),o.then(()=>{i.get(e)===s&&i.delete(e)},()=>{i.get(e)===s&&i.delete(e)})}return o},l=e=>{let o=d.get(e);return o||(o=(async()=>{let s=await m(e);return{appendInputAudio:h=>s.appendInputAudio(h),onOutputAudio:h=>s.onOutputAudio(h),sessionId:u(e)}})(),d.set(e,o),o.catch(()=>{d.get(e)===o&&d.delete(e)})),o},f=async(e,o,s)=>{if(s?.aborted){let g=i.get(e);throw(c.get(e)===void 0||g!==void 0&&g.waiting===0)&&await q(e.session),v(s)}let h=o(e),w=i.get(e);return w!==void 0&&w.waiting++,s===void 0?h:new Promise((g,y)=>{let k=()=>{w!==void 0&&--w.waiting===0&&i.get(e)===w&&(w.gone.abort(),i.delete(e),c.delete(e),d.delete(e),q(e.session).catch(()=>{})),y(v(s))};s.addEventListener("abort",k,{once:!0});let L=()=>s.removeEventListener("abort",k);h.then(A=>{L(),g(A)},A=>{L(),y(A)})})};return{createResponse:N({sessionFor:e=>n.sessionFor(e),sessionIdOf:e=>u(e),evict:(e,o)=>n.evict(e,o),onAdmissionVerdict:(e,o,s)=>{se(s)&&(n.evict(e,o),r?.(e,s.kind==="never-live"?"never-live":"create-failed"))},createStream:async(e,o)=>(await E(e.session),O(await e.responses.responses.create(o),e.gone))}),listModels:()=>n.modelList(),openRouterModels:()=>n.openRouterModels(),supportsImages:(e,o)=>n.supportsImages(e,o),listImageModels:()=>n.imageModelList(),catalogIdentity:e=>n.catalogIdentityFor(e),servingAppSlug:async e=>await n.servingAppSlugFor(e),supportsAudio:e=>n.supportsAudio(e),supportsSpeech:e=>n.supportsSpeech(e),speechVoices:e=>n.speechVoices(e),supportsTranscription:e=>n.supportsTranscription(e),transcriptStreamFor:e=>n.transcriptStreamFor(e),listSpeechToTextModels:()=>n.speechToTextModelList(),openAudio:async(e,o)=>{let{entry:s}=await n.sessionFor(e);return await f(s,m,o)},openAudioOn:async(e,o)=>{let{entry:s}=await n.sessionForHandle(e);return await f(s,l,o)},openTurnsOn:async function*(e,o){if(o?.aborted)throw v(o);let{entry:s}=await n.sessionForHandle(e);yield*U(s.session,o)},openVideo:async e=>{let{entry:o}=await n.sessionFor(e),s=p.get(o);return s||(s=C(o.session),p.set(o,s)),s},openVideoOut:async e=>{let{entry:o}=await n.sessionFor(e),s=a.get(o);return s||(s=I(o.session),a.set(o,s)),s},sessionHandle:async e=>(await n.handleFor(e)).handle,speechSessionHandle:async e=>(await n.speechHandleFor(e)).handle,evictSpeechSession:async e=>{let{app:o,entry:s}=await n.sessionForHandle(e);await n.evict(o,s)},createResponseOn:async(e,o)=>{let{entry:s}=await n.sessionForHandle(e);return await E(s.session),O(await s.responses.responses.create(o),s.gone)},onSessionEnd:async(e,o)=>{let{entry:s}=await n.sessionForHandle(e),h=s.session;if(typeof h.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let w=!1;return h.onPhase(g=>{if(w||!te.has(g.name))return;w=!0;let y=h.endsAt??null;o({timeLeftMs:y?Math.max(0,y.getTime()-Date.now()):null,reason:g.reason??`session ${g.name}`})})}}}export{Pe as a,Oe as b};