@urun-sh/openai 0.6.20 → 0.6.22
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.
- package/dist/chunk-4W3ZPIR7.js +62 -0
- package/dist/{chunk-BAKPG5S3.js → chunk-CUDFHFNX.js} +3 -3
- package/dist/chunk-HCAKF2SQ.js +7 -0
- package/dist/chunk-KSC5Q6PZ.js +2 -0
- package/dist/hosted/bin.cjs +40 -38
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +36 -34
- package/dist/hosted/index.d.cts +105 -3
- package/dist/hosted/index.d.ts +59 -2
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +40 -40
- package/dist/proxy/cli.cjs +51 -49
- package/dist/proxy/cli.js +15 -14
- package/dist/proxy/index.cjs +26 -26
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/dist/{responses-turn-DmzWIpmO.d.ts → responses-turn-2UJImii3.d.ts} +12 -1
- package/dist/{responses-turn-Cb1qQBA7.d.cts → responses-turn-C0PBaF29.d.cts} +41 -1
- package/package.json +1 -1
- package/dist/chunk-64WZRHYB.js +0 -6
- package/dist/chunk-7ZH2UHK6.js +0 -1
- package/dist/chunk-TF2IMK3T.js +0 -62
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import{c as He,e as _n,f as q,g as se}from"./chunk-CUDFHFNX.js";import{a as yn,c as wn,d as ve,e as dt,f as z,g as vn,h as bn,i as xn,j as kn,k as Sn,l as Rn,m as En,n as In,r as An,t as On,u as Tn,v as Pn,w as Cn,x as Mn}from"./chunk-3JWYIKHM.js";import{a as $t}from"./chunk-6M5JK4YC.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{randomUUID as is}from"crypto";import{WebSocketServer as as}from"ws";var us=256,lt=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>us;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},ds="local",Je=n=>n.slice(0,120),ct=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof q){this.ws.close(wn,Je(e.message));return}if(e instanceof se){this.ws.close(dt,Je(e.message));return}if(e instanceof z){this.ws.close(e.closeCode,Je(e.message));return}this.ws.close(ve,Je(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=vn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new z(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:o}=In(t.clientContent);this.transcript.push(...s),o&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=On(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:An);return}this.transcript.push(...Tn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new z("setup may only be sent once, as the first client message");let t=Sn(e),r=t.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",dt);if(o.model!==t.model)throw new z(`sessionResumption.handle was issued for model "${o.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new 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(t.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`,dt);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(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let o=this.clients.openVideoOut;if(o){let i=await o.call(this.clients,t.model),a=i.onOutputFrame(d=>this.send(kn(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},s[bn]=xn(i.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new z("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new z("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ve);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Cn(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new z("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)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)",ve);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new 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,t.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(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=is();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Rn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(En(e.timeLeftMs)),this.ws.close(ve,Je(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,o=!1;for await(let u of r){if(t.interrupted)break;let d=u;if(d.type==="error")throw new z(`upstream error: ${JSON.stringify(d)}`,ve);if(d.type==="response.completed"){s=d.response,o=!0;continue}let l=Pn(d);l&&this.send(l)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!o)throw new z("upstream produced no response.completed event",ve);let{messages:i,assistantItems:a}=Mn(s);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},be=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function ls(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(n.headers["x-goog-api-key"]);let o=n.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 be(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&i!==void 0&&i!=="")throw new be(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new be(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Ln(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new as({noServer:!0}),s=new lt;n.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===yn&&(a.on("error",()=>{}),(async()=>{let l=ls(i,d,t),c;if(e.authenticate)c=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new be(401,"invalid local proxy api key");c={clients:e.clients,scope:ds}}r.handleUpgrade(i,a,u,v=>{new ct(v,c,s)})})().catch(l=>{let c=502;(l instanceof be||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(u=>u===void 0?i():a(u)))})(),o)}function Bi(n,e,t=new lt){new ct(n,e,t)}A();import ps from"os";import ms from"path";import{fileURLToPath as fs}from"url";import{format as hs}from"util";var Un="0.6.22";var Nn=4141,gs=Un,Xi={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 _s(n,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${n}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${n}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Qi(n,e,t){let r={...n,..._s(e,t)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Zi(n,e,t){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${n}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],s=t.indexOf("--"),o=s===-1?t:t.slice(0,s),i=o.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=t[0]==="exec",u=o.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...r,...i?[]:["-m",e],...d]}function ea(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",n,...e]}function ta(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${n}`,...e]}function na(n,e,t){let r=(n.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!t(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=fs(new URL("../pi-extension/standalone.cjs",e));if(!t(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 Fn(n){let e=Number(n);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${n}`);return e}function ra(n){if(n[0]!=="--port")return null;let e=Fn(n[1]);return n.splice(0,2),e}function sa(n){let e=n.indexOf("--port");if(e===-1)return Nn;let t=Fn(n[e+1]);return n.splice(e,2),t}function oa(n){if(n===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 n}function Nt(n,e){let t=(n[e]??"").trim();if(!t)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 t}function ia(n){let e=ys(Nt(n,"URUN_BASE_URL")),t=Nt(n,"URUN_ORG_ID"),r=Nt(n,"URUN_APP"),s=(n.URUN_FUNCTION??"serve").trim()||"serve",o=(n.URUN_API_URL??"").trim(),i=o?$n(o,"URUN_API_URL"):_n,a=(n.URUN_JWT??"").trim();if(a)return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(n.URUN_API_KEY??"").trim();if(u){let d=(n.URUN_GATEWAY_URL??"").trim(),l=d?$n(d):void 0;return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:i,auth:{lane:"api-key",apiKey:u,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 ys(n,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(n).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${n} \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 n}function $n(n,e="URUN_GATEWAY_URL"){let t=new URL(n),r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${n}) \u2014 the org API key rides the request's Authorization header`);return n}function aa(n){return{app:n.appId,org:n.orgId,fn:n.fnName,base_url:n.baseUrl,proxy_version:gs}}function ws(n,e){return n.app===e.app&&n.org===e.org&&n.fn===e.fn&&n.base_url===e.base_url&&n.proxy_version===e.proxy_version}var vs=250;async function bs(n,e=vs){try{let t=await fetch(`http://127.0.0.1:${n}/stats`,{signal:AbortSignal.timeout(e)});if(!t.ok)return null;let r=(await t.json()).identity;if(r==null||typeof r!="object")return null;let{app:s,org:o,fn:i,base_url:a,proxy_version:u}=r;return typeof s!="string"||typeof o!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:s,org:o,fn:i,base_url:a,proxy_version:u}}catch{return null}}var qn=2e3;async function xs(n,e=qn){try{let t=await fetch(`http://127.0.0.1:${n}/v1/models`,{signal:AbortSignal.timeout(e)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function ua(n,e,t=Nn,r=qn){if(n!=null)return{mode:"spawn",port:n};let s=await bs(t);if(s!==null&&ws(s,e)){let o=await xs(t,r);return o===null?{mode:"reuse",port:t,identity:s}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} 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 da(n,e=ps.homedir()){return ms.join(e,".urun","logs",`compat-proxy-${n}.log`)}var Ft=["log","info","warn","error","debug","trace"];function la(n,e=process,t=console){let r=e.stdout.write,s=e.stderr.write,o=(a,...u)=>n.write(a,...u);e.stdout.write=o,e.stderr.write=o;let i=Object.fromEntries(Ft.map(a=>[a,t[a]]));for(let a of Ft)t[a]=(...u)=>{n.write(`${hs(...u)}
|
|
6
|
+
`)};return()=>{e.stdout.write=r,e.stderr.write=s;for(let a of Ft)t[a]=i[a]}}var ks=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Dn(n){let e=n?.code;return typeof e=="string"&&ks.has(e)}function ge(n,e){try{return n.write(e),!0}catch(t){if(Dn(t))return!1;throw t}}function ca(n){let e={stdout:!1,stderr:!1},t=[];for(let r of["stdout","stderr"]){let s=n.streams[r],o=i=>{Dn(i)&&(e[r]=!0);let a=i?.code;try{n.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),t.push([s,o])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,s]of t)r.off("error",s)}}}function pa(n){let e=t=>{let r=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{n.appendSync(n.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
8
|
+
`)}catch{}n.restore();try{n.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${n.logPath}
|
|
9
|
+
`)}catch(s){try{n.appendSync(n.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(s?.code??s)}) \u2014 the terminal is gone
|
|
10
|
+
`)}catch{}}n.killChild(),n.exit(1)};return n.proc.on("uncaughtException",e),n.proc.on("unhandledRejection",e),()=>{n.proc.off("uncaughtException",e),n.proc.off("unhandledRejection",e)}}function ma(n,e){let t="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${n} 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:${n}, or ${t}`:`port ${n} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${t}`}A();import{SessionFailedError as As}from"@urun-sh/core";A();import{randomUUID as Ss}from"crypto";function k(n){return`${n}_${Ss().replace(/-/g,"").slice(0,24)}`}var pt=4*1024*1024,qt=8*1024*1024,mt=512,ft=20*1024*1024;function j(n,e,t){return{type:"invalid_request_error",code:n,message:e,param:t??null}}function Pe(n,e){return{type:"server_error",code:n,message:e}}function U(n){return{type:"error",event_id:k("event"),error:n}}function Dt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var S=class extends Error{constructor(t,r,s="invalid_value"){super(t);this.param=r;this.code=s;this.name="SessionUpdateError"}param;code},Rs={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},Es={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Is={format:!0,voice:!0,speed:!0};function Bn(n,e){let t=n;if(!t||typeof t!="object"||t.type!=="audio/pcm"||t.rate!==void 0&&t.rate!==24e3)throw new S(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function Ve(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))throw new S("session must be an object","session","invalid_request");let r=n,s=Object.keys(r).filter(i=>!(i in Rs));if(s.length>0)throw new S(`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 S(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new S(`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"&&!t.turns)throw new S('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 S("model must be a string or null","model");o.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new S("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 S("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new S(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!t.voice)throw new S('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}o.outputModalities=u;break}case"voice":if(a===null){delete o.voice;break}if(typeof a!="string")throw new S("voice must be a string or null","voice");if(!t.voice)throw new S("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 S(`${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 S("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 S(`${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 S("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 S("metadata must be an object or null","metadata");o.metadata=a??null;break;case"turn_detection":{if(a===null){o.turnDetection=null;break}if(!t.turns)throw new S("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new S("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new S(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");o.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){o.inputAudioTranscription=!1;break}if(!t.turns)throw new S("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 S("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new S(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=a.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==t.model)throw new S(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${t.model===void 0?"the unnamed default app":JSON.stringify(t.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}o.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new S("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new S("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new S("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in Es))throw new S(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&Bn(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=Ve({input_audio_transcription:d.transcription},o,t);o.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=Ve({turn_detection:d.turn_detection},o,t);o.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new S("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new S("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in Is))throw new S(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&Bn(d.format,"audio.output.format"),d.speed!==void 0)throw new S("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete o.voice;else{if(typeof d.voice!="string")throw new S("audio.output.voice must be a string or null","audio.output.voice");if(!t.voice)throw new S("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");o.voice=d.voice}d.format!==void 0&&!o.outputModalities.includes("audio")&&(o.outputModalities=["text","audio"])}break}default:break}return o}function ht(n,e){return{id:e,object:"realtime.session",type:n.type??"realtime",model:n.model??null,instructions:n.instructions??"",modalities:[...n.outputModalities],voice:n.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:n.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:n.turnDetection?{type:"server_vad",create_response:n.turnDetection.createResponse,interrupt_response:n.turnDetection.interruptResponse}:null,temperature:n.temperature??null,max_response_output_tokens:n.maxOutputTokens??"inf",tool_choice:n.toolChoice??"auto",tools:n.tools??[],metadata:n.metadata??null}}function Bt(n,e){let t=n;if(!t||typeof t!="object")throw new S("item must be an object","item","invalid_request");if(t.type==="function_call_output"){if(typeof t.call_id!="string"||typeof t.output!="string")throw new S("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof t.id=="string"?t.id:k("item"),type:"function_call_output",callId:t.call_id,output:t.output}}if(t.type==="message"){let r=t.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new S('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(t.content))throw new S("message item content must be an array","item.content","invalid_request");let s=[];for(let o of t.content){let i=o;if(!i||typeof i!="object")throw new S("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 S(`${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 S("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 S("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 S(`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 t.id=="string"?t.id:k("item"),type:"message",role:r,content:s}}throw new S(`item type ${String(t.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function jt(n){let e=[],t=!1;for(let r of n){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let s=[];for(let 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}t=!0;continue}}e.push({role:r.role,content:s})}return{input:e,sawAudioOnlyItem:t}}var Os=1001,Ts=1011,jn=n=>n.slice(0,120),Ps=/^[A-Za-z0-9+/=]*$/,Cs=2;function Ms(n){let e=Buffer.from(n,"base64");for(let t=0;t+1<e.byteLength;t+=2)if(Math.abs(e.readInt16LE(t))>Cs)return!1;return!0}var We=class{id=k("conn");ws;binding;onClosed;config=Dt();sessionId=k("sess");conversationId=k("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",t=>{this.onMessage(t)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:k("event"),session:ht(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:k("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let t=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=t,(async()=>{try{for(;;){let r=await t.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(U(Pe("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===t&&(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 t=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:k("event"),item_id:e,content_index:0,transcript:t})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let t=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,t.length>0&&(this.turnTranscript.text+=t),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&t.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:k("event"),item_id:r??"input_audio_turn",content_index:0,delta:t}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:k("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let t=this.pendingTranscriptItemId;if(t!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:k("event"),item_id:t,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(t);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:k("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:k("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=k("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:k("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.created",event_id:k("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:k("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:k("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 t;try{t=e.toString()}catch{this.fail(j("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(t,"utf8")>pt){this.fail(j("frame_too_large",`frame exceeds the ${pt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(t)}catch{this.fail(j("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(j("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(U({type:"invalid_request_error",code:o.code??"invalid_value",message:o.message,param:o.param??null}));return}this.fail(Pe(null,s instanceof Error?s.message:String(s)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Ve(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:k("event"),session:ht(this.config,this.sessionId)});return;case"conversation.item.create":{let t=Bt(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(t),this.send({type:"conversation.item.created",event_id:k("event"),previous_item_id:r,item:this.itemToProtocol(t)});return}case"conversation.item.delete":{let t=this.items.findIndex(r=>r.id===e.item_id);if(t<0){this.send(U(j("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(t,1),this.send({type:"conversation.item.deleted",event_id:k("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let t=this.items.find(r=>r.id===e.item_id);if(!t){this.send(U(j("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:k("event"),item:this.itemToProtocol(t)});return}case"conversation.item.truncate":{let t=this.items.find(r=>r.id===e.item_id);if(!t||t.type!=="message"||t.role!=="assistant"){this.send(U(j("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}t.truncated=!0,this.send({type:"conversation.item.truncated",event_id:k("event"),item_id:t.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(U(j("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ps.test(e.audio)){this.send(U(j("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let t=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+t>ft){this.send(U(j("buffer_full",`uncommitted input audio exceeds the ${ft}-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+=t;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=t;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:k("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(U(j("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 t=this.takeTurnTranscript();t===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=k("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...t!==null?{transcript:t}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:k("event"),previous_item_id:s,item_id:r}),this.send({type:"conversation.item.created",event_id:k("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(t!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:k("event"),item_id:r,content_index:0,transcript:t});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:k("event"),item_id:r,content_index:0,transcript:o}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(U(j("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(U(j("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(U(j("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(U(j("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,t=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(t.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");t.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(U({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,t){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??[],t)}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(U(j("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let t=e??{};if(t.modalities!==void 0){if(!Array.isArray(t.modalities)||t.modalities.some(R=>R!=="text"&&R!=="audio")){this.send(U(j("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(t.modalities.includes("audio")&&!this.ensureVoice())return}if(t.input!==void 0){this.send(U(j("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=k("req"),s=`resp_${r}`;this.activeResponseId=s;let o=this.items.length,{input:i,sawAudioOnlyItem:a}=jt(this.items),u=typeof t.instructions=="string"?t.instructions:this.config.instructions,d=typeof t.temperature=="number"?t.temperature:this.config.temperature,l=t.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,v=t.tools!==void 0?t.tools:this.config.tools,p=t.tool_choice!==void 0?t.tool_choice:this.config.toolChoice,x={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...c!==void 0?{max_output_tokens:c}:{},...v!==void 0?{tools:v}:{},...p!==void 0?{tool_choice:p}:{}};for(let R of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(R);this.inFlight=(async()=>{let R=[],b=E=>{this.responseFlushed?this.send(E):R.push(E)},m=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:k("event"),response:this.responseObject(s,"in_progress")}),this.send({type:"response.in_progress",event_id:k("event"),response:this.responseObject(s,"in_progress")});for(let E of R)this.send(E);R.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 E;try{E=await this.upstreamStream(x,r)}catch(_){this.upstreamTurnFault(_,s);return}try{for await(let _ of E){if(this.cancelled)break;let f=_;if(f.type==="error"){let y=this.upstreamErrorBody(f);this.responseFlushed?this.send(U(y)):this.send({type:"response.failed",event_id:k("event"),response:this.failedResponse(s,y)});return}if(f.type==="response.output_text.delta"&&typeof f.delta=="string"){m(),h.messageOpen||(this.beginMessageItem(s,h.nextOutputIndex++),h.messageOpen=!0),b({type:"response.output_text.delta",event_id:k("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"){m();let y=typeof f.delta=="string"?f.delta:"",P=typeof f.call_id=="string"&&f.call_id.length>0?f.call_id:`${s}_fc_${h.nextOutputIndex}`,w=h.tools.get(P);if(!w){let I=typeof f.name=="string"&&f.name.length>0?f.name:void 0;w={outputIndex:h.nextOutputIndex++,name:I,args:""},h.tools.set(P,w),b({type:"response.output_item.added",event_id:k("event"),response_id:s,output_index:w.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&&(w.name=f.name),w.args+=y,b({type:"response.function_call_arguments.delta",event_id:k("event"),item_id:P,response_id:s,output_index:w.outputIndex,call_id:P,name:w.name??"",delta:y});continue}if(f.type==="response.completed"){g=f.response??null;continue}}}catch(_){this.upstreamTurnFault(_,s);return}if(this.cancelled)return;this.closeOpenItems(s,h,o),m(),this.send({type:"response.done",event_id:k("event"),response:this.doneResponse(s,o,g)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,t){if(this.cancelled)return;if(this.activeResponseId!==e){if(Ms(t))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(U({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:k("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:k("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:k("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:t})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,t){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:k("event"),response_id:e,output_index:t,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:k("event"),item_id:r,response_id:e,output_index:t,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let t=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:k("event"),response_id:e,output_index:0,item:{id:t,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:k("event"),item_id:t,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,t,r){if(t.messageOpen||this.messageItemOpenForAudio){let s=`${e}_msg_0`,o=this.messageItemOpenForAudio;o&&this.send({type:"response.output_audio.done",event_id:k("event"),item_id:s,response_id:e,output_index:0,content_index:0}),t.messageText.length>0&&this.send({type:"response.output_text.done",event_id:k("event"),item_id:s,response_id:e,output_index:0,content_index:0,text:t.messageText}),this.send({type:"response.content_part.done",event_id:k("event"),item_id:s,response_id:e,output_index:0,content_index:0,part:o?{type:"output_audio",transcript:""}:{type:"output_text",text:t.messageText}});let i=[];o&&i.push({type:"output_audio"}),t.messageText.length>0&&i.push({type:"output_text",text:t.messageText});let a={id:s,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:k("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[s,o]of t.tools){let i=o.args.length>0?o.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:k("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:k("event"),response_id:e,output_index:o.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,t,r){return{id:e,object:"realtime.response",status:t,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,t){return this.responseObject(e,"failed",{status_details:{error:{code:t.code,message:t.message}}})}doneResponse(e,t,r){let s=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,o=[];for(let i=t;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 t=e.error,r=t&&typeof t.message=="string"?t.message:JSON.stringify(e);return{type:"server_error",code:t&&typeof t.code=="string"?t.code:null,message:r}}failSessionGone(e){let t=e instanceof Error?e.message:String(e);this.fail(Pe("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${t}`),"session_gone")}upstreamTurnFault(e,t){if(e instanceof se){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof As&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,t)}}emitUpstreamFault(e,t){let r=Pe(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(U(r)):this.send({type:"response.failed",event_id:k("event"),response:this.failedResponse(t,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(U(j("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let t=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:k("event"),response:this.responseObject(t,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>mt&&(this.items.shift(),this.send(U({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${mt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let t={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...t,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...t,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(s=>s.type==="input_text"||s.type==="output_text"?{type:s.type,text:s.text}:s.type==="input_audio"?{type:"input_audio",...s.transcript?{transcript:s.transcript}:{}}:{type:"output_audio",transcript:s.transcript??""});return{...t,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>qt){this.ws.close(Os,jn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,t){this.send(U(e)),this.ws.close(Ts,jn(t)),this.teardown(t)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null;let t=this.turnLaneIterator;if(this.turnLaneIterator=null,t!==null){let r=t.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>Gn(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Gn(this.id,e)}},Gt=[];function Gn(n,e){Gt.push({id:n,reason:e}),Gt.length>256&&Gt.shift()}A();import{SessionFailedError as Ns}from"@urun-sh/core";A();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ls}from"@urun-sh/core";var Us={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},$s={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",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Ht(n,e){let t=$s[n.code];return e?`${t} (${e})`:t}function gt(n){if(n==null)return null;let e=Us[n];return e===void 0?null:{status:e,code:n,retryable:e!==502,openaiType:n==="no_capacity"||n==="queue_full"?"capacity_error":n==="queue_timeout"||n==="cold_start_exceeded"||n==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function _t(n){if(n.kind==="create-failed")return gt(n.status.error?.code??null);if(n.kind!=="never-live")return null;let e=(n.status.elapsedMs??0)>=Ls;return gt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as Fs}from"ws";var Vt="/v1/realtime",qs=n=>n.slice(0,120);function Ds(n,e,t){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";n.write(`HTTP/1.1 ${e} ${r}\r
|
|
11
|
+
Connection: close\r
|
|
12
|
+
Content-Type: text/plain\r
|
|
13
|
+
\r
|
|
14
|
+
${qs(t)}\r
|
|
15
|
+
`),n.destroy()}function Bs(n){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...n})}
|
|
16
|
+
`}function js(n){ge(process.stdout,n)}function Gs(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function Jt(n){return n.audioSession?.audio.sessionId??void 0}function Wt(n,e){let t=new Fs({noServer:!0}),r=new Set;return n.on("upgrade",(s,o,i)=>{if(new URL(s.url??"/","http://localhost").pathname!==Vt)return;r.add(o),o.on("close",()=>{r.delete(o)});let u=k("rtup"),d=Gs(s),l=_=>{(e.log??js)(Bs(_))};l({stage:"accept",conn:u,model:d}),o.resume();let c=new AbortController,v=null,p=_=>{v??=_,c.abort(new Error(v))},x=()=>p("client socket closed"),R=()=>p("client socket closed (half-close)"),b=_=>p(`client socket error: ${_.message}`);o.once("close",x),o.once("end",R),o.once("error",b);let m=()=>{o.removeListener("close",x),o.removeListener("end",R),o.removeListener("error",b)},h=_=>{l({stage:"close",conn:u,model:d,..._})},g=_=>{let f=_,y=f.session!=null&&typeof f.session.sendResponseCreate=="function",P=f.clients!=null&&typeof f.clients.createResponse=="function";if(!y&&!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((w,I)=>{t.handleUpgrade(s,o,i,C=>{try{new We({ws:C,binding:_,onClosed:($,K)=>{h({while:"live",reason:K.reason})}}),l({stage:"admit",conn:u,model:d,...Jt(_)===void 0?{}:{session:Jt(_)}}),w()}catch($){I($)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(s,c.signal).then(async _=>{if(c.signal.aborted){m();let f=Jt(_);try{await _.release?.()}catch(y){h({while:"queued",...f===void 0?{}:{session:f},reason:v??"client socket closed",release_failed:y instanceof Error?y.message:String(y)});return}h({while:"queued",...f===void 0?{}:{session:f},reason:v??"client socket closed",released:!0}),o.destroy();return}m(),await g(_)}).catch(_=>{let f=_ instanceof Ns?_t(_):null,y=null;if(_!==null&&typeof _=="object"&&"status"in _){let I=_.status;typeof I=="number"&&(y=I)}let P=y??f?.status??502,w=_ instanceof Error?_.message:String(_);h({while:"queued",...c.signal.aborted?{reason:v??"client socket closed"}:{reason:w,status:P}}),o.destroyed||Ds(o,P,w)}).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=>t.close(()=>o()))}}A();A();A();import{createServer as li}from"http";A();import{WebSocketServer as no,WebSocket as Qe}from"ws";A();A();import{randomUUID as Hs}from"crypto";var Hn="Inference-Id";function Ke(){return Hs()}function Kt(n){return n==="/v1"||n.startsWith("/v1/")}function Jn(n,e){if(!Kt(n)||e===null)throw new Error(`no inference turn for ${n}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function ze(n){return`resp_${n}`}function Vn(n){return`chatcmpl-${n}`}function Wn(n){return`msg_${n}`}function oe(n){return e=>{n.sessionId=e.sessionId,n.catalog=e.identity}}function Kn(n){let e=n.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:n.turn.id,method:n.method,path:n.path,status:n.res.headersSent?n.res.statusCode:null,delivered:n.res.writableFinished,stream_error:n.turn.streamError,model:n.turn.model,stream:n.turn.stream,org:n.turn.org,duration_ms:e()-n.turn.startedAt,ttft_ms:n.turn.stream===!0?n.turn.ttftMs:null,prompt_tokens:n.turn.promptTokens,completion_tokens:n.turn.completionTokens,output_units:n.turn.outputUnits,output_minutes:n.turn.outputMinutes,session_id:n.turn.sessionId,queue_ms:n.turn.timing?.queue_ms??null,prefill_ms:n.turn.timing?.prefill_ms??null,decode_ms:n.turn.timing?.decode_ms??null,total_ms:n.turn.timing?.total_ms??null,...n.turn.decision?{decision_resolve_ms:n.turn.decision.resolve_ms,decision_dial_ms:n.turn.decision.dial_ms,decision_first_event_ms:n.turn.decision.first_event_ms,decision_stream_ms:n.turn.decision.stream_ms,decision_question_fwd_ms:n.turn.decision.question_fwd_ms,decision_head_ms:n.turn.decision.head_ms}:{},catalog:n.turn.catalog}}function zn(n){return`${JSON.stringify(n)}
|
|
17
|
+
`}var Js=256,Vs=128;function te(n){return typeof n.model!="string"||!n.model.trim()?"(default)":n.model.trim().slice(0,Vs)}var xe=class n{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,t,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=t,this.naiveInBytes+=r}modelEntry(e){let t=this.models[e];if(t)return t;let r=Object.keys(this.models).length>=Js?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,t,r){let s=this,o=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),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+=d.delta.length,t!==void 0&&(s.modelEntry(t).tokens_out+=1)),yield d;let u=(performance.now()-(i??o))/1e3;a>0&&u>0&&(s.tokRates.push(a/u),s.tokRates.length>512&&s.tokRates.shift())})()}static p50(e){if(!e.length)return null;let t=[...e].sort((r,s)=>r-s);return t[Math.floor(t.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((t,r)=>t+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:n.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:n.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Ws=256;function Ks(n){if(typeof n=="string")return[{role:"user",content:n}];if(Array.isArray(n))return n;throw new Error("responses input must be a string or an array of messages/items")}var ke=class extends Error{},Ce=class{conversations=new Map;thread(e,t){let r=Ks(t);if(e==null)return r;let s=this.conversations.get(String(e));if(!s)throw new ke(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...s,...r]}remember(e,t,r,s=!0){this.conversations.set(e,[...t,...r]);for(let o of this.conversations.keys()){if(this.conversations.size<=Ws)break;this.conversations.delete(o)}}forget(e){this.conversations.delete(e)}},Yn=new WeakMap;function Ye(n){let e=Yn.get(n);return e||(e=new Ce,Yn.set(n,e)),e}function Me(n){let e=n?.output;return Array.isArray(e)?e.filter(t=>t.type==="function_call"):[]}function de(n){return n.find(e=>e.type==="response.completed")?.response??null}function Le(n){return n.type!=="response.function_call_arguments.delta"||typeof n.tool_index!="number"?null:{tool_index:n.tool_index,call_id:typeof n.call_id=="string"?n.call_id:void 0,name:typeof n.name=="string"?n.name:void 0,delta:typeof n.delta=="string"?n.delta:""}}var _e=class{calls=new Map;add(e){let t=this.calls.get(e.tool_index),r=!t;return t||(t={args:""},this.calls.set(e.tool_index,t)),e.call_id&&(t.id=e.call_id),e.name&&(t.name=e.name),t.args+=e.delta,{call:t,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,t])=>({type:"function_call",call_id:t.id??`call_${e}`,name:t.name??"",arguments:t.args}))}},zs=["<tool_call>","<function="];function Ys(n){return zs.find(e=>n.includes(e))}function Se(n,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${n}" (see catalog parser_defaults)`}function Re(n,e,t){if(!(!n||e>0))return Ys(t)}function Ue(n,e){let t=e?.output_text;return typeof t=="string"?t:n.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Xs(n){let e=n?.output;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s=r;s.type==="message"?t.push({role:"assistant",content:s.content??""}):s.type==="function_call"&&t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:s.arguments})}return t}function zt(n,e){let t=Xs(n);return t.length>0?t:e?[{role:"assistant",content:e}]:[]}var ie=class extends Error{constructor(t,r,s=400,o){super(t);this.code=r;this.status=s;this.param=o}code;status;param};function $e(n,e){try{return n.thread(e.previous_response_id,e.input)}catch(t){throw t instanceof ke?new ie(t.message,"previous_response_not_found",400,"previous_response_id"):new ie(String(t instanceof Error?t.message:t),"invalid_input")}}function Xn(n){let e=n.text;if(e!==null&&typeof e=="object"){let t=e.format;if(t!==void 0)return t}}async function Yt(n,e,t,r,s){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ie("instructions must be a string","invalid_instructions");let o=typeof e.instructions=="string"?e.instructions:void 0;return n.createResponse({model:e.model,input:t,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...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}:{},...Xn(e)!==void 0?{response_format:Xn(e)}:{}},s)}async function Xe(n){let{body:e,clients:t,store:r,stats:s}=n,o=$e(r,e);e.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(o))-Buffer.byteLength(JSON.stringify(e.input)));let i=n.responseId,a=n.remember??e.store!==!1,u=e.store!==!1,d=te(e);s.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,c=n.turn,v=await Yt(t,e,o,!0,c?oe(c):void 0);return{responseId:i,events:to({events:v,conversation:o,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:s,turn:n.turn})}}function Qs(n,e){let t=[...n].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],s=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),o=t.filter(u=>u.type==="message").length===s.length,i=0;return[...t.map(u=>u.type==="message"&&o?eo(s[i++],u):u),...Zs(r,t)]}function Zs(n,e){let t=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),s=d=>String(d.call_id??d.id??""),o=e.filter(d=>d.type==="function_call"),i=n.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=o.length===i,u=new Set(o.map(s));return n.filter(d=>{if(d===null||typeof d!="object")return!0;let l=d;return l.type==="message"?!t:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!u.has(s(l)):!0})}function eo(n,e){let t=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(n.content)?n.content:[];if(r.filter(t).length!==1)return e;let o=(Array.isArray(e.content)?e.content:[]).find(t);if(o===void 0)return e;let i={...n};return i.id=e.id,n.role===void 0&&(i.role=e.role),n.status===void 0&&(i.status=e.status),i.content=r.map(a=>t(a)?{...a,text:o.text}:a),i}async function*to(n){let{events:e,conversation:t,responseId:r,modelKey:s,requestHadTools:o,remember:i,persist:a,store:u,stats:d}=n,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,R=0;function*b(){p||(p=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let m=[],h=(O,L)=>{m.push({output_index:O,item:L})},g=!1,E=0,_="",f=0,y="";function*P(){if(!g)return;g=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:E,content_index:0,text:y};let O={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:y}],status:"completed"};yield{type:"response.output_item.done",output_index:E,item:O},h(E,O),y=""}let w=!1,I=0,C="",$=0,K="",ee="";function*ae(O){if(!w)return;w=!1,yield{type:"response.output_text.done",item_id:C,output_index:I,content_index:0,text:K},yield{type:"response.content_part.done",item_id:C,output_index:I,content_index:0,part:{type:"output_text",text:K}};let L={id:C,type:"message",role:"assistant",status:O,content:[{type:"output_text",text:K}]};yield{type:"response.output_item.done",output_index:I,item:L},h(I,L),K=""}let fe=new _e,G=null,H=-1;function*X(O){if(!G)return;let L=G;G=null,yield{type:"response.function_call_arguments.done",item_id:L.fcId,output_index:L.outputIndex,arguments:L.args};let V={id:L.fcId,type:"function_call",call_id:L.callId??L.fcId,name:L.name??"",arguments:L.args,status:O};yield{type:"response.output_item.done",output_index:L.outputIndex,item:V},h(L.outputIndex,V)}let we=!1;for await(let O of d.track(e,s,n.turn)){l.push(O);let L=String(O.type??"");if(L==="response.created"||L==="response.in_progress"){p=!0,yield c(O);continue}if(L==="response.output_item.added"){x=!0,yield c(O);continue}if(L==="response.reasoning_text.delta"&&!x){yield*b(),g||(g=!0,E=R++,f+=1,_=f===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${f}`,yield{type:"response.output_item.added",output_index:E,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),y+=String(O.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:E,content_index:0,delta:O.delta};continue}if(L==="response.output_text.delta"&&!x){yield*b(),yield*P(),w||(w=!0,I=R++,$+=1,C=$===1?v:`${v}_${$}`,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:""}}),K+=String(O.delta??""),ee+=String(O.delta??""),yield{type:L,item_id:C,output_index:I,content_index:0,delta:O.delta};continue}let V=x?null:Le(O);if(V){if(yield*b(),yield*P(),yield*ae("completed"),fe.add(V),V.tool_index!==H){yield*X("completed"),H=V.tool_index;let ce=R++;G={fcId:`fc_${r.slice(5)}_${V.tool_index}`,outputIndex:ce,callId:V.call_id,name:V.name,args:""},yield{type:"response.output_item.added",output_index:ce,item:{id:G.fcId,type:"function_call",call_id:G.callId??G.fcId,name:G.name??"",arguments:"",status:"in_progress"}}}G&&(V.call_id&&(G.callId=V.call_id),V.name&&(G.name=V.name),G.args+=V.delta,yield{type:"response.function_call_arguments.delta",item_id:G.fcId,output_index:G.outputIndex,delta:V.delta});continue}if(L==="response.completed"&&!x){let ce=Me(O.response),N=Re(o,fe.size+ce.length,ee);if(N){we=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Se(s,N)}};break}if(yield*P(),yield*ae("completed"),yield*X("completed"),fe.size===0)for(let he of ce){let Te=R++,ut=he.id??he.call_id??`fc_${Te}`,Ut=he.arguments??"",hn={id:ut,type:"function_call",call_id:he.call_id??ut,name:he.name??""};yield{type:"response.output_item.added",output_index:Te,item:{...hn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ut,output_index:Te,delta:Ut},yield{type:"response.function_call_arguments.done",item_id:ut,output_index:Te,arguments:Ut};let gn={...hn,arguments:Ut,status:"completed"};yield{type:"response.output_item.done",output_index:Te,item:gn},h(Te,gn)}let Q=Qs(m,O.response);yield Q.length>0?c({...O,response:{...O.response,output:Q}}):c(O);continue}yield c(O)}if(yield*P(),yield*ae("incomplete"),yield*X("incomplete"),i&&!we){let O=de(l);u.remember(r,t,zt(O,Ue(l,O)),a)}}var ro="/v1/responses",so=64*1024*1024,oo=8*1024*1024,io=16,Qn=32,Zn=3600*1e3,ao=/^[A-Za-z0-9._-]{1,256}$/;function ne(n,e,t){return{type:"error",status:n,...t!==void 0?{stream_id:t}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var uo=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 n,e;return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}async function lo(n){for(;n.bufferedAmount>oo&&n.readyState===Qe.OPEN;){let{promise:e,resolve:t}=Zt();setTimeout(t,5),await e}}var Xt=class extends Ce{constructor(t){super();this.shared=t}shared;thread(t,r){if(t==null)return super.thread(t,r);try{return super.thread(t,r)}catch(s){if(!(s instanceof ke))throw s;return this.shared.thread(t,r)}}remember(t,r,s,o=!0){o?this.shared.remember(t,r,s):super.remember(t,r,s)}forget(t){super.forget(t),this.shared.forget(t)}},Qt=class{constructor(e,t,r,s){this.ws=e;this.clients=t;this.stats=r;this.statusOf=s;this.store=new Xt(Ye(t)),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 (${Zn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Zn).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,t){if(this.closed)return;if(t){this.sendFrame(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"||!ao.test(s.stream_id)){this.sendFrame(uo);return}if(o=s.stream_id,!this.lanes.has(o)&&this.namedLaneCount()>=Qn){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 (${Qn}). 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??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,t){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 Xe({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ze(Ke())})}catch(i){this.failTurn(i,t,e);return}this.laneOfResponse.set(s.responseId,t??null);let o=s.events;this.activeTurns.add(o);try{for await(let i of o){if(this.closed||this.ws.readyState!==Qe.OPEN)break;this.send(i,t),await lo(this.ws)}}finally{this.activeTurns.delete(o)}}catch(r){this.failTurn(r,t,e)}finally{this.release()}}}runWarmup(e,t){if(this.closed)return;let r=ze(Ke());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,t??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},t)}catch(s){this.failTurn(s,t,e)}}failTurn(e,t,r){this.sendFrame(this.errorFrameOf(e,t));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(t??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,t){let r=String(e instanceof Error?e.message:e);if(e instanceof ie)return ne(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},t);if(e instanceof q)return ne(404,{type:"invalid_request_error",code:"model_not_found",message:r},t);if(e instanceof se)return ne(503,{type:"upstream_error",code:"session_gone",message:r},t);let s=this.statusOf?.(e)??null;return s?ne(s.status,{type:s.openaiType,message:r},t):ne(500,{type:"upstream_error",message:r},t)}async acquire(){for(;this.active>=io;){let{promise:e,resolve:t}=Zt();this.waiters.push(t),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,t){if(this.closed||this.ws.readyState!==Qe.OPEN)return;let r=t===void 0?e:{...e,stream_id:t};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Qe.OPEN||this.ws.send(JSON.stringify(e))}};function yt(n,e,t){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",s=`${t}\r
|
|
18
|
+
`;n.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 er(n,e){let t=new no({noServer:!0,maxPayload:so}),r=new xe,s=new Set,o=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,c,v)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{yt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),p.pathname!==ro){i.add(c);return}o.add(c);let x=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){yt(c,401,"invalid local proxy api key");return}let R;try{R=await a(l)}catch(b){let m=e.statusOf?.(b)??null;yt(c,m?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(x=!0,t.handleUpgrade(l,c,v,b=>{o.delete(c),s.add(b),b.on("close",()=>s.delete(b));try{new Qt(b,R,r,e.statusOf)}catch{s.delete(b),b.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!x&&!c.destroyed&&yt(c,500,"responses websocket upgrade failed")}).finally(()=>o.delete(c))};return n.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Zt();if(u)return c(),l;u=!0,n.off("upgrade",d);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!==Qe.CLOSED&&p.terminate()},2e3);return v.unref?.(),t.close(()=>{clearTimeout(v),c()}),l}}}A();var Ne=class extends Error{code;status;retryAfterSeconds;constructor(e,t,r,s){super(s),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Ze=class extends Ne{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},en=class extends Ne{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},et=class extends Error{constructor(){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError"}},tr=class{constructor(e){this.opts=e;if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e5}opts;slots=[];nextIndex=0;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}async boot(){if(!(this.closed||this.draining)){for(;this.slots.length<this.opts.min;)this.ensureSlot();await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t));return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Ze;let e=this.opts.acquireTimeoutMs??6e5,t=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new Ze;if(!this.slots.some(u=>u.state==="queued")&&this.slots.length<this.opts.max){this.ensureSlot();continue}let o=t+e-Date.now();if(o<=0)throw new en(e);let i,a={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(u=>{a.resolve=u,this.waiters.push(a)}),new Promise(u=>{i=setTimeout(u,o)})])}finally{clearTimeout(i);let u=this.waiters.indexOf(a);u!==-1&&this.waiters.splice(u,1),a.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Ze}}tryAcquireReady(){if(this.closed)return null;this.restoreMin();let e=this.tryLease();return e||(!this.slots.some(t=>t.state==="queued")&&this.slots.length<this.opts.max&&this.ensureSlot(),null)}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let o=s.session;if(typeof o!="object"||o===null||!("whenLive"in o))return!1;let i=o.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(o,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){this.restoreMin();let e=null;for(let o of this.slots)o.state!=="attached"||o.inFlight>=this.opts.inFlightCap||(!e||o.inFlight<e.inFlight)&&(e=o);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1;let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.signalDrain())}restoreMin(){if(this.slots.filter(r=>r.state!=="paused").length>=this.opts.min)return;let t=this.slots.filter(r=>r.state==="paused"&&!r.opening);t.sort((r,s)=>r.slot.index-s.slot.index);for(let r of t){if(this.slots.filter(s=>s.state!=="paused").length>=this.opts.min)break;this.openRuntime(r)}}reap(){if(this.closed||this.draining)return;this.restoreMin();let e=this.now(),t=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,s)=>(r.idleSince??0)-(s.idleSince??0)||s.slot.index-r.slot.index);for(let r of t){if(this.slots.filter(s=>s.state!=="paused").length<=this.opts.min)break;this.endSlot(r)}}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(s=>s.state==="attached").length,t=this.slots.filter(s=>s.state==="queued").length,r=this.slots.filter(s=>s.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:r,inFlight:this.slots.reduce((s,o)=>s+o.inFlight,0),draining:this.draining}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,t)=>e+t.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let t of this.waiters.splice(0))t.settled||(t.settled=!0,t.resolve());if(this.slots.reduce((t,r)=>t+r.inFlight,0)>0){if(!this.drainComplete){let r,s=new Promise(o=>{r=o});this.drainComplete={promise:s,resolve:r}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let s of this.waiters.splice(0))s.settled||(s.settled=!0,s.resolve());let e=this.slots.map(s=>s.entry).filter(s=>s!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(s=>this.opts.closeSlot(s)))).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};A();A();var Y=class extends Error{};async function wt(n,e){let t=Number(n.headers["content-length"]??"0");if(Number.isFinite(t)&&t>e)throw new Y(`request body exceeds the ${e}-byte limit`);let r=[],s=0;for await(let o of n){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 vt(n,e){let t=n[Symbol.asyncIterator](),r=0,s=new ReadableStream({async pull(i){try{let a=await t.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(){t.return?.()}}),o;try{let i=new Headers;for(let[d,l]of Object.entries(n.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let c of l)i.append(d,c);let a={method:"POST",headers:i,body:s,duplex:"half"};o=await new Request(`https://proxy.internal${n.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 nr="/v1/images/generations",bt="/v1/images/edits";function rr(n){return n===nr||n===bt}var sr="/v1/images/models";async function or(n,e,t){if(n){if(n.model=te({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var M=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}},co=16*1024*1024,ir=64*1024*1024;function ar(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":null}function tt(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function ur(n,e,t,r){let s=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1},r),o=null;for await(let c of s){if(c.type==="error"){let v=c.error??{};throw new M(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 M(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 M(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(ar(d)===null)throw new M(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function dr(n){return n instanceof M?n:n instanceof q?new M(404,n.message):new M(502,`image upstream failed: ${String(n instanceof Error?n.message:n)}`)}async function lr(n,e,t,r){if(await n(e,t))return!0;let s=t==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return tt(r,new M(404,e===void 0?`no image-capable default model is configured for this caller (${s}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${t==="edit"?"edit-capable":"generation-capable"} for this caller (${s}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function cr(n,e){n&&(n.outputUnits=e.images.length)}function pr(n,e){n.statusCode=200,n.setHeader("content-type","application/json"),n.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(t=>({b64_json:t}))}))}var po={model:!0,prompt:!0,response_format:!0,n:!0};async function mr(n,e,t){let r=t.maxBodyBytes??ir;try{if(n.method!=="POST")throw new M(405,`${String(n.method)} is not supported on ${nr}`);let s;try{s=JSON.parse((await wt(n,r)).toString("utf8")||"{}")}catch(c){throw c instanceof Y?new M(413,c.message):new M(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new M(400,"request body must be a JSON object");let o=s;for(let c of Object.keys(o))if(!po[c])throw new M(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 M(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 M(400,"model must be a string","model");await or(t.turn,t.clients,a);let u=o.n??1;if(u!==1)throw new M(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=o.response_format??"b64_json";if(d!=="b64_json")throw new M(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(t.stats?.request("images_generations",i.length,i.length),!await lr(t.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await ur(t.clients,a,l,t.turn?oe(t.turn):void 0);cr(t.turn,c),pr(e,c)}catch(c){throw dr(c)}}catch(s){if(s instanceof Y){tt(e,new M(413,s.message));return}if(s instanceof M){tt(e,s);return}throw s}}var mo={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function fr(n,e,t){let r=t.maxBodyBytes??ir,s=t.maxImagePartBytes??co;try{if(n.method!=="POST")throw new M(405,`${String(n.method)} is not supported on ${bt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new M(400,`the edit endpoint consumes multipart/form-data, got ${o||"none"}`);let i;try{i=await vt(n,r)}catch(p){throw p instanceof Y?new M(413,p.message):new M(400,String(p instanceof Error?p.message:p))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new M(400,"model must be a string field","model");let d=u===null?void 0:u;await or(t.turn,t.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new M(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(!mo[p])throw new M(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 M(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 M(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let R=new Uint8Array(await x.arrayBuffer()),b=ar(R);if(b===null)throw new M(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:R,mime:b})}if(c.length===0)throw new M(400,"the edit endpoint requires at least one `image` file part","image");if(t.stats?.request("images_edits",a.length,a.length),!await lr(t.imageModels,d,"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 ur(t.clients,d,v,t.turn?oe(t.turn):void 0);cr(t.turn,p),pr(e,p)}catch(p){throw dr(p)}}catch(o){if(o instanceof Y){tt(e,new M(413,o.message));return}if(o instanceof M){tt(e,o);return}throw o}}A();var nt="/v1/audio/speech";function kr(n){return n===nt}var hr=4096,gr=18e4,_r=5e3,fo=64*1024*1024,yr=8,wr=5,vr=1024*1024,Fe="voice_applied",kt="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,t,r,s){super(t),this.status=e,this.param=r,this.retryAfterSeconds=s}};function tn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&n.setHeader("retry-after",String(e.retryAfterSeconds)),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var St=class extends T{constructor(e){super(502,e)}};function Sr(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t!==9&&!(t>=32&&t<=126)&&!(t>=128&&t<=255))return!1}return!0}function Rr(n){return new T(502,`the runtime's ${Fe} receipt ${JSON.stringify(n)} cannot be relayed as the ${kt} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function ho(n,e,t){if(n){if(n.model=te({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Er(n,e){if(!n)return;let t=e/(24e3*2);n.outputUnits=t,n.outputMinutes=t/60}var go=2;function _o(n){for(let e=0;e+1<n.byteLength;e+=2)if(Math.abs(n.readInt16LE(e))>go)return!1;return!0}function yo(n){let e=24e3,t=2,r=1,s=Buffer.alloc(44);return s.write("RIFF",0,"ascii"),s.writeUInt32LE(36+n,4),s.write("WAVE",8,"ascii"),s.write("fmt ",12,"ascii"),s.writeUInt32LE(16,16),s.writeUInt16LE(1,20),s.writeUInt16LE(r,22),s.writeUInt32LE(e,24),s.writeUInt32LE(e*r*t,28),s.writeUInt16LE(r*t,32),s.writeUInt16LE(16,34),s.write("data",36,"ascii"),s.writeUInt32LE(n,40),s}var br=new WeakMap,xt=new WeakMap;function wo(n,e){let t=xt.get(n)??0;if(t>=yr)throw new T(503,`this model's speech queue is full \u2014 ${yr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${wr}s`,void 0,wr);xt.set(n,t+1);let r=br.get(n)??Promise.resolve(),s,o=new Promise(i=>{s=i});return br.set(n,o),(async()=>{await r;try{return await e()}finally{xt.set(n,(xt.get(n)??1)-1),s()}})()}async function vo(n,e,t,r){if(typeof n.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 n.evictSpeechSession(e)}catch(i){if(!(i instanceof se))throw i}if(t?.return===void 0)return;let s=Promise.resolve(t.return()).then(()=>{},()=>{}),o;await Promise.race([s,new Promise(i=>{o=setTimeout(i,r)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}function Ee(n){return n instanceof T?n:n instanceof q?new T(404,n.message):new T(502,`speech upstream failed: ${String(n instanceof Error?n.message:n)}`)}async function xr(n,e,t,r,s,o,i,a){let u=a??(()=>{});return wo(e,async()=>{if(i?.()===!0)return null;let d=!1,l=!1,c=!1,v,p=new Promise(_=>{v=_}),x=[],R=()=>{l&&!c&&x.length>=s.quietRunFrames&&(c=!0,v())},b=e.onOutputAudio(_=>{let f=Buffer.from(_,"base64");if(f.byteLength===0)return;let y=_o(f);if(!d){if(y)return;d=!0}if(y){x.push(f),R();return}for(let P of x)u(P);x.length=0,u(f),R()}),m=null,h,g,E;try{E=(await n.createResponseOn(t,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let f=new Promise(w=>{g=setTimeout(w,o.capMs)}),y=!1;for(;;){let w=E.next(),I=await Promise.race([w,f]);if(I===void 0){y=!0,w.catch(()=>{});break}if(I.done)break;let C=I.value;if(C.type==="error"){let $=C.error??{};throw await E.return?.(),new T(502,`speech upstream error: ${String($.message??"upstream reported an error")}`)}if(C.type==="response.completed"){m=C.response??null,l=!0,R(),await E.return?.();break}}if(clearTimeout(g),y)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(m===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(w=>{h=setTimeout(()=>{P=!0,w()},s.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let w=m[Fe];if(typeof w!="string"||w!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof w=="string"?`${Fe} ${JSON.stringify(w)}`:`no ${Fe} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new St(I):new T(502,I)}}if(!d)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 m}catch(_){throw _ instanceof St||await vo(n,t,E,o.returnBoundMs),_}finally{h!==void 0&&clearTimeout(h),g!==void 0&&clearTimeout(g),b()}})}function bo(n,e,t,r){let s=!1,o=0,i=a=>{n.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){t()||(s||(s=!0,n.statusCode=200,n.setHeader("content-type","audio/pcm"),r&&n.setHeader("trailer",kt)),n.write(a,u=>{u||(o+=a.byteLength,Er(e,o))}),n.writableLength>vr&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${vr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>s,async finish(a){if(!t()){if(r){let u=a[Fe];if(typeof u=="string"){if(!Sr(u))throw Rr(u);n.addTrailers({[kt]:u})}}await new Promise(u=>{n.end(()=>u())})}},fail:i}}async function xo(n,e,t){let r;try{r=await n(e)}catch(s){throw Ee(s)}return r?!0:(tn(t,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 ko={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},So="wav, pcm";async function Ir(n,e,t){let r=t.maxBodyBytes??fo,s=!1;e.once("close",()=>{s=!0});let o=()=>s||e.destroyed;try{if(n.method!=="POST")throw new T(405,`${String(n.method)} is not supported on ${nt}`);let i;try{i=JSON.parse((await wt(n,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(!ko[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 u=a.input;if(typeof u!="string"||u.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(u.length>hr)throw new T(400,`input is ${u.length} chars \u2014 over the ${hr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new T(400,"model must be a string","model");let 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 t.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 ${nt} against a stale copy of the list`);let c;try{c=await t.clients.speechVoices(d)}catch(g){throw Ee(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 ${So} \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 R=a.instructions;if(R!==void 0){if(typeof R!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(R.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 ho(t.turn,t.clients,d);let b=Buffer.byteLength(JSON.stringify(a));if(t.stats?.request("audio_speech",b,b),!await xo(t.speechModels,d,e))return;if(typeof t.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 t.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 t.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 m;try{m=await t.clients.speechSessionHandle(d)}catch(g){throw Ee(g)}let h;try{h=await t.clients.openAudioOn(m)}catch(g){throw Ee(g)}t.turn&&(t.turn.sessionId=h.sessionId);try{if(p==="wav"){let g=[],E=await xr(t.clients,h,m,{model:d,text:u,...v!==void 0?{voice:v}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??gr,returnBoundMs:t.turnReturnBoundMs??_r},o,f=>g.push(f));if(E===null||o())return;let _=Buffer.concat(g);if(v===void 0){let f=E[Fe];if(typeof f=="string"){if(!Sr(f))throw Rr(f);e.setHeader(kt,f)}}Er(t.turn,_.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([yo(_.byteLength),_]))}else{let g=bo(e,t.turn,o,v===void 0),E;try{E=await xr(t.clients,h,m,{model:d,text:u,...v!==void 0?{voice:v}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??gr,returnBoundMs:t.turnReturnBoundMs??_r},o,g.sink)}catch(_){let f=Ee(_);if(!g.started())throw f;t.turn&&(t.turn.streamError=!0),g.fail(f);return}if(E===null)return;try{await g.finish(E)}catch(_){let f=Ee(_);t.turn&&(t.turn.streamError=!0),g.fail(f);return}}}catch(g){throw Ee(g)}}catch(i){if(i instanceof Y){tn(e,new T(413,i.message));return}if(i instanceof T){tn(e,i);return}throw i}}A();var Rt="/v1/audio/transcriptions";function Ar(n){return n===Rt}var Or="/v1/audio/models",Ro=16*1024*1024,Eo=64*1024*1024,F=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}};function nn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Tr(n){return n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===65&&n[10]===86&&n[11]===69}function Io(n){if(!Tr(n))return null;let e=12,t=null,r=null;for(;e+8<=n.length;){let o=String.fromCharCode(n[e],n[e+1],n[e+2],n[e+3]),i=(n[e+4]|n[e+5]<<8|n[e+6]<<16|n[e+7]<<24)>>>0,a=e+8;if(o==="fmt "&&a+16<=n.length){let u=n[a+2]|n[a+3]<<8,d=(n[a+4]|n[a+5]<<8|n[a+6]<<16|n[a+7]<<24)>>>0,l=n[a+14]|n[a+15]<<8;t={sampleRate:d,channels:u,bitsPerSample:l}}else if(o==="data"){let u=n.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(t===null||r===null||r===0||t.sampleRate===0||t.channels===0||t.bitsPerSample===0)return null;let s=r/(t.sampleRate*t.channels*(t.bitsPerSample/8));return!Number.isFinite(s)||s<0?null:{seconds:s,sampleRate:t.sampleRate,channels:t.channels,bitsPerSample:t.bitsPerSample}}async function Ao(n,e,t){if(n){if(n.model=te({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Oo(n,e){n&&(n.outputUnits=e.seconds)}async function To(n,e,t,r,s){let o=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1,...r!==void 0?{language:r}:{}},s),i=[],a=null;for await(let u of o){if(i.push(u),u.type==="error"){let d=u.error??{},l=typeof d.type=="string"?d.type:"upstream_error",c=String(d.message??"upstream reported an error");throw new F(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new F(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Ue(i,a)}function Pr(n){return n instanceof F?n:n instanceof q?new F(404,n.message):new F(502,`transcription upstream failed: ${String(n instanceof Error?n.message:n)}`)}async function Po(n,e,t){let r;try{r=await n(e)}catch(s){throw Pr(s)}return r?!0:(nn(t,new F(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Co=new Set(["file","model","language","response_format"]);async function Cr(n,e,t){let r=t.maxBodyBytes??Eo,s=t.maxAudioPartBytes??Ro;try{if(n.method!=="POST")throw new F(405,`${String(n.method)} is not supported on ${Rt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the transcriptions endpoint consumes multipart/form-data, got ${o||"none"}`);let i;try{i=await vt(n,r)}catch(m){throw m instanceof Y?new F(413,m.message):new F(400,String(m instanceof Error?m.message:m))}let a=new Map;for(let m of i.keys()){if(!Co.has(m))throw new F(400,`form field "${m}" 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.`,m);a.set(m,(a.get(m)??0)+1)}for(let[m,h]of a)if(h>1)throw new F(400,`form field "${m}" 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`,m);let u=i.get("model");if(u!==null&&typeof u!="string")throw new F(400,"model must be a string field","model");let d=u===null?void 0:u,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new F(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 F(400,`response_format ${JSON.stringify(v)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let p=i.get("file");if(!(p instanceof File))throw new F(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(p.size>s)throw new F(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let x=new Uint8Array(await p.arrayBuffer());if(!Tr(x))throw new F(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let R=Io(x);if(R===null)throw new F(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ao(t.turn,t.clients,d),t.stats?.request("audio_transcriptions",x.length,x.length),!await Po(t.transcriptionModels,d,e))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(x).toString("base64"),format:"wav"}}];try{let m=await To(t.clients,d,b,c,t.turn?oe(t.turn):void 0);Oo(t.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:m}))}catch(m){throw Pr(m)}}catch(o){if(o instanceof Y){nn(e,new F(413,o.message));return}if(o instanceof F){nn(e,o);return}throw o}}A();var Nr="/v1/usage/requests",Mr=1e4,Mo=/^[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(t,r=400){super(t);this.status=r;this.name="UsageRequestError"}status},W=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Et=class extends W{constructor(e){super(e),this.name="UsageWithholdingError"}},Fr=1024*1024;function on(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new ye(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let t=n[e];if(!Array.isArray(t))throw new ye(`"${e}" must be an array of uuid strings`);if(t.length>Mr)throw new ye(`"${e}" carries ${t.length} ids; at most ${Mr} 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 t){if(typeof o!="string"||!Mo.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 qr(n){return on(n,"inference_ids")}var Lo=["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 qe(n,e,t){let r=n[e];if(typeof r!="string"||r==="")throw new W(`${t}: ${e} is not a non-empty string (got ${Be(r)})`);return r}function rn(n,e,t){let r=n[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new W(`${t}: ${e} is neither null nor a non-empty string (got ${Be(r)})`);return r}function De(n,e,t,r){let s=n[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 W(`${t}: ${e} is not a number (got ${Be(s)})`);if(r&&!Number.isSafeInteger(o))throw new W(`${t}: ${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 W(`${t}: ${e} is negative`);return Object.is(o,-0)?0:o}var Uo=40,Lr=64,Ur=600;function Dr(n){let e=Object.keys(n).sort(),r=e.slice(0,Uo).map(s=>s.length>Lr?`${s.slice(0,Lr)}\u2026`:s).join(", ");return r.length>Ur&&(r=`${r.slice(0,Ur)}\u2026`),`${e.length} keys present: [${r}]`}function Be(n){return n===null?"null":n===void 0?"undefined":Array.isArray(n)?"an array":typeof n=="object"?"an object":`a ${typeof n}`}function sn(n){ge(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:n.where,reason:n.reason})}
|
|
24
|
+
`)}function $o(n,e){let t;try{t=n(e)}catch{$r(n,e);return}No(t)&&Promise.resolve(t).catch(()=>{$r(n,e)})}function No(n){return typeof n?.then=="function"}function $r(n,e){if(n!==sn)try{sn(e)}catch{}}function xu(n,e=sn){let t=n?.requests;if(!Array.isArray(t)){let s=n!==null&&typeof n=="object"&&!Array.isArray(n)?Dr(n):Be(n);throw new W(`the usage surface answered without a "requests" array: got ${Be(t)} (${s})`)}let r=[];for(let s=0;s<t.length;s++){let o=`usage.requests[${s}]`;try{r.push(Fo(t[s],o))}catch(i){if(i instanceof Et||!(i instanceof W))throw i;$o(e,{where:o,reason:i.message})}}if(t.length>0&&r.length===0)throw new W(`the usage surface returned ${t.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Fo(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new W(`${e} is not an object: got ${Be(n)}`);let t=n;if(Object.hasOwn(t,"gpu_seconds"))throw new Et(`${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 Lo)if(!Object.hasOwn(t,s))throw new W(`${e} has no "${s}" column (${Dr(t)})`);let r=De(t,"http_status",e,!0);if(r===null)throw new W(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:qe(t,"inference_id",e),model_id:qe(t,"model_id",e),identity_kind:qe(t,"identity_kind",e),variant:rn(t,"variant",e),task:qe(t,"task",e),http_status:r,started_at:qe(t,"started_at",e),completed_at:qe(t,"completed_at",e),prompt_tokens:De(t,"prompt_tokens",e,!0),completion_tokens:De(t,"completion_tokens",e,!0),output_units:De(t,"output_units",e,!1),output_minutes:De(t,"output_minutes",e,!1),cost_nano_usd:De(t,"cost_nano_usd",e,!0),price_version:rn(t,"price_version",e),priced_at:rn(t,"priced_at",e)}}function It(n,e){let t=new Set(e),r=new Set;for(let s=0;s<n.length;s++){let o=n[s];if(!t.has(o.inference_id))throw new W(`the usage surface returned an id at validated answer position ${s} that was not in the request (${e.length} asked, ${n.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(o.inference_id))throw new W(`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 ci,SessionFailedError as pi}from"@urun-sh/core";A();import{SessionFailedError as Br}from"@urun-sh/core";var pe=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},qo=33e4;function Iu(n,e=qo){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,o=new Promise((d,l)=>{s=l}),i=setTimeout(()=>s(new At),e),a;try{a=await Promise.race([r.next(),o])}catch(d){throw d instanceof se||d instanceof Br&&d.kind==="transport-failed"?d:d instanceof At?(await r.return?.(void 0),new pe("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new pe("upstream_threw",`decision stream failed: ${String(d instanceof Error?d.message:d)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new pe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var At=class extends Error{constructor(){super("stream idle timeout")}};function Au(n){return n instanceof pe?!1:n instanceof se?!0:n instanceof Br?n.kind==="transport-failed":!1}A();var an="/partners/huggingface/v1/billing/requests";function Do(n){return on(n,"requestIds")}function Bo(n){return n>=200&&n<=399}function jo(n){let e=[];for(let t of n)t.cost_nano_usd!==null&&Bo(t.http_status)&&e.push({requestId:t.inference_id,costNanoUsd:t.cost_nano_usd});return{requests:e.length>0?e:null}}async function jr(n,e){let t=Do(n),r=await e(t);return It(r,t),jo(r)}A();var Go={"/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 Ho(n){return Go[n]??null}var Jr=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Jo(n){let e=n?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Vo(n){return n==="surface"}function Wo(n){let e=n?.ledgerFailureReason;return Jr.includes(e)?e:"unknown"}var Ko=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Gr=["priced","unpriced"],zo={written:Gr,already_written:Gr,skipped:Ko,failed:Jr},Uu=Object.entries(zo).flatMap(([n,e])=>e.map(t=>({outcome:n,reason:t})));function Yo(n){return n.status===null?!1:n.status>=200&&n.status<400&&!n.stream_error}function Xo(n){let e=Date.parse(n.ts),t=Number.isFinite(n.duration_ms)?Math.max(0,n.duration_ms):0;return new Date(e-Math.round(t)).toISOString()}var Qo=256,Hr=4096,rt=12e4,Zo=250,ei=8e3,me=[],un=new Set,st=0,je=!1;function $u(){return me.length}function Nu(n=Date.now()){let e=me[0];return e===void 0?0:Math.max(0,n-e.queuedAt)}var Ot=new Set;function Vr(){return st===0&&me.length===0}function Wr(){if(Vr()){je=!1;for(let n of[...Ot])n()}}async function Fu(n=Kr){return Vr()?!0:await new Promise(e=>{let t=null,r=()=>{Ot.delete(r),t&&clearTimeout(t),e(!0)};Ot.add(r),t=setTimeout(()=>{Ot.delete(r),e(!1)},n),t.unref?.()})}function qu(){je=!0;let n=[...me.splice(0,me.length),...un];for(let e of n)e.settled||Ie(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Kr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Wr(),n.length}var Kr=5e3;function zr(n,e){return`${JSON.stringify({event:n,ts:new Date().toISOString(),...e})}
|
|
25
|
+
`}function ti(n){ge(process.stdout,n)}function Yr(n,e){try{n(e)}catch{}}function Xr(n){let{record:e,ledger:t}=n;if(t===null)return;let r=t.report??ti,s=Ho(e.path);if(s===null)return;let o=l=>{try{t.observe(l)}catch{}},i=(l,c)=>{o({outcome:"skipped",reason:l}),Yr(r,zr("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 u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:s,http_status:e.status,started_at:Xo(e),completed_at:e.ts,billable_outcome:Yo(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(me.length>=Hr){i("queue_full",`${me.length} ledger writes are already waiting (capacity ${Hr}, ${st} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}me.push({entry:d,req:n.req,record:e,ledger:t,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),st<Qo&&(st+=1,ni())}async function ni(){try{for(;;){let n=ri();if(n===void 0)return;un.add(n);try{await si(n)}finally{un.delete(n)}}}finally{st-=1,Wr()}}function ri(){let n=Date.now();for(;;){let e=me.shift();if(e===void 0)return;let t=n-e.queuedAt;if(t<rt)return e;Ie(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${t}ms for the control plane (bound ${rt}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function si(n){let{entry:e,record:t,ledger:r}=n;for(;;){n.attempts+=1;try{let s=await r.write(n.req,e);Ie(n,{outcome:"written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:s.inference_id,path:t.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:t.org,session_id:e.session_id,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,unpriced_reason:s.unpriced_reason,attempts:n.attempts});return}catch(s){let o=Jo(s);if(o!==null){Ie(n,{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:n.attempts});return}let i=Wo(s),a=Date.now()-n.queuedAt;if(je){Ie(n,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:n.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${s instanceof Error?s.message:String(s)}`});return}if(Vo(i)&&a<rt){if(await ii(oi(n.attempts)),je||Date.now()-n.queuedAt>=rt){let u=Date.now()-n.queuedAt;Ie(n,{outcome:"failed",reason:je?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:je?"dropped_on_exit":"dwell_expired",attempts:n.attempts,waited_ms:u,error:`this row's backoff outlived the ${rt}ms dwell bound (waited ${u}ms over ${n.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${s instanceof Error?s.message:String(s)}`});return}continue}Ie(n,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:n.attempts,waited_ms:a,error:s instanceof Error?s.message:String(s)});return}}}function oi(n){return Math.min(ei,Zo*2**Math.max(0,n-1))}function ii(n){return new Promise(e=>{setTimeout(e,n).unref?.()})}function Ie(n,e,t){if(n.settled)return;n.settled=!0;try{n.ledger.observe(e)}catch{}let{event:r,...s}=t;Yr(n.report,zr(r,{inference_id:n.entry.inference_id,path:n.record.path,org:n.record.org,...s}))}A();var ln="x-urun-profile",ot="voice";var re=class extends Error{status=400},ai=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,ui=/\s/;function di(n){return ai.test(n)}function dn(n,e,t){let r=n[e];if(r===void 0)return t;if(typeof r!="boolean")throw new re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Qr(n,e,t,r={}){let s=n[e];if(s===void 0)return t;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new 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 Zr(n,e){let t=Array.isArray(n)?n[0]:n,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new 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(t!=null){let d=t.trim();if(d==="")throw new re(`the ${ln} header is empty \u2014 the only profile this lane accepts is "${ot}" (omit the header for the ordinary lane)`);if(d!==ot)throw new re(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${ot}"`);i=!0}if(o!==void 0){if(typeof o!="string"||o!==ot)throw new re(`unknown profile ${JSON.stringify(o)} \u2014 the only profile this lane accepts is "${ot}"`);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 u=a??{};return{flushMaxChars:Qr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Qr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:dn(u,"sentence_flush",!0),includeReasoning:dn(u,"include_reasoning",!1),metadata:dn(u,"metadata",!1)}}var Tt=class{constructor(e,t){this.config=e;this.sink=t}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let t=this.boundedCut();this.sink(this.buffer.slice(0,t)),this.buffer=this.buffer.slice(t)}(this.buffer.length>=e||this.config.sentenceFlush&&di(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(ui.test(this.buffer[s]))return s+1;let t=Math.max(1,e),r=this.buffer.charCodeAt(t-1);return r>=55296&&r<=56319?t-1:t}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function mn(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function mi(n){n.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),n.flushHeaders(),n.socket?.setNoDelay(!0)}function Z(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function J(n,e,t,r="invalid_request_error",s){Z(n,e,{error:s?{message:t,type:r,code:s}:{message:t,type:r}})}function fn(n,e){let t=e.error,r=t?.type??"upstream_error",s=t?.message??JSON.stringify(e);Z(n,r==="invalid_request_error"?400:502,{error:{message:s,type:r,code:t?.code??null}})}function le(n,e,t,r){Z(n,e,{type:"error",error:{type:t,message:r}})}function Ge(n,e,t){if(e==="anthropic"){Z(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}Z(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var fi=64*1024*1024,it=class extends Error{};async function es(n,e=fi){let t=[],r=0;for await(let o of n){if(r+=o.length,r>e)throw new it(`request body exceeds ${e} bytes`);t.push(o)}let s=Buffer.concat(t).toString("utf8");return s?JSON.parse(s):{}}function Ae(n,e,t,r){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:r}]}}function rs(n){let e=n?.usage;if(!e||typeof e!="object")return{kind:"absent"};let t=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,s=r(t.input_tokens),o=r(t.output_tokens),i=u=>u??0,a=r(t.total_tokens)??i(s)+i(o);if(i(s)>0||i(o)>0){let u={input_tokens:i(s),output_tokens:i(o),total_tokens:a};return s===null||o===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return s===null||o===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Pt(n){let e=rs(n);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ts(n){let e=Pt(n);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 hi(n,e){let t=rs(e);t.kind==="absent"||t.kind==="partial"||(n.promptTokens=t.usage.input_tokens,n.completionTokens=t.usage.output_tokens)}function gi(n){let e=n?.urun_timing;if(!e||typeof e!="object")return null;let t=e,r=u=>{let d=t[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d: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 _i(n,e){let t=gi(e);t&&(n.timing=t)}function Oe(n,e){hi(n,e),_i(n,e)}async function Lt(n,e,t){if(typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function ss(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let s of r.content)s.type==="reasoning_text"&&(t+=String(s.text??""));return t}function yi(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var Ct=class extends Error{};function wi(n,e){return Array.isArray(e)?e.map(t=>{let r=t;if(r.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let s=r.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new Ct(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function vi(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let r of t.tool_calls){let s=r.function??{};e.push({type:"function_call",call_id:r.id,name:s.name,arguments:s.arguments})}continue}e.push({...t,content:wi(t.role,t.content)})}return e}function cn(n){return Me(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function bi(n,e,t,r,s,o){let i=ze(o.id),a=n.stream===!0;if(o.model=te(n),o.stream=a,await Lt(o,e,typeof n.model=="string"?n.model:void 0),a){let m;try{m=await Xe({body:n,clients:e,store:t,stats:s,responseId:i,turn:o})}catch(h){if(h instanceof q){Ge(r,"openai",h);return}if(h instanceof ie){J(r,h.status,h.message);return}throw h}mn(r);for await(let h of m.events)h.type==="error"&&(o.streamError=!0),h.type==="response.completed"&&Oe(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 u;try{u=$e(t,n)}catch(m){if(m instanceof ie){J(r,m.status,m.message);return}throw m}n.previous_response_id!=null&&(s.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(n.input)));let d=n.store!==!1,l=te(n);s.model(l);let c=Array.isArray(n.tools)&&n.tools.length>0,v;try{v=await Yt(e,n,u,!1,oe(o))}catch(m){if(m instanceof q){Ge(r,"openai",m);return}if(m instanceof ie){J(r,m.status,m.message);return}throw m}let p=[],x=null;for await(let m of s.track(v,l,o)){if(p.push(m),m.type==="error"){fn(r,m);return}m.type==="response.completed"&&(x=m.response)}if(x==null){J(r,502,"upstream produced no response.completed event","upstream_error");return}Oe(o,x);let R=Ue(p,x),b=Re(c,Me(x).length,R);if(b){J(r,502,Se(l,b),"upstream_error");return}d&&t.remember(i,u,zt(x,R),d),Z(r,200,{...x,id:i})}async function xi(n,e,t,r,s,o){let i=n.messages;if(!Array.isArray(i)){J(t,400,"chat/completions requires a messages array");return}let a;try{a=Zr(o,n)}catch(w){if(w instanceof re){J(t,w.status,w.message);return}throw w}let u=String(n.model??"urun"),d=Vn(s.id),l;try{l=vi(i)}catch(w){if(w instanceof Ct){J(t,400,w.message);return}throw w}let c=te(n);r.model(c),s.model=c,s.stream=n.stream===!0,await Lt(s,e,typeof n.model=="string"?n.model:void 0);let v=Array.isArray(n.tools)&&n.tools.length>0,p;try{p=await e.createResponse({model:n.model,input:l,stream:!0,tools:yi(n.tools),tool_choice:n.tool_choice,temperature:n.temperature,top_p:n.top_p,stop:n.stop,max_output_tokens:n.max_completion_tokens??n.max_tokens,...n.reasoning_effort!==void 0?{reasoning_effort:n.reasoning_effort}:{},...n.chat_template_kwargs!==void 0?{chat_template_kwargs:n.chat_template_kwargs}:{},...n.response_format!==void 0?{response_format:n.response_format}:{}},oe(s))}catch(w){if(w instanceof q){Ge(t,"openai",w);return}throw w}if(n.stream===!0){a?mi(t):mn(t);let w=[],I=new _e,C="",$=a?new Tt(a,ee=>{t.write(`data: ${JSON.stringify(Ae(d,u,{content:ee},null))}
|
|
31
|
+
|
|
32
|
+
`)}):null,K=ee=>{$?.flush(),t.write(ee),t.end()};try{a?.metadata&&t.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
|
|
33
|
+
|
|
34
|
+
`),t.write(`data: ${JSON.stringify(Ae(d,u,{role:"assistant"},null))}
|
|
35
|
+
|
|
36
|
+
`);for await(let H of r.track(p,c,s)){w.push(H);let X=Le(H);if(H.type==="response.output_text.delta"&&typeof H.delta=="string")C+=H.delta,$?$.push(H.delta):t.write(`data: ${JSON.stringify(Ae(d,u,{content:H.delta},null))}
|
|
37
|
+
|
|
38
|
+
`);else if(H.type==="response.reasoning_text.delta"&&typeof H.delta=="string")(!a||a.includeReasoning)&&t.write(`data: ${JSON.stringify(Ae(d,u,{reasoning_content:H.delta},null))}
|
|
39
|
+
|
|
40
|
+
`);else if(X){$?.flush();let{call:we,isNew:O}=I.add(X),L=O?{index:X.tool_index,id:we.id??`call_${X.tool_index}`,type:"function",function:{name:we.name??"",arguments:X.delta}}:{index:X.tool_index,function:{arguments:X.delta}};t.write(`data: ${JSON.stringify(Ae(d,u,{tool_calls:[L]},null))}
|
|
41
|
+
|
|
42
|
+
`)}else if(H.type==="error"){s.streamError=!0,K(`data: ${JSON.stringify({error:H})}
|
|
43
|
+
|
|
44
|
+
`);return}}let ee=cn(de(w)),ae=Re(v,I.size+ee.length,C);if(ae){s.streamError=!0,K(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Se(c,ae)}})}
|
|
45
|
+
|
|
46
|
+
`);return}$?.flush(),I.size===0&&ee.length>0&&t.write(`data: ${JSON.stringify(Ae(d,u,{tool_calls:ee},null))}
|
|
47
|
+
|
|
48
|
+
`);let fe=I.size>0||ee.length>0;t.write(`data: ${JSON.stringify(Ae(d,u,{},fe?"tool_calls":"stop"))}
|
|
49
|
+
|
|
50
|
+
`);let G=Pt(de(w));Oe(s,de(w)),G&&t.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:ts(de(w))})}
|
|
51
|
+
|
|
52
|
+
`),t.write(`data: [DONE]
|
|
53
|
+
|
|
54
|
+
`),t.end();return}finally{$?.flush(),$?.dispose()}}let x="",R="",b=[],m=new _e;for await(let w of r.track(p,c,s)){b.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"&&(R+=w.delta);let I=Le(w);if(I&&m.add(I),w.type==="error"){fn(t,w);return}}let h=de(b);Oe(s,h);let g=cn(h),E=g.length>0?g:cn({output:m.items()}),_=Re(v,E.length,x);if(_){J(t,502,Se(c,_),"upstream_error");return}let f=E.map(({index:w,...I})=>I),y={role:"assistant",content:x||null},P=R||ss(h);P&&(y.reasoning_content=P),f.length>0&&(y.tool_calls=f),Z(t,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:y,finish_reason:f.length>0?"tool_calls":"stop"}],usage:ts(h)})}var ki="sense-latest";async function Si(n,e,t,r,s){if(n===null||typeof n!="object"||Array.isArray(n)){J(t,400,"systemone requires a JSON object body");return}delete n.key;let o=typeof n.model=="string"&&n.model?n.model:ki,i=te({model:o});if(s.model=i,s.stream=!1,n.state===void 0||n.state===null){J(t,400,"systemone requires a state (string or JSON structure)");return}let a=n.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){J(t,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(n.media!==void 0&&!Array.isArray(n.media)){J(t,400,"systemone media, when present, must be an array");return}let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};s.decision=u;let d=performance.now();r.model(i),await Lt(s,e,o),u.resolve_ms=Math.round(performance.now()-d);let l,c=performance.now();try{l=await e.createResponse({model:o,input:[{role:"user",content:JSON.stringify(n)}],stream:!0},oe(s))}catch(m){if(m instanceof q){Ge(t,"openai",m);return}if(m instanceof et){t.setHeader("retry-after","2"),J(t,503,m.message,"capacity_error");return}throw m}u.dial_ms=Math.round(performance.now()-c);let v=[],p=null;try{for await(let m of r.track(l,i,s))if(p===null&&(p=performance.now(),u.first_event_ms=Math.round(p-c)),v.push(m),m.type==="error"){fn(t,m);return}}catch(m){if(m instanceof q){p!==null&&(u.stream_ms=Math.round(performance.now()-p)),Ge(t,"openai",m);return}if(m instanceof et){p!==null&&(u.stream_ms=Math.round(performance.now()-p)),t.setHeader("retry-after","2"),J(t,503,m.message,"capacity_error");return}throw p!==null&&(u.stream_ms=Math.round(performance.now()-p)),m}p!==null&&(u.stream_ms=Math.round(performance.now()-p));let x=de(v);if(x==null){J(t,502,"upstream produced no response.completed event","upstream_error");return}Oe(s,x);let R=Ue(v,x),b;try{b=JSON.parse(R)}catch{J(t,502,"systemone answer was not valid JSON","upstream_error");return}if(b===null||typeof b!="object"||Array.isArray(b)){J(t,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof b=="object"&&b!==null&&!Array.isArray(b)&&"timing"in b){let m=b.timing;if(typeof m=="object"&&m!==null&&!Array.isArray(m)&&"question_fwd_ms"in m&&"head_ms"in m){let h=g=>typeof g=="number"&&Number.isFinite(g)&&g>=0?Math.round(g):null;u.question_fwd_ms=h(m.question_fwd_ms),u.head_ms=h(m.head_ms)}}Z(t,200,b)}function Ri(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var at=class extends Error{};function Mt(n){return new at(`unsupported anthropic content block type "${n}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ei(n){if(Array.isArray(n))return n.map(e=>{let t=e;return{type:"function",name:t.name,description:t.description,parameters:t.input_schema}})}function Ii(n){if(n==null)return;let e=n.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:n.name};throw new at(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Ai(n){if(typeof n=="string")return n;if(n==null)return"";if(!Array.isArray(n))throw Mt(typeof n);let e="";for(let t of n){let r=String(t.type??"");if(r!=="text")throw Mt(`tool_result > ${r}`);e+=String(t.text??"")}return e}function Oi(n){let{role:e,content:t}=n;if(typeof t=="string")return[{role:e,content:t}];if(t==null)return[];if(!Array.isArray(t))throw Mt(typeof t);let r=[],s="",o=()=>{s&&(r.push({role:e,content:s}),s="")};for(let i of t){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:Ai(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Mt(a)}}return o(),r}function pn(n){return Me(n).map((e,t)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${t}`,name:e.name??"",input:r}})}async function Ti(n,e,t,r,s){let o=n.messages;if(!Array.isArray(o)){le(t,400,"invalid_request_error","messages requires a messages array");return}if(typeof n.max_tokens!="number"||!Number.isInteger(n.max_tokens)||n.max_tokens<1){le(t,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(n.top_k!==void 0){le(t,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(n.stop_sequences!==void 0&&(!Array.isArray(n.stop_sequences)||n.stop_sequences.some(y=>typeof y!="string"))){le(t,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(n.model??"urun"),a=Wn(s.id),u=[],d;try{n.system&&u.push({role:"system",content:Ri(n.system)});for(let y of o)u.push(...Oi(y));d=Ii(n.tool_choice)}catch(y){if(y instanceof at){le(t,400,"invalid_request_error",y.message);return}throw y}let l=te(n);r.model(l),s.model=l,s.stream=n.stream===!0,await Lt(s,e,typeof n.model=="string"?n.model:void 0);let c=Array.isArray(n.tools)&&n.tools.length>0,v;try{v=await e.createResponse({model:n.model,input:u,stream:!0,tools:Ei(n.tools),tool_choice:d,temperature:n.temperature,max_output_tokens:n.max_tokens,top_p:n.top_p,stop:n.stop_sequences},oe(s))}catch(y){if(y instanceof q){Ge(t,"anthropic",y);return}throw y}let p=(y,P)=>{t.destroyed||t.write(`event: ${y}
|
|
55
|
+
data: ${JSON.stringify({type:y,...P})}
|
|
56
|
+
|
|
57
|
+
`)};if(n.stream===!0){let y=r.track(v,l,s);mn(t),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,w="",I=0,C="none",$=()=>C,K=-1,ee=-1,ae=new _e,fe=[],G=()=>{C!=="none"&&(C="none",p("content_block_stop",{index:K}))},H=(N,Q)=>{G(),C=N,K=I++,p("content_block_start",{index:K,content_block:Q})};for await(let N of y){if(t.destroyed)break;fe.push(N);let Q=Le(N);if(N.type==="response.reasoning_text.delta"&&typeof N.delta=="string")$()!=="thinking"&&H("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:K,delta:{type:"thinking_delta",thinking:N.delta}});else if(N.type==="response.output_text.delta"&&typeof N.delta=="string")$()!=="text"&&H("text",{type:"text",text:""}),P+=1,w+=N.delta,p("content_block_delta",{index:K,delta:{type:"text_delta",text:N.delta}});else if(Q){let{call:he}=ae.add(Q);($()!=="tool"||Q.tool_index!==ee)&&(ee=Q.tool_index,H("tool",{type:"tool_use",id:he.id??`call_${Q.tool_index}`,name:he.name??"",input:{}})),Q.delta&&p("content_block_delta",{index:K,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)}}),t.end();return}}if(t.destroyed)return;let X=de(fe),we=Me(X),O=Re(c,ae.size+we.length,w);if(O){s.streamError=!0,p("error",{error:{type:"api_error",message:Se(l,O)}}),t.end();return}G();let L=[];if(ae.size===0)try{L=pn(X)}catch(N){s.streamError=!0,p("error",{error:{type:"api_error",message:String(N instanceof Error?N.message:N)}}),t.end();return}I===0&&L.length===0&&(H("text",{type:"text",text:""}),G()),L.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 V=ae.size>0||L.length>0,ce=Pt(X);Oe(s,X),p("message_delta",{delta:{stop_reason:V?"tool_use":"end_turn"},usage:ce?{input_tokens:ce.input_tokens,output_tokens:ce.output_tokens}:{output_tokens:P}}),p("message_stop",{}),t.end();return}let x="",R="",b=[],m=new _e;for await(let y of r.track(v,l,s)){b.push(y),y.type==="response.output_text.delta"&&typeof y.delta=="string"&&(x+=y.delta),y.type==="response.reasoning_text.delta"&&typeof y.delta=="string"&&(R+=y.delta);let P=Le(y);if(P&&m.add(P),y.type==="error"){let w=y.error,I=w?.type==="invalid_request_error";le(t,I?400:502,I?"invalid_request_error":"api_error",w?.message??JSON.stringify(y));return}if(t.destroyed)break}if(t.destroyed)return;let h=de(b);Oe(s,h);let g;try{g=pn(h),g.length===0&&m.size>0&&(g=pn({output:m.items()}))}catch(y){le(t,502,"api_error",String(y instanceof Error?y.message:y));return}let E=Re(c,g.length,x);if(E){le(t,502,"api_error",Se(l,E));return}let _=[],f=R||ss(h);f&&_.push({type:"thinking",thinking:f}),(x||g.length===0)&&_.push({type:"text",text:x}),_.push(...g),Z(t,200,{id:a,type:"message",role:"assistant",content:_,model:i,stop_reason:g.length>0?"tool_use":"end_turn",usage:Pt(h)??{input_tokens:0,output_tokens:0}})}function Pi(n){ge(process.stdout,n)}function Ci(n){let{clients:e,apiKey:t,identity:r,statusOf:s}=n,o=typeof e=="function"?e:()=>e,i=n.requestLog??Pi,a=n.observe,u=new xe;return(d,l)=>{let c=new URL(d.url??"/","http://localhost"),v=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),p=(h,g,E,_,f)=>v?le(l,h,_,g):J(l,h,g,E,f),x=Kt(c.pathname),R=c.pathname.startsWith("/partners/"),b=x||R?{id:Ke(),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;b&&(l.setHeader(Hn,b.id),l.once("close",()=>{let h=Kn({turn:b,method:d.method??"",path:c.pathname,res:l});i(zn(h)),a?.(h),Xr({record:h,ledger:n.ledger??null,req:d})}));let m=()=>Jn(c.pathname,b);(async()=>{if(d.method==="GET"&&c.pathname==="/healthz"){Z(l,200,{ok:!0});return}if(d.method==="GET"&&c.pathname==="/stats"){Z(l,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(t&&(d.headers.authorization??"")!==`Bearer ${t}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=c.pathname===Nr?"canonical":c.pathname===an?"huggingface":null;if(h){if(d.method!=="POST"){p(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let f=n.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 y=f.authorize(d),P;try{P=await es(d,Fr)}catch(C){if(C instanceof it){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 w=C=>f.lookup(y,C),I;try{if(h==="canonical"){let C=qr(P),$=await w(C);It($,C),I={requests:$}}else I=await jr(P,w)}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(d.method==="GET"&&c.pathname===He){let f=await o(d);if(b&&(b.org=f.tenant??null),!f.openRouterModels){p(501,`GET ${He} 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 ${d.method} ${c.pathname} \u2014 the partner surface currently carries ${an} and GET ${He}`,"invalid_request_error","not_found_error");return}let g=await o(d);if(b&&(b.org=g.tenant??null),d.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){l.writeHead(308,{location:He}),l.end();return}Z(l,200,await g.listModels());return}if(d.method==="GET"&&c.pathname===sr){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(rr(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:u,turn:m()};c.pathname===bt?await fr(d,l,f):await mr(d,l,f);return}if(d.method==="GET"&&c.pathname===Or){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(Ar(c.pathname)){if(!g.supportsTranscription){p(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Rt}`,"not_implemented","not_implemented_error");return}let f={clients:g,transcriptionModels:g.supportsTranscription,stats:u,turn:m()};await Cr(d,l,f);return}if(kr(c.pathname)){if(!g.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${nt}`,"not_implemented","not_implemented_error");return}let f={clients:g,speechModels:g.supportsSpeech,stats:u,turn:m()};await Ir(d,l,f);return}if(d.method!=="POST"){p(404,`no route for ${d.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let E;try{E=await es(d)}catch(f){if(f instanceof it){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 _=Buffer.byteLength(JSON.stringify(E));if(c.pathname==="/v1/responses"){u.request("responses",_,_),await bi(E,g,Ye(g),l,u,m());return}if(c.pathname==="/v1/chat/completions"){u.request("chat_completions",_,_),await xi(E,g,l,u,m(),d.headers[ln]);return}if(c.pathname==="/v1/systemone"){u.request("systemone",_,_),await Si(E,g,l,u,m());return}if(c.pathname==="/v1/messages"){u.request("messages",_,_),await Ti(E,g,l,u,m());return}if(c.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",_,_),le(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?.(h)??null;if(_){p(_.status,g,_.openaiType,_.anthropicType);return}if(h instanceof ci){let f=gt(h.code);if(f){let y=h.retryAfterSeconds??(f.status===429?30:void 0);y!==void 0&&l.setHeader("Retry-After",String(y)),p(f.status,Ht(f,h.code??void 0),f.openaiType,f.anthropicType,f.code);return}}if(h instanceof pi){let f=_t(h);if(f){let y=f.status===429?30:void 0;y!==void 0&&l.setHeader("Retry-After",String(y)),p(f.status,Ht(f,h.status.sessionId?`session ${h.status.sessionId}`:void 0),f.openaiType,f.anthropicType,f.code);return}}if(h instanceof W){p(502,g,"upstream_error","api_error");return}if(h instanceof pe){h.retryable&&l.setHeader("Retry-After","1"),p(502,g,"upstream_error","api_error",h.code);return}if(h instanceof Ne){l.setHeader("Retry-After",String(h.retryAfterSeconds)),p(h.status,g,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}p(500,g,"proxy_error","api_error","proxy_error");return}b&&(b.streamError=!0);let E=h instanceof pe?h.code:null;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",code:E}})}
|
|
61
|
+
|
|
62
|
+
`)),l.end()})}}function md(n){let{clients:e,apiKey:t}=n,r=li(Ci(n)),s=er(r,{clients:e,apiKey:t,statusOf:n.statusOf}),o=Wt(r,{resolver:ns(e,t)}),i=r.close.bind(r);return r.close=(a=>(s.close(),o(),i(a))),Ln(r,{clients:e,apiKey:t}),r}var ue=(n,e)=>Object.assign(new Error(e),{status:n});function Mi(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function Li(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}var Ui='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function $i(n,e,t,r){if(!n.supportsAudio)throw ue(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 n.supportsAudio(e)}catch(d){throw d instanceof q?ue(404,d.message):d}if(!s)throw ue(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(!n.openAudioOn)throw ue(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(d){throw d instanceof q?ue(404,d.message):d}if(o&&!n.openTurnsOn)throw ue(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let d;try{d=await n.transcriptStreamFor(e)}catch(l){throw l instanceof q?ue(404,l.message):l}if(d!=="stt")throw ue(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \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 ue(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Ui}`);if(r==="transcription"&&!o)throw ue(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 n.sessionHandle(e),a={audio:await n.openAudioOn(i,t)},u={clients:{createResponse:async d=>await n.createResponseOn(i,d)},voice:s,audioSession:a};return o&&(u.turns=d=>n.openTurnsOn(i,d)),r==="transcription"&&(u.intent="transcription"),e!==void 0&&(u.model=e),u}function ns(n,e){return{resolve:async(t,r)=>{if(e!==void 0){let s=t.headers.authorization,o=typeof s=="string"?s.trim():"",i=o.startsWith("Bearer ")?o.slice(7).trim():"";if(i===""||i!==e)throw ue(401,"invalid local proxy api key")}return $i(n,Mi(t),r,Li(t))}}}export{lt as a,Ln as b,Bi as c,ro as d,er as e,Xi as f,_s as g,Qi as h,Zi as i,ea as j,ta as k,na as l,ra as m,sa as n,oa as o,ia as p,ys as q,$n as r,aa as s,bs as t,ua as u,da as v,la as w,ge as x,ca as y,pa as z,ma as A,We as B,Vt as C,Wt as D,Mi as E,Li as F,$i as G,ns as H,et as I,tr as J,Nr as K,W as L,xu as M,qo as N,Iu as O,Au as P,an as Q,Uu as R,$u as S,Nu as T,Fu as U,qu as V,ki as W,Ci as X,md as Y};
|