@urun-sh/openai 0.6.17 → 0.6.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +0,0 @@
1
- import{c as y}from"./chunk-YSFSRI3D.js";y();y();var p=class extends Error{},ue=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function ce(o){if(typeof o!="string")return!1;let t=ue.exec(o);if(!t)return!1;let[,e,n,r,i,l,d]=t.map(Number);if(!Number.isFinite(Date.parse(o)))return!1;let a=new Date(Date.UTC(e,n-1,r,i,l,d));return a.getUTCFullYear()===e&&a.getUTCMonth()===n-1&&a.getUTCDate()===r&&a.getUTCHours()===i&&a.getUTCMinutes()===l&&a.getUTCSeconds()===d}function pe(o){if(o===null||typeof o!="object")return null;let t=o.shared;if(t==null)return null;if(typeof t!="object")throw new p(`catalog "shared" block is ${typeof t}, expected an object`);let{shared_org_id:e,endpoints:n,regions:r,compliance:i}=t;if(typeof e!="string"||e==="")throw new p(`catalog "shared" block has no shared_org_id: ${JSON.stringify(t)}`);if(!Array.isArray(n))throw new p(`catalog "shared" block endpoints is not an array: ${JSON.stringify(t)}`);let l=n.map((d,a)=>{if(d===null||typeof d!="object")throw new p(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(d)}`);let s=d;for(let c of["model_id","variant","app_slug","function"])if(typeof s[c]!="string"||s[c].length===0)throw new p(`catalog shared endpoints[${a}] (${JSON.stringify(s)}) has no valid "${c}"`);let u=(c,g)=>{if(s[c]!==void 0&&s[c]!==null&&!g)throw new p(`catalog shared endpoints[${a}] (${s.model_id}:${s.variant}) carries a malformed "${c}": ${JSON.stringify(s[c])}`)};u("ready",typeof s.ready=="boolean"),u("ready_runtimes",typeof s.ready_runtimes=="number"&&Number.isInteger(s.ready_runtimes)&&s.ready_runtimes>=0),u("ready_since",ce(s.ready_since));for(let c of["model_id","variant"]){let g=s[c];if(g.includes(":"))throw new p(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(g)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return u("output_free",typeof s.output_free=="boolean"),s});if(r!=null&&(!Array.isArray(r)||!r.every(d=>typeof d=="string"&&d.length>0)))throw new p(`catalog "shared" block regions is malformed: ${JSON.stringify(r)}`);if(i!=null){let d=i;if(typeof i!="object"||typeof d.zdr!="boolean"||typeof d.hipaa!="boolean")throw new p(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let a of Object.keys(d))if(a!=="zdr"&&a!=="hipaa")throw new p(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return l.length===0?null:{shared_org_id:e,endpoints:l,...r!=null?{regions:r}:{},...i!=null?{compliance:i}:{}}}function S(o){return[...o.endpoints].sort((t,e)=>t.model_id.localeCompare(e.model_id)||t.variant.localeCompare(e.variant))}function K(o,t,e){let n=(t??"").trim();if(n==="")return null;let r=n,i=e,l=n.lastIndexOf(":");l>0&&(r=n.slice(0,l),i=n.slice(l+1));let d=o.endpoints.filter(s=>s.model_id===r);if(d.length===0)return null;if(i!==void 0){let s=d.find(u=>u.variant===i);return s?{shared_org_id:o.shared_org_id,endpoint:s}:null}if(d.length===1)return{shared_org_id:o.shared_org_id,endpoint:d[0]};let a=d.filter(s=>s.compat_default===!0);if(a.length!==1)throw new p(`shared model "${r}" has ${a.length} compat_default rows (exactly one required) among variants ${d.map(s=>s.variant).join(", ")}`);return{shared_org_id:o.shared_org_id,endpoint:a[0]}}async function Ie(o){let t=o.fetchImpl??fetch,e=`${o.apiUrl.replace(/\/+$/,"")}/catalog`,n=await t(e,{headers:{Authorization:`Bearer ${o.apiKey}`,Accept:"application/json"}});if(!n.ok)throw new p(`catalog read failed: GET ${e} \u2192 ${n.status}`);return pe(await n.json())}y();function _(o){return o.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}y();var w=class extends Error{name="ModelPriceError"},E="per_million_input_tokens",N="per_million_output_tokens",z="model_id,variant,unit,price_usd,effective_at,expires_at",J={per_request:!0,per_minute:!0,per_output_unit:!0},ge=5e3;function fe(o,t){let e=typeof o=="number"?o:typeof o=="string"&&o.trim()!==""?Number(o):NaN;if(!Number.isFinite(e)||e<0)throw new w(`${t}: price_usd is not a non-negative number (${JSON.stringify(o)})`);return e}function H(o,t,e){let n=typeof o=="string"?Date.parse(o):NaN;if(!Number.isFinite(n))throw new w(`${t}: ${e} is not a parseable timestamp (${JSON.stringify(o)})`);return n}function he(o,t,e){return o===null?null:H(o,t,e)}function me(o,t){if(o===E)return"input";if(o===N)return"output";if(typeof o=="string"&&Object.hasOwn(J,o))return null;throw new w(`${t}: unit ${JSON.stringify(o)} is neither a per-token rate (${E} | ${N}) nor a known GPU-time unit (${Object.keys(J).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function we(o,t){let e=o.reduce((r,i)=>i.effective_at>r.effective_at?i:r,o[0]),n=o.find(r=>r.effective_at===e.effective_at&&r.usd!==e.usd);return n?{reason:`two ${t} rates are effective at the same instant (${e.usd} and ${n.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:e}}function D(o,t){return`${o}\0${t}`}function ye(o){if(!Array.isArray(o))throw new w(`model_prices read is not an array: ${JSON.stringify(o)}`);let t=[];for(let e=0;e<o.length;e++){let n=o[e],r=`model_prices[${e}]`;if(n===null||typeof n!="object"||Array.isArray(n))throw new w(`${r} is not an object: ${JSON.stringify(n)}`);let i=n;for(let s of z.split(","))if(!Object.hasOwn(i,s))throw new w(`${r} has no "${s}" column: ${JSON.stringify(i)}`);let l=me(i.unit,r);if(l===null)continue;let d=i.model_id;if(typeof d!="string"||d==="")throw new w(`${r} has no model_id (${JSON.stringify(i)})`);let a=i.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new w(`${r} has a non-string variant (${JSON.stringify(a)})`);t.push({model_id:d,variant:a,side:l,usd:fe(i.price_usd,r),effective_at:H(i.effective_at,r,"effective_at"),expires_at:he(i.expires_at,r,"expires_at")})}return t}function q(o,t=Date.now(),e){let n=new Map,r=new Map;for(let a of o){if(a.effective_at>t||a.expires_at!==null&&a.expires_at<=t)continue;let s=n.get(a.model_id);s||(s=new Map,n.set(a.model_id,s),r.set(a.model_id,new Map));let u=a.variant??"",c=s.get(u);c||(c={input:[],output:[]},s.set(u,c),r.get(a.model_id).set(u,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let i=[],l=[];for(let[a,s]of n){let u=s.get(""),c=(g,h,v)=>{let m=g&&g.length>0?g:u?.[h];if(!m||m.length===0)return null;let f=we(m,h);return"reason"in f?f:f.rate.usd===0?h==="output"&&v!==null&&e?.has(D(a,v))?f.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:f.rate};for(let[g,h]of r.get(a)){let v=s.get(g),m=c(v?.input,"input",h),f=c(v?.output,"output",h);if(m!==null&&"reason"in m){l.push({model_id:a,variant:h,reason:m.reason});continue}if(f!==null&&"reason"in f){l.push({model_id:a,variant:h,reason:f.reason});continue}m===null||f===null||i.push({model_id:a,variant:h,pricing:{input:m.usd,output:f.usd}})}}let d=(a,s)=>a.model_id.localeCompare(s.model_id)||(a.variant===null?1:0)-(s.variant===null?1:0)||(a.variant??"").localeCompare(s.variant??"");return{prices:i.sort(d),refusals:l.sort(d)}}function k(o,t,e){if(e.refusals.some(i=>i.model_id===o&&i.variant===t))return null;let n=e.prices.find(i=>i.model_id===o&&i.variant===t);if(n)return n.pricing;if(e.refusals.some(i=>i.model_id===o&&i.variant===null))return null;let r=e.prices.find(i=>i.model_id===o&&i.variant===null);return r?r.pricing:null}var C={prices:[],refusals:[]};async function Le(o){let t=o.fetchImpl??fetch,e=`${E},${N}`,n=await t(`${o.catalogUrl}/model_prices?select=${z}&unit=in.(${e})`,{headers:{apikey:o.anonKey,Authorization:`Bearer ${o.anonKey}`},signal:AbortSignal.timeout(ge)});if(!n.ok)throw new Error(`model_prices fetch failed: ${n.status}`);return ye(await n.json())}y();var _e={chat:!0,code:!0,agent:!0,vl:!0},G={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ve(o){let t=o.toLowerCase();return Object.hasOwn(G,t)?G[t]:null}var V={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Re(o,t){if(!o||o.length===0)return[];let e=[],n=[];for(let r of o){let i=Object.hasOwn(V,r)?V[r]:null;if(i===null){n.push(r);continue}e.some(d=>d.region===r)||e.push({country_code:i,region:r})}return n.length>0&&t(`urun openrouter doc: shared block region(s) ${n.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),e}var W={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Q={2:"Llama2",3:"Llama3"};function be(o){if(!o)return null;let t=o.split("@")[0],e=t.indexOf("/"),n=(e===-1?t:t.slice(e+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<n.length;r+=1){let i=n[r];if(Object.hasOwn(W,i))return W[i];let l=n[r+1];if(i==="llama"&&l!==void 0&&Object.hasOwn(Q,l))return Q[l];if(i==="phi"&&l!==void 0&&/^\d/.test(l))return"Phi"}return null}var Se=["context_length","max_model_len"];function $e(o){let t=Se.map(e=>o.engine_args?.[e]).filter(e=>typeof e=="number"&&Number.isFinite(e)&&e>0);return t.length===0?null:t.every(e=>e===t[0])?t[0]:null}function T(o){let t=o.map($e),e=t[0];return e==null?null:t.every(n=>n===e)?e:null}function ke(o){let t=o.engine_args?.reasoning_parser;return t==null||t===""?!1:typeof t=="string"?!0:null}function F(o){if(o.length===0)return null;let t=o.map(ke),e=t[0];return e==null?null:t.every(n=>n===e)?e:null}function Ce(o,t){let e=t.filter(r=>_(`${r.model_id}-${r.variant}`)===o);if(e.length>0)return M(e);let n=t.filter(r=>_(r.model_id)===o);return n.length>0?M(n):null}function M(o){let t=o[0];return o.every(n=>n.model_id===t.model_id&&n.variant===t.variant)?{row:o.length===1?t:Pe(o),matches:o}:null}function Pe(o){let t=o[0],e=n=>o.every(r=>(r[n]??void 0)===(t[n]??void 0))?t[n]:void 0;return{model_id:t.model_id,variant:t.variant,gpu_spec:e("gpu_spec"),engine:e("engine"),task:e("task"),description:e("description"),size_gb:e("size_gb"),hf_repo:e("hf_repo"),updated_at:e("updated_at")}}function Y(o){let t=o.updated_at?Date.parse(o.updated_at):NaN;return Number.isFinite(t)?Math.floor(t/1e3):0}function A(o,t,e){let n=Ce(o,t);if(!n)return{id:o,object:"model",created:0,owned_by:"urun"};let{row:r,matches:i}=n,l=T(i),d=k(r.model_id,r.variant,e),a=ee(r,i),s=F(i);return{id:o,object:"model",created:Y(r),owned_by:"urun",name:`${r.model_id}:${r.variant}`,...r.description?{description:r.description}:{},...r.task?{task:r.task}:{},...r.engine?{engine:r.engine}:{},...r.gpu_spec?{gpu_spec:r.gpu_spec}:{},...l!==null?{context_length:l}:{},...d!==null?{pricing:d}:{},...a.published.length>0?{voices:[...a.published]}:{},...s!==null?{capabilities:{reasoning:s}}:{}}}var xe=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function ee(o,t){if((o.task??void 0)!=="tts")return{published:[],defect:null};let e=t.map(i=>i.engine_args?.voices),n=e[0];if(Array.isArray(n)&&n.length>0&&n.every(i=>typeof i=="string")&&e.every(i=>Array.isArray(i)&&i.length===n.length&&i.every((l,d)=>l===n[d])))return{published:[...n],defect:null};let r=e.some(i=>i!=null)?`the catalog's engine_args.voices for ${o.model_id}:${o.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return o.model_id==="qwen3-tts-customvoice"?{published:[...xe],defect:r}:{published:[],defect:r}}function L(o){let t=o.length>0?M(o):null;return t===null?{published:[],defect:null}:ee(t.row,t.matches)}function X(o){let t=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(o));if(!t)throw new Error(`unrenderable per-token price: ${String(o)}`);let[,e="",n="",r=""]=t,i=e+n,l=e.length-6+(r===""?0:Number(r));return(l<=0?`0.${"0".repeat(-l)}${i}`:`${i.slice(0,l)}.${i.slice(l).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Z(o){return{input:[{type:"prompt",unit:"token",cost_usd:X(o.input)}],output:[{type:"completion",unit:"token",cost_usd:X(o.output)}]}}function Oe(o,t,e,n){if(t.length===0)return null;let r=M(t);if(!r)return null;let{row:i,matches:l}=r;if(!i.task||_e[i.task]!==!0)return null;let d=T(l),a=k(i.model_id,i.variant,e),s=be(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:Y(i),quantization:ve(i.variant),...s!==null?{tokenizer:s}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:o.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...a?{pricing:Z(a).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...a?{pricing:Z(a).output}:{}}],...n.datacenters.length>0?{datacenters:n.datacenters}:{},...n.compliance?{compliance:n.compliance}:{}}}function te(o,t,e,n){let r=n??(s=>console.warn(s.trimEnd())),i=o?S(o):[];if(i.length>0){let s=i.filter(u=>u.ready===void 0);if(s.length===i.length)r("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(s.length>0){let u=s.map(c=>`${c.model_id}:${c.variant}`).join(", ");r(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${u} carry no ready field and are declared not ready`)}}let l={datacenters:Re(o?.regions,r),compliance:o?.compliance??null},d=[],a=new Set;for(let s of i){let u=`${s.model_id}:${s.variant}`;if(a.has(u))continue;a.add(u);let c=Oe(s,t.filter(g=>g.model_id===s.model_id&&g.variant===s.variant),e,l);c&&d.push(c)}return{data:d}}var Xe="https://api.urun.sh/v1",$=class extends Error{},P=class extends Error{},B="urs1.";function ne(o,t){return B+Buffer.from(JSON.stringify([o,t]),"utf8").toString("base64url")}function Me(o){if(!o.startsWith(B))return null;try{let t=JSON.parse(Buffer.from(o.slice(B.length),"base64url").toString("utf8"));if(Array.isArray(t)&&typeof t[0]=="string"&&typeof t[1]=="string")return{app:t[0],key:t[1]}}catch{}return null}async function Ze(o){let t=o.fetchImpl??fetch,e=`${o.apiUrl.replace(/\/+$/,"")}/apps`,n=await t(e,{headers:{Authorization:`Bearer ${o.apiKey}`,Accept:"application/json"}});if(!n.ok)throw new Error(`org apps listing failed: GET ${e} \u2192 ${n.status}`);let r=await n.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${e})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${e} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}function oe(o){if(o.length===0)return[];if(!o.every(e=>(e.task??void 0)==="image"))return[];let t=Ae(o);return t===null?[]:[t]}function U(o,t,e,n,r){if(!r)throw new p(`shared model "${o}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(t===void 0||e===void 0)throw new p(`shared model "${o}" resolved without a catalog id + variant to join on`);let i=n.filter(l=>l.model_id===t&&l.variant===e);if(i.length===0)throw new p(`shared model "${o}" names endpoint ${t}:${e} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function re(o,t){if(!t.every(r=>(r.task??void 0)==="image"))return[];let e=t.map(r=>r.engine_args?.expects_image),n=e[0];if(typeof n!="boolean"||!e.every(r=>r===n))throw new p(`shared image model "${o}" does not vouch an explicit image mode: its ${t.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(e)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[n===!1?"generation":"edit"]}var de="shared:",ie="speech:";function j(o){return o.sharedApp?de+o.appSlug:o.appSlug}function se(o){return typeof o.modelId=="string"&&typeof o.variant=="string"?{kind:"catalog",model_id:o.modelId,variant:o.variant}:{kind:"not-a-catalog-model",model:o.appSlug}}function b(o,t){let e=t.filter(i=>_(`${i.model_id}-${i.variant}`)===o);if(e.length>0)return e;let n=t.filter(i=>_(i.model_id)===o);return new Set(n.map(i=>i.variant)).size===1?n:[]}function Te(o){let t=o.engine_args?.expects_image;return t==null?"edit":t===!1?"generation":t===!0?"edit":null}function Ae(o){let t=o.map(Te),e=t[0];return e!=null&&t.every(n=>n===e)?e:null}var ae={stt:"stt",tts:"tts"};function R(o){if(o.length===0)return null;let t=o[0].task??void 0;return t===void 0||ae[t]===void 0?null:o.every(e=>(e.task??void 0)===t)?ae[t]:null}var I=6e4,le=class{constructor(t){this.opts=t}opts;pool=new Map;appsCache=null;rowsCache=null;seed(t,e){this.pool.set(t,Promise.resolve(e))}async deployedApps(){if(!this.opts.listApps)return[];let t=this.opts.appsTtlMs??I;if(this.appsCache&&Date.now()-this.appsCache.at<t)return this.appsCache.apps;let e=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:e},e}async sharedBlock(){if(!this.opts.shared)return null;let t=this.opts.appsTtlMs??I;if(this.sharedCache&&Date.now()-this.sharedCache.at<t)return this.sharedCache.block;let e=await this.opts.shared();return this.sharedCache={at:Date.now(),block:e},e}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let t=this.opts.appsTtlMs??I;if(this.rowsCache&&Date.now()-this.rowsCache.at<t)return this.rowsCache.rows;let e=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:e},e}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let t=this.opts.appsTtlMs??I;if(this.pricesCache&&Date.now()-this.pricesCache.at<t)return this.pricesCache.rows;let e=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:e},e}async pricesForListing(t){let e;try{e=await this.priceRows()}catch(r){if(r instanceof w)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
2
- `),C}let n=q(e,Date.now(),t);for(let r of n.refusals)this.warn(`urun /v1/models: refusing to price ${r.model_id}:${r.variant??"*"} \u2014 ${r.reason}
3
- `);return n}outputFreeKeys(t){let e=new Set;if(!t)return e;for(let n of t.endpoints)n.output_free===!0&&e.add(D(n.model_id,n.variant));return e}warn(t){(this.opts.warn??(n=>console.warn(n.trimEnd())))(t)}servable(t){return t.filter(e=>e.serves==="openai"&&e.deployment_status==="active").map(e=>e.app_slug)}async availableIds(){let t=this.opts.defaultApp,e=new Set(t===null?[]:[t]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))e.add(r);for(let r of this.pool.keys())r.startsWith(de)||r.startsWith(ie)||e.add(r);let n=[...e].filter(r=>r!==t).sort();return t===null?n:[t,...n]}async noDefaultApp(t){let e=await this.availableIds(),n=e.length>0?e.join(", "):"(none deployed)";throw new $(t===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${n}`:`model "${t}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${n}`)}async resolveTarget(t){let e=(t??"").trim(),n=this.opts.defaultApp;if(!e||e==="urun")return n===null?this.noDefaultApp(e):{appSlug:n};let r=_(e);if(r===n)return{appSlug:n};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let i=await this.deployedApps(),l=this.servable(i);if(l.includes(r))return{appSlug:r};let d=l.filter(s=>s.startsWith(`${r}-`));if(d.length===1)return{appSlug:d[0]};if(d.length>1)throw new $(`model "${e}" is ambiguous across deployed apps ${d.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let a=i.find(s=>s.app_slug===r||s.app_slug.startsWith(`${r}-`));if(a)throw new $(`model "${e}" maps to app "${a.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${e}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let i=await this.sharedBlock();if(i){let l=K(i,e);if(l)return{appSlug:l.endpoint.app_slug,fnName:l.endpoint.function,sharedApp:!0,modelId:l.endpoint.model_id,variant:l.endpoint.variant,sharedOrgId:i.shared_org_id}}}if(this.opts.listCatalog){let l=(await this.opts.listCatalog()).find(d=>e===d.model_id||e===`${d.model_id}:${d.variant}`||r===_(d.model_id)||r===_(`${d.model_id}-${d.variant}`));if(l)throw new $(`model "${e}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${l.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return n===null?this.noDefaultApp(e):{appSlug:n}}async catalogIdentityFor(t){let e=se(await this.resolveTarget(t));return e.kind==="catalog"?{model_id:e.model_id,variant:e.variant}:null}async servingAppSlugFor(t){return(await this.resolveTarget(t)).appSlug}async targetFor(t){return this.resolveTarget(t)}async resolveApp(t){return j(await this.resolveTarget(t))}async sessionFor(t){let e=await this.resolveTarget(t);return this.acquire(e,j(e))}async speechSessionFor(t){let e=await this.resolveTarget(t);return this.acquire(e,ie+j(e))}async acquire(t,e){let n=this.pool.get(e);return n||(n=Promise.resolve(this.opts.openSession(t,e)),this.pool.set(e,n),n.catch(()=>this.pool.delete(e))),{app:e,entry:await n,identity:se(t)}}keyOf(t){let e=this.opts.sessionKey;if(!e)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let n=e(t);if(typeof n!="string"||n.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return n}async handleFor(t){let{app:e,entry:n}=await this.sessionFor(t);return{app:e,handle:ne(e,this.keyOf(n))}}async speechHandleFor(t){let{app:e,entry:n}=await this.speechSessionFor(t);return{app:e,handle:ne(e,this.keyOf(n))}}async sessionForHandle(t){let e=Me(t);if(!e)throw new P(`malformed session handle ${JSON.stringify(t)} \u2014 not issued by this proxy`);let{app:n,key:r}=e,i=this.pool.get(n),l=i?await i.then(d=>d,()=>null):null;if(l===null)throw new P(`the session behind this handle (app "${n}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(l)!==r)throw new P(`the session behind this handle (app "${n}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:n,entry:l}}async evict(t,e){let n=this.pool.get(t);!n||await n.then(i=>i,()=>null)!==e||this.pool.get(t)!==n||(this.pool.delete(t),await this.opts.closeSession(e).catch(()=>{}))}async modelList(){let t=this.opts.sharedOnlyListing?[]:await this.availableIds(),e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows().then(s=>({ok:!0,rows:s}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(e))]),i=n.rows,l=n.ok?r:C;n.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
4
- `);let a=(e?S(e):[]).map(s=>{let u={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`};s.gpu_spec&&(u.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(u.warm=s.warm);let c=i.filter(f=>f.model_id===s.model_id&&f.variant===s.variant),g=T(c);g!==null&&(u.context_length=g);let h=F(c);h!==null&&(u.capabilities={reasoning:h});let v=k(s.model_id,s.variant,l);v!==null&&(u.pricing=v);let m=L(c);return m.published.length>0&&(u.voices=[...m.published]),u});return{object:"list",data:this.opts.sharedOnlyListing?a:[...t.map(s=>A(s,i,l)),...a]}}async openRouterModels(){let t=await this.sharedBlock(),[e,n]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(t))]);return te(t,e,n,r=>this.warn(r))}async supportsImages(t,e){let n=await this.resolveTarget(t),r=await this.catalogRows();if(n.sharedApp){let i=U(String(t),n.modelId,n.variant,r,this.opts.listCatalog!==null);return re(`${n.modelId}:${n.variant}`,i).includes(e)}return oe(b(n.appSlug,r)).includes(e)}async supportsAudio(t){let e=await this.resolveTarget(t),n=await this.catalogRows();return e.sharedApp?R(n.filter(r=>r.model_id===e.modelId&&r.variant===e.variant))!==null:R(b(e.appSlug,n))!==null}async supportsSpeech(t){let e=await this.resolveTarget(t),n=await this.catalogRows();return e.sharedApp?R(n.filter(r=>r.model_id===e.modelId&&r.variant===e.variant))==="tts":R(b(e.appSlug,n))==="tts"}async supportsTranscription(t){let e=await this.resolveTarget(t),n=await this.catalogRows();return e.sharedApp?R(n.filter(r=>r.model_id===e.modelId&&r.variant===e.variant))==="stt":R(b(e.appSlug,n))==="stt"}async speechVoices(t){let e=await this.resolveTarget(t),n=await this.catalogRows(),r=e.sharedApp?n.filter(i=>i.model_id===e.modelId&&i.variant===e.variant):b(e.appSlug,n);return L(r)}async imageModelList(){let t=await this.catalogRows(),e=C,n=[];for(let i of await this.availableIds()){let l=oe(b(i,t));l.length!==0&&n.push({...A(i,t,e),image_modes:l})}let r=await this.sharedBlock();if(r)for(let i of S(r)){let l=U(`${i.model_id}:${i.variant}`,i.model_id,i.variant,t,this.opts.listCatalog!==null),d=re(`${i.model_id}:${i.variant}`,l);if(d.length===0)continue;let a={id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun",name:`${i.model_id}:${i.variant}`,image_modes:d};i.gpu_spec&&(a.gpu_spec=i.gpu_spec),typeof i.warm=="number"&&(a.warm=i.warm),n.push(a)}return{object:"list",data:n}}async speechToTextModelList(){let t=await this.catalogRows(),e=C,n=[];for(let i of await this.availableIds())R(b(i,t))==="stt"&&n.push(A(i,t,e));let r=await this.sharedBlock();if(r)for(let i of S(r)){let l=U(`${i.model_id}:${i.variant}`,i.model_id,i.variant,t,this.opts.listCatalog!==null);if(R(l)!=="stt")continue;let d={id:`${i.model_id}:${i.variant}`,object:"model",created:0,owned_by:"urun",name:`${i.model_id}:${i.variant}`};i.gpu_spec&&(d.gpu_spec=i.gpu_spec),typeof i.warm=="number"&&(d.warm=i.warm),n.push(d)}return{object:"list",data:n}}async closeAll(){let t=[...this.pool.values()],e=[];if(await Promise.all(t.map(async n=>{try{await this.opts.closeSession(await n)}catch(r){e.push(String(r instanceof Error?r.message:r))}})),e.length>0)throw new Error(`failed to close ${e.length} pooled session(s): ${e.join("; ")}`)}};export{Ie as a,Le as b,Xe as c,$ as d,P as e,Ze as f,ie as g,j as h,se as i,le as j};
@@ -1,62 +0,0 @@
1
- import{c as gn,d as L,e as pe,i as Mt}from"./chunk-TMQJY56F.js";import{a as hn,c as yn,d as be,e as st,f as Y,g as _n,h as wn,i as vn,j as bn,k as xn,l as kn,m as Rn,n as Sn,r as En,t as In,u as An,v as On,w as Tn,x as Pn}from"./chunk-3JWYIKHM.js";import{a as Ct}from"./chunk-6M5JK4YC.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{randomUUID as Yr}from"crypto";import{WebSocketServer as Xr}from"ws";var Qr=256,it=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Qr;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Zr="local",De=t=>t.slice(0,120),at=class{constructor(e,n,r){this.ws=e;this.call=n;this.registry=r;this.clients=n.clients,this.scope=n.scope,e.on("message",o=>this.onMessage(o)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof L){this.ws.close(yn,De(e.message));return}if(e instanceof pe){this.ws.close(st,De(e.message));return}if(e instanceof Y){this.ws.close(e.closeCode,De(e.message));return}this.ws.close(be,De(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=_n(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new Y(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=Sn(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=In(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:En);return}this.transcript.push(...An(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new Y("setup may only be sent once, as the first client message");let n=xn(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new Y("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",st);if(s.model!==n.model)throw new Y(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new Y("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new Y(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,st);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(bn(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[wn]=vn(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new Y("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new Y("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",be);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Tn(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new Y("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new Y("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",be);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new Y(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new Y("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new Y("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=Yr();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(kn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let n=null;try{n=await this.clients.sessionHandle(this.config.model)}catch{}if(n!==null&&n!==this.proxyHandle){this.proxyHandle=n,this.unsubscribeEnd=await this.clients.onSessionEnd(n,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(Rn(e.timeLeftMs)),this.ws.close(be,De(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new Y(`upstream error: ${JSON.stringify(d)}`,be);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=On(d);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new Y("upstream produced no response.completed event",be);let{messages:i,assistantItems:a}=Pn(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},xe=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function eo(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new xe(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new xe(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new xe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function Cn(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Xr({noServer:!0}),o=new it;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===hn&&(a.on("error",()=>{}),(async()=>{let l=eo(i,d,n),c;if(e.authenticate)c=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new xe(401,"invalid local proxy api key");c={clients:e.clients,scope:Zr}}r.handleUpgrade(i,a,u,v=>{new at(v,c,o)})})().catch(l=>{let c=502;(l instanceof xe||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 s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}function Hi(t,e,n=new it){new at(t,e,n)}A();import no from"os";import ro from"path";import{fileURLToPath as oo}from"url";import{format as so}from"util";var Mn="0.6.17";var Ln=4141,io=Mn,Zi={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function ao(t,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${t}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${t}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function ea(t,e,n){let r={...t,...ao(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,delete r.URUN_SESSION_TOKEN_SECRET,r}function ta(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",u=s.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...d]}function na(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ra(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function oa(t,e,n){let r=(t.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=oo(new URL("../pi-extension/standalone.cjs",e));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function Un(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${t}`);return e}function sa(t){if(t[0]!=="--port")return null;let e=Un(t[1]);return t.splice(0,2),e}function ia(t){let e=t.indexOf("--port");if(e===-1)return Ln;let n=Un(t[e+1]);return t.splice(e,2),n}function aa(t){if(t===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return t}function $t(t,e){let n=(t[e]??"").trim();if(!n)throw new Error(`${e} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function ua(t){let e=uo($t(t,"URUN_BASE_URL")),n=$t(t,"URUN_ORG_ID"),r=$t(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?$n(s,"URUN_API_URL"):gn,a=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"jwt",jwt:u}};let d=(t.URUN_API_KEY??"").trim();if(d){let l=(t.URUN_GATEWAY_URL??"").trim(),c=l?$n(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:c}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function uo(t,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return t}function $n(t,e="URUN_GATEWAY_URL"){let n=new URL(t),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}function da(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:io}}function lo(t,e){return t.app===e.app&&t.org===e.org&&t.fn===e.fn&&t.base_url===e.base_url&&t.proxy_version===e.proxy_version}var co=250;async function po(t,e=co){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:a,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:o,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var Nn=2e3;async function mo(t,e=Nn){try{let n=await fetch(`http://127.0.0.1:${t}/v1/models`,{signal:AbortSignal.timeout(e)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function la(t,e,n=Ln,r=Nn){if(t!=null)return{mode:"spawn",port:t};let o=await po(n);if(o!==null&&lo(o,e)){let s=await mo(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function ca(t,e=no.homedir()){return ro.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Lt=["log","info","warn","error","debug","trace"];function pa(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(a,...u)=>t.write(a,...u);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Lt.map(a=>[a,n[a]]));for(let a of Lt)n[a]=(...u)=>{t.write(`${so(...u)}
6
- `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let a of Lt)n[a]=i[a]}}var fo=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Bn(t){let e=t?.code;return typeof e=="string"&&fo.has(e)}function ye(t,e){try{return t.write(e),!0}catch(n){if(Bn(n))return!1;throw n}}function ma(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Bn(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
7
- `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function fa(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
8
- `)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
9
- `)}catch(o){try{t.appendSync(t.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
10
- `)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function ga(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}A();import{SessionFailedError as wo}from"@urun-sh/core";A();import{randomUUID as go}from"crypto";function R(t){return`${t}_${go().replace(/-/g,"").slice(0,24)}`}var ut=4*1024*1024,Ut=8*1024*1024,dt=512,lt=20*1024*1024;function G(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Pe(t,e){return{type:"server_error",code:t,message:e}}function U(t){return{type:"error",event_id:R("event"),error:t}}function Nt(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var I=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},ho={model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},yo={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},_o={format:!0,voice:!0,speed:!0};function Fn(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new I(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function je(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new I("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in ho));if(o.length>0)throw new I(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new I("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new I("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new I("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new I(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new I('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new I("voice must be a string or null","voice");if(!n.voice)throw new I("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new I(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new I("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new I(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new I("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new I("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new I("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new I("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new I(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new I("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new I("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new I(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new I("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new I("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in yo))throw new I(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&Fn(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=je({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=je({turn_detection:d.turn_detection},s,n);s.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new I("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in _o))throw new I(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&Fn(d.format,"audio.output.format"),d.speed!==void 0)throw new I("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new I("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new I("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function ct(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Bt(t,e){let n=t;if(!n||typeof n!="object")throw new I("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new I("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:R("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new I('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new I("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new I("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new I(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new I("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new I("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new I(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:R("item"),type:"message",role:r,content:o}}throw new I(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function Ft(t){let e=[],n=!1;for(let r of t){if(r.type==="function_call"){e.push({type:"function_call",call_id:r.callId,name:r.name,arguments:r.arguments??"{}"});continue}if(r.type==="function_call_output"){e.push({type:"function_call_output",call_id:r.callId,output:r.output});continue}let o=[];for(let s of r.content??[]){if(s.type==="input_text"||s.type==="output_text"){o.push({type:s.type,text:s.text});continue}if(s.type==="input_audio"){let i=s.transcript;if(typeof i=="string"&&i.trim().length>0){o.push({type:"input_text",text:i});continue}n=!0;continue}}e.push({role:r.role,content:o})}return{input:e,sawAudioOnlyItem:n}}var vo=1001,bo=1011,qn=t=>t.slice(0,120),xo=/^[A-Za-z0-9+/=]*$/,ko=2;function Ro(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ko)return!1;return!0}var He=class{id=R("conn");ws;binding;onClosed;config=Nt();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:R("event"),session:ct(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(U(Pe("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:R("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=R("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(G("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>ut){this.fail(G("frame_too_large",`frame exceeds the ${ut}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(G("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(G("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(U({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Pe(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=je(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:R("event"),session:ct(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Bt(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(U(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:R("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(U(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:R("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(U(G("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:R("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(U(G("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!xo.test(e.audio)){this.send(U(G("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>lt){this.send(U(G("buffer_full",`uncommitted input audio exceeds the ${lt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(U(G("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(U(G("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(U(G("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(U(G("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(U({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(U(G("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(S=>S!=="text"&&S!=="audio")){this.send(U(G("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(U(G("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=R("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=Ft(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,v=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,w={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 S of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(S);this.inFlight=(async()=>{let S=[],k=E=>{this.responseFlushed?this.send(E):S.push(E)},m=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:R("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(o,"in_progress")});for(let E of S)this.send(E);S.length=0,this.responseFlushed=!0}},g={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},h=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(w,r)}catch(f){this.upstreamTurnFault(f,o);return}try{for await(let f of E){if(this.cancelled)break;let y=f;if(y.type==="error"){let b=this.upstreamErrorBody(y);this.responseFlushed?this.send(U(b)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(o,b)});return}if(y.type==="response.output_text.delta"&&typeof y.delta=="string"){m(),g.messageOpen||(this.beginMessageItem(o,g.nextOutputIndex++),g.messageOpen=!0),k({type:"response.output_text.delta",event_id:R("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:y.delta}),g.messageText+=y.delta;continue}if(y.type==="response.function_call_arguments.delta"){m();let b=typeof y.delta=="string"?y.delta:"",M=typeof y.call_id=="string"&&y.call_id.length>0?y.call_id:`${o}_fc_${g.nextOutputIndex}`,_=g.tools.get(M);if(!_){let x=typeof y.name=="string"&&y.name.length>0?y.name:void 0;_={outputIndex:g.nextOutputIndex++,name:x,args:""},g.tools.set(M,_),k({type:"response.output_item.added",event_id:R("event"),response_id:o,output_index:_.outputIndex,item:{id:M,object:"realtime.item",type:"function_call",call_id:M,name:x??"",arguments:"",status:"in_progress"}})}typeof y.name=="string"&&y.name.length>0&&(_.name=y.name),_.args+=b,k({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:M,response_id:o,output_index:_.outputIndex,call_id:M,name:_.name??"",delta:b});continue}if(y.type==="response.completed"){h=y.response??null;continue}}}catch(f){this.upstreamTurnFault(f,o);return}if(this.cancelled)return;this.closeOpenItems(o,g,s),m(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(o,s,h)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Ro(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(U({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:R("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:R("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Pe("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof pe){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof wo&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Pe(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(U(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(U(G("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:R("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>dt&&(this.items.shift(),this.send(U({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${dt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Ut){this.ws.close(vo,qn("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(U(e)),this.ws.close(bo,qn(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>Dn(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Dn(this.id,e)}}},qt=[];function Dn(t,e){qt.push({id:t,reason:e}),qt.length>256&&qt.shift()}A();import{SessionFailedError as Ao}from"@urun-sh/core";A();import{COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as So}from"@urun-sh/core";var Eo={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},Io={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session"};function Dt(t,e){let n=Io[t.code];return e?`${n} (${e})`:n}function pt(t){if(t==null)return null;let e=Eo[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function mt(t){if(t.kind==="create-failed")return pt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=So;return pt(e?"cold_start_exceeded":"queue_timeout")}import{WebSocketServer as Oo}from"ws";var Ht="/v1/realtime",To=t=>t.slice(0,120);function Po(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
11
- Connection: close\r
12
- Content-Type: text/plain\r
13
- \r
14
- ${To(n)}\r
15
- `),t.destroy()}function Co(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
16
- `}function Mo(t){ye(process.stdout,t)}function $o(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function jt(t){return t.audioSession?.audio.sessionId??void 0}function Gt(t,e){let n=new Oo({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Ht)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=R("rtup"),d=$o(o),l=f=>{(e.log??Mo)(Co(f))};l({stage:"accept",conn:u,model:d}),s.resume();let c=new AbortController,v=null,p=f=>{v??=f,c.abort(new Error(v))},w=()=>p("client socket closed"),S=()=>p("client socket closed (half-close)"),k=f=>p(`client socket error: ${f.message}`);s.once("close",w),s.once("end",S),s.once("error",k);let m=()=>{s.removeListener("close",w),s.removeListener("end",S),s.removeListener("error",k)},g=f=>{l({stage:"close",conn:u,model:d,...f})},h=f=>{let y=f,b=y.session!=null&&typeof y.session.sendResponseCreate=="function",M=y.clients!=null&&typeof y.clients.createResponse=="function";if(!b&&!M)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((_,x)=>{n.handleUpgrade(o,s,i,P=>{try{new He({ws:P,binding:f,onClosed:(N,z)=>{g({while:"live",reason:z.reason})}}),l({stage:"admit",conn:u,model:d,...jt(f)===void 0?{}:{session:jt(f)}}),_()}catch(N){x(N)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async f=>{if(c.signal.aborted){m();let y=jt(f);try{await f.release?.()}catch(b){g({while:"queued",...y===void 0?{}:{session:y},reason:v??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}g({while:"queued",...y===void 0?{}:{session:y},reason:v??"client socket closed",released:!0}),s.destroy();return}m(),await h(f)}).catch(f=>{let y=f instanceof Ao?mt(f):null,b=null;if(f!==null&&typeof f=="object"&&"status"in f){let x=f.status;typeof x=="number"&&(b=x)}let M=b??y?.status??502,_=f instanceof Error?f.message:String(f);g({while:"queued",...c.signal.aborted?{reason:v??"client socket closed"}:{reason:_,status:M}}),s.destroyed||Po(s,M,_)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}A();A();A();import{createServer as fi}from"http";A();import{WebSocketServer as Wo,WebSocket as Ke}from"ws";A();A();import{randomUUID as Lo}from"crypto";var jn="Inference-Id";function Ge(){return Lo()}function Jt(t){return t==="/v1"||t.startsWith("/v1/")}function Hn(t,e){if(!Jt(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function Je(t){return`resp_${t}`}function Gn(t){return`chatcmpl-${t}`}function Jn(t){return`msg_${t}`}function oe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Vn(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function Wn(t){return`${JSON.stringify(t)}
17
- `}var Uo=256,No=128;function te(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,No)}var ke=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Uo?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Bo=256;function Fo(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Re=class extends Error{},Ce=class{conversations=new Map;thread(e,n){let r=Fo(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Re(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=Bo)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Kn=new WeakMap;function Ve(t){let e=Kn.get(t);return e||(e=new Ce,Kn.set(t,e)),e}function Me(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ae(t){return t.find(e=>e.type==="response.completed")?.response??null}function $e(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var _e=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},qo=["<tool_call>","<function="];function Do(t){return qo.find(e=>t.includes(e))}function Se(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Ee(t,e,n){if(!(!t||e>0))return Do(n)}function Le(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function jo(t){let e=t?.output;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r===null||typeof r!="object")continue;let o=r;o.type==="message"?n.push({role:"assistant",content:o.content??""}):o.type==="function_call"&&n.push({type:"function_call",call_id:o.call_id,name:o.name,arguments:o.arguments})}return n}function Vt(t,e){let n=jo(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var se=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ue(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Re?new se(n.message,"previous_response_not_found",400,"previous_response_id"):new se(String(n instanceof Error?n.message:n),"invalid_input")}}function zn(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Wt(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new se("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...zn(e)!==void 0?{response_format:zn(e)}:{}},o)}async function We(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ue(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=te(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,v=await Wt(n,e,s,!0,c?oe(c):void 0);return{responseId:i,events:Vo({events:v,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function Ho(t,e){let n=[...t].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?Jo(o[i++],u):u),...Go(r,n)]}function Go(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let l=d;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!u.has(o(l)):!0})}function Jo(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*Vo(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,l=[],c=O=>O.response&&typeof O.response=="object"?{...O,response:{...O.response,id:r}}:O,v=`item_${r.slice(5)}`,p=!1,w=!1,S=0;function*k(){p||(p=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let m=[],g=(O,$)=>{m.push({output_index:O,item:$})},h=!1,E=0,f="",y=0,b="";function*M(){if(!h)return;h=!1,yield{type:"response.reasoning_text.done",item_id:f,output_index:E,content_index:0,text:b};let O={id:f,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:E,item:O},g(E,O),b=""}let _=!1,x=0,P="",N=0,z="",ee="";function*ie(O){if(!_)return;_=!1,yield{type:"response.output_text.done",item_id:P,output_index:x,content_index:0,text:z},yield{type:"response.content_part.done",item_id:P,output_index:x,content_index:0,part:{type:"output_text",text:z}};let $={id:P,type:"message",role:"assistant",status:O,content:[{type:"output_text",text:z}]};yield{type:"response.output_item.done",output_index:x,item:$},g(x,$),z=""}let ge=new _e,q=null,D=-1;function*Q(O){if(!q)return;let $=q;q=null,yield{type:"response.function_call_arguments.done",item_id:$.fcId,output_index:$.outputIndex,arguments:$.args};let W={id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:$.args,status:O};yield{type:"response.output_item.done",output_index:$.outputIndex,item:W},g($.outputIndex,W)}let ve=!1;for await(let O of d.track(e,o,t.turn)){l.push(O);let $=String(O.type??"");if($==="response.created"||$==="response.in_progress"){p=!0,yield c(O);continue}if($==="response.output_item.added"){w=!0,yield c(O);continue}if($==="response.reasoning_text.delta"&&!w){yield*k(),h||(h=!0,E=S++,y+=1,f=y===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${y}`,yield{type:"response.output_item.added",output_index:E,item:{id:f,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(O.delta??""),yield{type:"response.reasoning_text.delta",item_id:f,output_index:E,content_index:0,delta:O.delta};continue}if($==="response.output_text.delta"&&!w){yield*k(),yield*M(),_||(_=!0,x=S++,N+=1,P=N===1?v:`${v}_${N}`,yield{type:"response.output_item.added",output_index:x,item:{id:P,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:P,output_index:x,content_index:0,part:{type:"output_text",text:""}}),z+=String(O.delta??""),ee+=String(O.delta??""),yield{type:$,item_id:P,output_index:x,content_index:0,delta:O.delta};continue}let W=w?null:$e(O);if(W){if(yield*k(),yield*M(),yield*ie("completed"),ge.add(W),W.tool_index!==D){yield*Q("completed"),D=W.tool_index;let ce=S++;q={fcId:`fc_${r.slice(5)}_${W.tool_index}`,outputIndex:ce,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:ce,item:{id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:"",status:"in_progress"}}}q&&(W.call_id&&(q.callId=W.call_id),W.name&&(q.name=W.name),q.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:q.fcId,output_index:q.outputIndex,delta:W.delta});continue}if($==="response.completed"&&!w){let ce=Me(O.response),B=Ee(s,ge.size+ce.length,ee);if(B){ve=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Se(o,B)}};break}if(yield*M(),yield*ie("completed"),yield*Q("completed"),ge.size===0)for(let he of ce){let Te=S++,ot=he.id??he.call_id??`fc_${Te}`,Pt=he.arguments??"",mn={id:ot,type:"function_call",call_id:he.call_id??ot,name:he.name??""};yield{type:"response.output_item.added",output_index:Te,item:{...mn,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:ot,output_index:Te,delta:Pt},yield{type:"response.function_call_arguments.done",item_id:ot,output_index:Te,arguments:Pt};let fn={...mn,arguments:Pt,status:"completed"};yield{type:"response.output_item.done",output_index:Te,item:fn},g(Te,fn)}let Z=Ho(m,O.response);yield Z.length>0?c({...O,response:{...O.response,output:Z}}):c(O);continue}yield c(O)}if(yield*M(),yield*ie("incomplete"),yield*Q("incomplete"),i&&!ve){let O=ae(l);u.remember(r,n,Vt(O,Le(l,O)),a)}}var Ko="/v1/responses",zo=64*1024*1024,Yo=8*1024*1024,Xo=16,Yn=32,Xn=3600*1e3,Qo=/^[A-Za-z0-9._-]{1,256}$/;function ne(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Zo=ne(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Yt(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function es(t){for(;t.bufferedAmount>Yo&&t.readyState===Ke.OPEN;){let{promise:e,resolve:n}=Yt();setTimeout(n,5),await e}}var Kt=class extends Ce{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Re))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},zt=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Kt(Ve(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ne(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Xn/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Xn).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ne(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ne(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ne(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ne(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ne(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ne(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!Qo.test(o.stream_id)){this.sendFrame(Zo);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Yn){this.sendFrame(ne(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Yn}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await We({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Je(Ge())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==Ke.OPEN)break;this.send(i,n),await es(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=Je(Ge());try{let o=Ue(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof se)return ne(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof L)return ne(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof pe)return ne(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?ne(o.status,{type:o.openaiType,message:r},n):ne(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Xo;){let{promise:e,resolve:n}=Yt();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Ke.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Ke.OPEN||this.ws.send(JSON.stringify(e))}};function ft(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
18
- `;t.end(`HTTP/1.1 ${e} ${r}\r
19
- Connection: close\r
20
- Content-Type: text/plain; charset=utf-8\r
21
- Content-Length: ${Buffer.byteLength(o)}\r
22
- \r
23
- ${o}`)}function Qn(t,e){let n=new Wo({noServer:!0,maxPayload:zo}),r=new ke,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,c,v)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{ft(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),p.pathname!==Ko){i.add(c);return}s.add(c);let w=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){ft(c,401,"invalid local proxy api key");return}let S;try{S=await a(l)}catch(k){let m=e.statusOf?.(k)??null;ft(c,m?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(w=!0,n.handleUpgrade(l,c,v,k=>{s.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new zt(k,S,r,e.statusOf)}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!w&&!c.destroyed&&ft(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Yt();if(u)return c(),l;u=!0,t.off("upgrade",d);for(let p of s)p.destroy();s.clear();for(let p of i)p.destroy();i.clear();for(let p of o)p.close(1001,"server shutting down");let v=setTimeout(()=>{for(let p of o)p.readyState!==Ke.CLOSED&&p.terminate()},2e3);return v.unref?.(),n.close(()=>{clearTimeout(v),c()}),l}}}A();A();var X=class extends Error{};async function gt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new X(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new X(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function ht(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new X(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,l]of Object.entries(t.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:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof X?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Zn="/v1/images/generations",yt="/v1/images/edits";function er(t){return t===Zn||t===yt}var tr="/v1/images/models";async function nr(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var C=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ts=16*1024*1024,rr=64*1024*1024;function or(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}function ze(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function sr(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let c of o){if(c.type==="error"){let v=c.error??{};throw new C(502,`image upstream error: ${String(v.message??"upstream reported an error")}`)}if(c.type==="response.completed"){s=c.response??null;break}}if(s===null)throw new C(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new C(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(or(d)===null)throw new C(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function ir(t){return t instanceof C?t:t instanceof L?new C(404,t.message):new C(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function ar(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return ze(r,new C(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function ur(t,e){t&&(t.outputUnits=e.images.length)}function dr(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var ns={model:!0,prompt:!0,response_format:!0,n:!0};async function lr(t,e,n){let r=n.maxBodyBytes??rr;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${Zn}`);let o;try{o=JSON.parse((await gt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof X?new C(413,c.message):new C(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new C(400,"request body must be a JSON object");let s=o;for(let c of Object.keys(s))if(!ns[c])throw new C(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=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new C(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new C(400,"model must be a string","model");await nr(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new C(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new C(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await ar(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await sr(n.clients,a,l,n.turn?oe(n.turn):void 0);ur(n.turn,c),dr(e,c)}catch(c){throw ir(c)}}catch(o){if(o instanceof X){ze(e,new C(413,o.message));return}if(o instanceof C){ze(e,o);return}throw o}}var rs={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function cr(t,e,n){let r=n.maxBodyBytes??rr,o=n.maxImagePartBytes??ts;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${yt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new C(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await ht(t,r)}catch(p){throw p instanceof X?new C(413,p.message):new C(400,String(p instanceof Error?p.message:p))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new C(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new C(400,"model must be a string field","model");let d=u===null?void 0:u;await nr(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new C(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(!rs[p])throw new C(400,`form field "${p}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,p);let c=[];for(let p of["image","image[]"])for(let w of i.getAll(p)){if(!(w instanceof File))throw new C(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(w.size>o)throw new C(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let S=new Uint8Array(await w.arrayBuffer()),k=or(S);if(k===null)throw new C(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);c.push({bytes:S,mime:k})}if(c.length===0)throw new C(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await ar(n.imageModels,d,"edit",e))return;let v=[{type:"input_text",text:a}];for(let{bytes:p,mime:w}of c)v.push({type:"input_image",image_url:`data:${w};base64,${Buffer.from(p).toString("base64")}`});try{let p=await sr(n.clients,d,v,n.turn?oe(n.turn):void 0);ur(n.turn,p),dr(e,p)}catch(p){throw ir(p)}}catch(s){if(s instanceof X){ze(e,new C(413,s.message));return}if(s instanceof C){ze(e,s);return}throw s}}A();var Xe="/v1/audio/speech";function hr(t){return t===Xe}var pr=4096,os=18e4,ss=5e3,is=64*1024*1024,mr=8,fr=5,wt="voice_applied",as="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Xt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var vt=class extends T{constructor(e){super(502,e)}};async function us(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function ds(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var ls=2;function cs(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>ls)return!1;return!0}function ps(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var gr=new WeakMap,_t=new WeakMap;function ms(t,e){let n=_t.get(t)??0;if(n>=mr)throw new T(503,`this model's speech queue is full \u2014 ${mr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${fr}s`,void 0,fr);_t.set(t,n+1);let r=gr.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return gr.set(t,s),(async()=>{await r;try{return await e()}finally{_t.set(t,(_t.get(t)??1)-1),o()}})()}async function fs(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof pe))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Ye(t){return t instanceof T?t:t instanceof L?new T(404,t.message):new T(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function gs(t,e,n,r,o,s,i){return ms(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,l=!1,c=!1,v,p=new Promise(E=>{v=E}),w=()=>{l&&!c&&d>=o.quietRunFrames&&(c=!0,v())},S=e.onOutputAudio(E=>{let f=Buffer.from(E,"base64");if(f.byteLength===0)return;let y=cs(f);if(!u){if(y)return;u=!0}a.push(f),d=y?d+1:0,w()}),k=null,m,g,h;try{h=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let f=new Promise(_=>{g=setTimeout(_,s.capMs)}),y=!1;for(;;){let _=h.next(),x=await Promise.race([_,f]);if(x===void 0){y=!0,_.catch(()=>{});break}if(x.done)break;let P=x.value;if(P.type==="error"){let N=P.error??{};throw await h.return?.(),new T(502,`speech upstream error: ${String(N.message??"upstream reported an error")}`)}if(P.type==="response.completed"){k=P.response??null,l=!0,w(),await h.return?.();break}}if(clearTimeout(g),y)throw new T(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(k===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let b=!1;if(await Promise.race([p,new Promise(_=>{m=setTimeout(()=>{b=!0,_()},o.capMs)})]),m!==void 0&&clearTimeout(m),r.voice!==void 0){let _=k[wt];if(typeof _!="string"||_!==r.voice){let x=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof _=="string"?`${wt} ${JSON.stringify(_)}`:`no ${wt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new vt(x):new T(502,x)}}if(!u)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(b&&!c&&d<1)throw new T(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);let M=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(M),completed:k}}catch(E){throw E instanceof vt||await fs(t,n,h,s.returnBoundMs),E}finally{m!==void 0&&clearTimeout(m),g!==void 0&&clearTimeout(g),S()}})}async function hs(t,e,n){let r;try{r=await t(e)}catch(o){throw Ye(o)}return r?!0:(Xt(n,new T(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var ys={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},_s="wav, pcm";async function yr(t,e,n){let r=n.maxBodyBytes??is,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Xe}`);let i;try{i=JSON.parse((await gt(t,r)).toString("utf8")||"{}")}catch(h){throw h instanceof X?new T(413,h.message):new T(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new T(400,"request body must be a JSON object");let a=i;for(let h of Object.keys(a))if(!ys[h])throw new T(400,`request field "${h}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,h);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(u.length>pr)throw new T(400,`input is ${u.length} chars \u2014 over the ${pr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new T(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new T(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new T(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Xe} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(d)}catch(h){throw Ye(h)}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 ${_s} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new T(400,"stream_format, when present, must be a string","stream_format");let w=a.speed;if(w!==void 0){if(typeof w!="number"||!Number.isFinite(w))throw new T(400,"speed, when present, must be a number","speed");if(w!==1)throw new T(400,`speed=${JSON.stringify(w)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let S=a.instructions;if(S!==void 0){if(typeof S!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new T(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await us(n.turn,n.clients,d);let k=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",k,k),!await hs(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new T(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new T(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let m;try{m=await n.clients.speechSessionHandle(d)}catch(h){throw Ye(h)}let g;try{g=await n.clients.openAudioOn(m)}catch(h){throw Ye(h)}n.turn&&(n.turn.sessionId=g.sessionId);try{let h=await gs(n.clients,g,m,{model:d,text:u,...v!==void 0?{voice:v}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??os,returnBoundMs:n.turnReturnBoundMs??ss},s);if(h===null||s())return;if(ds(n.turn,h.pcm.byteLength),e.statusCode=200,v===void 0){let E=h.completed[wt];typeof E=="string"&&e.setHeader(as,E)}p==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([ps(h.pcm.byteLength),h.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(h.pcm))}catch(h){throw Ye(h)}}catch(i){if(i instanceof X){Xt(e,new T(413,i.message));return}if(i instanceof T){Xt(e,i);return}throw i}}A();var bt="/v1/audio/transcriptions";function _r(t){return t===bt}var wr="/v1/audio/models",ws=16*1024*1024,vs=64*1024*1024,F=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Qt(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function vr(t){return t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===65&&t[10]===86&&t[11]===69}function bs(t){if(!vr(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,d=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:d,channels:u,bitsPerSample:l}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function xs(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function ks(t,e){t&&(t.outputUnits=e.seconds)}async function Rs(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],a=null;for await(let u of s){if(i.push(u),u.type==="error"){let d=u.error??{},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 Le(i,a)}function br(t){return t instanceof F?t:t instanceof L?new F(404,t.message):new F(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ss(t,e,n){let r;try{r=await t(e)}catch(o){throw br(o)}return r?!0:(Qt(n,new F(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Es=new Set(["file","model","language","response_format"]);async function xr(t,e,n){let r=n.maxBodyBytes??vs,o=n.maxAudioPartBytes??ws;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${bt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await ht(t,r)}catch(m){throw m instanceof X?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(!Es.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,g]of a)if(g>1)throw new F(400,`form field "${m}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,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>o)throw new F(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let w=new Uint8Array(await p.arrayBuffer());if(!vr(w))throw new F(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let S=bs(w);if(S===null)throw new F(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await xs(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",w.length,w.length),!await Ss(n.transcriptionModels,d,e))return;let k=[{type:"input_audio",input_audio:{data:Buffer.from(w).toString("base64"),format:"wav"}}];try{let m=await Rs(n.clients,d,k,c,n.turn?oe(n.turn):void 0);ks(n.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:m}))}catch(m){throw br(m)}}catch(s){if(s instanceof X){Qt(e,new F(413,s.message));return}if(s instanceof F){Qt(e,s);return}throw s}}A();var Ir="/v1/usage/requests",kr=1e4,Is=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,we=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},K=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},xt=class extends K{constructor(e){super(e),this.name="UsageWithholdingError"}},Ar=1024*1024;function tn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new we(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new we(`"${e}" must be an array of uuid strings`);if(n.length>kr)throw new we(`"${e}" carries ${n.length} ids; at most ${kr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],o=new Set;for(let s of n){if(typeof s!="string"||!Is.test(s))throw new we(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function Or(t){return tn(t,"inference_ids")}var As=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function Ne(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new K(`${n}: ${e} is not a non-empty string (got ${Fe(r)})`);return r}function Zt(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new K(`${n}: ${e} is neither null nor a non-empty string (got ${Fe(r)})`);return r}function Be(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new K(`${n}: ${e} is not a number (got ${Fe(o)})`);if(r&&!Number.isSafeInteger(s))throw new K(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new K(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Os=40,Rr=64,Sr=600;function Tr(t){let e=Object.keys(t).sort(),r=e.slice(0,Os).map(o=>o.length>Rr?`${o.slice(0,Rr)}\u2026`:o).join(", ");return r.length>Sr&&(r=`${r.slice(0,Sr)}\u2026`),`${e.length} keys present: [${r}]`}function Fe(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function en(t){ye(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
24
- `)}function Ts(t,e){let n;try{n=t(e)}catch{Er(t,e);return}Ps(n)&&Promise.resolve(n).catch(()=>{Er(t,e)})}function Ps(t){return typeof t?.then=="function"}function Er(t,e){if(t!==en)try{en(e)}catch{}}function xu(t,e=en){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Tr(t):Fe(t);throw new K(`the usage surface answered without a "requests" array: got ${Fe(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(Cs(n[o],s))}catch(i){if(i instanceof xt||!(i instanceof K))throw i;Ts(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new K(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Cs(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new K(`${e} is not an object: got ${Fe(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new xt(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of As)if(!Object.hasOwn(n,o))throw new K(`${e} has no "${o}" column (${Tr(n)})`);let r=Be(n,"http_status",e,!0);if(r===null)throw new K(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Ne(n,"inference_id",e),model_id:Ne(n,"model_id",e),identity_kind:Ne(n,"identity_kind",e),variant:Zt(n,"variant",e),task:Ne(n,"task",e),http_status:r,started_at:Ne(n,"started_at",e),completed_at:Ne(n,"completed_at",e),prompt_tokens:Be(n,"prompt_tokens",e,!0),completion_tokens:Be(n,"completion_tokens",e,!0),output_units:Be(n,"output_units",e,!1),output_minutes:Be(n,"output_minutes",e,!1),cost_nano_usd:Be(n,"cost_nano_usd",e,!0),price_version:Zt(n,"price_version",e),priced_at:Zt(n,"priced_at",e)}}function kt(t,e){let n=new Set(e),r=new Set;for(let o=0;o<t.length;o++){let s=t[o];if(!n.has(s.inference_id))throw new K(`the usage surface returned an id at validated answer position ${o} that was not in the request (${e.length} asked, ${t.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(s.inference_id))throw new K(`the usage surface returned ${s.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(s.inference_id)}}import{SessionAllocationError as gi,SessionFailedError as hi}from"@urun-sh/core";A();var nn="/partners/huggingface/v1/billing/requests";function Ms(t){return tn(t,"requestIds")}function $s(t){return t>=200&&t<=399}function Ls(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&$s(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Pr(t,e){let n=Ms(t),r=await e(n);return kt(r,n),Ls(r)}A();var Us={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Ns(t){return Us[t]??null}var $r=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Bs(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Fs(t){return t==="surface"}function qs(t){let e=t?.ledgerFailureReason;return $r.includes(e)?e:"unknown"}var Ds=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Cr=["priced","unpriced"],js={written:Cr,already_written:Cr,skipped:Ds,failed:$r},Ou=Object.entries(js).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Hs(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Gs(t){let e=Date.parse(t.ts),n=Number.isFinite(t.duration_ms)?Math.max(0,t.duration_ms):0;return new Date(e-Math.round(n)).toISOString()}var Js=256,Mr=4096,Qe=12e4,Vs=250,Ws=8e3,me=[],rn=new Set,Ze=0,qe=!1;function Tu(){return me.length}function Pu(t=Date.now()){let e=me[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Rt=new Set;function Lr(){return Ze===0&&me.length===0}function Ur(){if(Lr()){qe=!1;for(let t of[...Rt])t()}}async function Cu(t=Nr){return Lr()?!0:await new Promise(e=>{let n=null,r=()=>{Rt.delete(r),n&&clearTimeout(n),e(!0)};Rt.add(r),n=setTimeout(()=>{Rt.delete(r),e(!1)},t),n.unref?.()})}function Mu(){qe=!0;let t=[...me.splice(0,me.length),...rn];for(let e of t)e.settled||Ie(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Nr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Ur(),t.length}var Nr=5e3;function Br(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
25
- `}function Ks(t){ye(process.stdout,t)}function Fr(t,e){try{t(e)}catch{}}function qr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Ks,o=Ns(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,c)=>{s({outcome:"skipped",reason:l}),Fr(r,Br("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:o,http_status:e.status,started_at:Gs(e),completed_at:e.ts,billable_outcome:Hs(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,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>=Mr){i("queue_full",`${me.length} ledger writes are already waiting (capacity ${Mr}, ${Ze} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}me.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Ze<Js&&(Ze+=1,zs())}async function zs(){try{for(;;){let t=Ys();if(t===void 0)return;rn.add(t);try{await Xs(t)}finally{rn.delete(t)}}}finally{Ze-=1,Ur()}}function Ys(){let t=Date.now();for(;;){let e=me.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Qe)return e;Ie(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${Qe}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function Xs(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Ie(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Bs(o);if(s!==null){Ie(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=qs(o),a=Date.now()-t.queuedAt;if(qe){Ie(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Fs(i)&&a<Qe){if(await Zs(Qs(t.attempts)),qe||Date.now()-t.queuedAt>=Qe){let u=Date.now()-t.queuedAt;Ie(t,{outcome:"failed",reason:qe?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:qe?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${Qe}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}Ie(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Qs(t){return Math.min(Ws,Vs*2**Math.max(0,t-1))}function Zs(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ie(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Fr(t.report,Br(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}A();var sn="x-urun-profile",et="voice";var re=class extends Error{status=400},ei=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,ti=/\s/;function ni(t){return ei.test(t)}function on(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Dr(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function jr(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let d=n.trim();if(d==="")throw new re(`the ${sn} header is empty \u2014 the only profile this lane accepts is "${et}" (omit the header for the ordinary lane)`);if(d!==et)throw new re(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${et}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==et)throw new re(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${et}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new re("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new re("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Dr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Dr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:on(u,"sentence_flush",!0),includeReasoning:on(u,"include_reasoning",!1),metadata:on(u,"metadata",!1)}}var St=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&ni(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(ti.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};A();import*as an from"crypto";var ri="urun-runtime-key-v1";function oi(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return an.createHmac("sha256",t).update(`${ri}|${e}`,"ascii").digest("base64url")}var si="decision-intake",Et=6e4,ii=Et/1e3+5,Hr=3,un=15;function ai(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:si,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=an.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function ui(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function di(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(Et)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new ue(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${Et}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!ui(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=un)}var li=un*1e3,ci=un*500,pi=256,Gr=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new ue("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new ue(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let l=null;for(let c=0;c<Hr;c++){let v=this.pick(d);if(v===null)throw new ue(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let p=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,w=ai(oi(this.opts.secret,p),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},ii);try{return{...await this.post(v,e,w),target:{...r,fnName:s}}}catch(S){if(S instanceof Ae)throw S;l=S;let k=this.replicas.get(v)??{outstanding:0,cooldownUntil:0};k.cooldownUntil=this.nowMs()+5e3,this.replicas.set(v,k);let m=this.presenceCache.get(u);m&&(m.rows=m.rows.filter(g=>g.address!==v),m.rows.length===0&&this.presenceCache.delete(u))}}throw new ue(`no runtime for app=${o} answered within ${Hr} attempts: ${String(l instanceof Error?l.message:l)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>li)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>ci&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=pi;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return di({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??Et)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new Ae(s.status,i);return{status:s.status,body:i,completed:mi(i)}}finally{o.outstanding-=1}}};function mi(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var Ae=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},ue=class extends Error{};function cn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function yi(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function J(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function V(t,e,n,r="invalid_request_error",o){J(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function pn(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);J(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function de(t,e,n,r){J(t,e,{type:"error",error:{type:n,message:r}})}function le(t,e,n){if(e==="anthropic"){J(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}J(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var _i=64*1024*1024,tt=class extends Error{};async function Jr(t,e=_i){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new tt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Oe(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function Kr(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function It(t){let e=Kr(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Vr(t){let e=It(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function wi(t,e){let n=Kr(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function vi(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function bi(t,e){let n=vi(e);n&&(t.timing=n)}function fe(t,e){wi(t,e),bi(t,e)}async function Tt(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function zr(t){let e=t?.output;if(!Array.isArray(e))return"";let n="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let o of r.content)o.type==="reasoning_text"&&(n+=String(o.text??""));return n}function xi(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var At=class extends Error{};function ki(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new At(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Ri(t){let e=[];for(let n of t){if(n.role==="tool"){e.push({type:"function_call_output",call_id:n.tool_call_id,output:typeof n.content=="string"?n.content:JSON.stringify(n.content??"")});continue}if(n.role==="assistant"&&Array.isArray(n.tool_calls)){typeof n.content=="string"&&n.content&&e.push({role:"assistant",content:n.content});for(let r of n.tool_calls){let o=r.function??{};e.push({type:"function_call",call_id:r.id,name:o.name,arguments:o.arguments})}continue}e.push({...n,content:ki(n.role,n.content)})}return e}function dn(t){return Me(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function Si(t,e,n,r,o,s){let i=Je(s.id),a=t.stream===!0;if(s.model=te(t),s.stream=a,await Tt(s,e,typeof t.model=="string"?t.model:void 0),a){let m;try{m=await We({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(g){if(g instanceof L){le(r,"openai",g);return}if(g instanceof se){V(r,g.status,g.message);return}throw g}cn(r);for await(let g of m.events)g.type==="error"&&(s.streamError=!0),g.type==="response.completed"&&fe(s,g.response),r.write(`event: ${String(g.type??"message")}
26
- data: ${JSON.stringify(g)}
27
-
28
- `);r.write(`data: [DONE]
29
-
30
- `),r.end();return}let u;try{u=Ue(n,t)}catch(m){if(m instanceof se){V(r,m.status,m.message);return}throw m}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,l=te(t);o.model(l);let c=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await Wt(e,t,u,!1,oe(s))}catch(m){if(m instanceof L){le(r,"openai",m);return}if(m instanceof se){V(r,m.status,m.message);return}throw m}let p=[],w=null;for await(let m of o.track(v,l,s)){if(p.push(m),m.type==="error"){pn(r,m);return}m.type==="response.completed"&&(w=m.response)}if(w==null){V(r,502,"upstream produced no response.completed event","upstream_error");return}fe(s,w);let S=Le(p,w),k=Ee(c,Me(w).length,S);if(k){V(r,502,Se(l,k),"upstream_error");return}d&&n.remember(i,u,Vt(w,S),d),J(r,200,{...w,id:i})}async function Ei(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){V(n,400,"chat/completions requires a messages array");return}let a;try{a=jr(s,t)}catch(_){if(_ instanceof re){V(n,_.status,_.message);return}throw _}let u=String(t.model??"urun"),d=Gn(o.id),l;try{l=Ri(i)}catch(_){if(_ instanceof At){V(n,400,_.message);return}throw _}let c=te(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Tt(o,e,typeof t.model=="string"?t.model:void 0);let v=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let _;try{_=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(x){if(x instanceof L){le(n,"openai",x);return}throw x}if(_!==null){try{let x=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);o.catalog=Mt(x.target),fe(o,x.completed),J(n,200,{...x.body,id:d})}catch(x){if(x instanceof L){le(n,"openai",x);return}if(x instanceof Ae){J(n,x.status,x.body);return}if(x instanceof ue){V(n,503,x.message,"upstream_error");return}throw x}return}}let p;try{p=await e.createResponse({model:t.model,input:l,stream:!0,tools:xi(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},oe(o))}catch(_){if(_ instanceof L){le(n,"openai",_);return}throw _}if(t.stream===!0){a?yi(n):cn(n);let _=[],x=new _e,P="",N=a?new St(a,ee=>{n.write(`data: ${JSON.stringify(Oe(d,u,{content:ee},null))}
31
-
32
- `)}):null,z=ee=>{N?.flush(),n.write(ee),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
33
-
34
- `),n.write(`data: ${JSON.stringify(Oe(d,u,{role:"assistant"},null))}
35
-
36
- `);for await(let D of r.track(p,c,o)){_.push(D);let Q=$e(D);if(D.type==="response.output_text.delta"&&typeof D.delta=="string")P+=D.delta,N?N.push(D.delta):n.write(`data: ${JSON.stringify(Oe(d,u,{content:D.delta},null))}
37
-
38
- `);else if(D.type==="response.reasoning_text.delta"&&typeof D.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Oe(d,u,{reasoning_content:D.delta},null))}
39
-
40
- `);else if(Q){N?.flush();let{call:ve,isNew:O}=x.add(Q),$=O?{index:Q.tool_index,id:ve.id??`call_${Q.tool_index}`,type:"function",function:{name:ve.name??"",arguments:Q.delta}}:{index:Q.tool_index,function:{arguments:Q.delta}};n.write(`data: ${JSON.stringify(Oe(d,u,{tool_calls:[$]},null))}
41
-
42
- `)}else if(D.type==="error"){o.streamError=!0,z(`data: ${JSON.stringify({error:D})}
43
-
44
- `);return}}let ee=dn(ae(_)),ie=Ee(v,x.size+ee.length,P);if(ie){o.streamError=!0,z(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Se(c,ie)}})}
45
-
46
- `);return}N?.flush(),x.size===0&&ee.length>0&&n.write(`data: ${JSON.stringify(Oe(d,u,{tool_calls:ee},null))}
47
-
48
- `);let ge=x.size>0||ee.length>0;n.write(`data: ${JSON.stringify(Oe(d,u,{},ge?"tool_calls":"stop"))}
49
-
50
- `);let q=It(ae(_));fe(o,ae(_)),q&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Vr(ae(_))})}
51
-
52
- `),n.write(`data: [DONE]
53
-
54
- `),n.end();return}finally{N?.flush(),N?.dispose()}}let w="",S="",k=[],m=new _e;for await(let _ of r.track(p,c,o)){k.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(w+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(S+=_.delta);let x=$e(_);if(x&&m.add(x),_.type==="error"){pn(n,_);return}}let g=ae(k);fe(o,g);let h=dn(g),E=h.length>0?h:dn({output:m.items()}),f=Ee(v,E.length,w);if(f){V(n,502,Se(c,f),"upstream_error");return}let y=E.map(({index:_,...x})=>x),b={role:"assistant",content:w||null},M=S||zr(g);M&&(b.reasoning_content=M),y.length>0&&(b.tool_calls=y),J(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:b,finish_reason:y.length>0?"tool_calls":"stop"}],usage:Vr(g)})}var Ii="reflex-latest";async function Ai(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){V(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:Ii,i=te({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){V(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){V(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){V(n,400,"systemone media, when present, must be an array");return}if(r.model(i),await Tt(o,e,s),e.stateless?.enabled){let p;try{p=await e.stateless.targetFor(s)}catch(w){if(w instanceof L){le(n,"openai",w);return}throw w}if(p!==null){try{let w=await e.stateless.decide(t,s);o.catalog=Mt(w.target),fe(o,w.completed),J(n,200,w.body)}catch(w){if(w instanceof L){le(n,"openai",w);return}if(w instanceof Ae){J(n,w.status,w.body);return}if(w instanceof ue){V(n,503,w.message,"upstream_error");return}throw w}return}}let u;try{u=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},oe(o))}catch(p){if(p instanceof L){le(n,"openai",p);return}throw p}let d=[];try{for await(let p of r.track(u,i,o))if(d.push(p),p.type==="error"){pn(n,p);return}}catch(p){if(p instanceof L){le(n,"openai",p);return}throw p}let l=ae(d);if(l==null){V(n,502,"upstream produced no response.completed event","upstream_error");return}fe(o,l);let c=Le(d,l),v;try{v=JSON.parse(c)}catch{V(n,502,"systemone answer was not valid JSON","upstream_error");return}if(v===null||typeof v!="object"||Array.isArray(v)){V(n,502,"systemone answer was not a JSON object","upstream_error");return}J(n,200,v)}function Oi(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var nt=class extends Error{};function Ot(t){return new nt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Ti(t){if(Array.isArray(t))return t.map(e=>{let n=e;return{type:"function",name:n.name,description:n.description,parameters:n.input_schema}})}function Pi(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new nt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Ci(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Ot(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Ot(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Mi(t){let{role:e,content:n}=t;if(typeof n=="string")return[{role:e,content:n}];if(n==null)return[];if(!Array.isArray(n))throw Ot(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Ci(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Ot(a)}}return s(),r}function ln(t){return Me(t).map((e,n)=>{let r;try{r=JSON.parse(e.arguments||"{}")}catch{throw new Error(`upstream function_call "${e.name??""}" arguments are not valid JSON`)}return{type:"tool_use",id:e.call_id??e.id??`toolu_${n}`,name:e.name??"",input:r}})}async function $i(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){de(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){de(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){de(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(b=>typeof b!="string"))){de(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=Jn(o.id),u=[],d;try{t.system&&u.push({role:"system",content:Oi(t.system)});for(let b of s)u.push(...Mi(b));d=Pi(t.tool_choice)}catch(b){if(b instanceof nt){de(n,400,"invalid_request_error",b.message);return}throw b}let l=te(t);r.model(l),o.model=l,o.stream=t.stream===!0,await Tt(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,v;try{v=await e.createResponse({model:t.model,input:u,stream:!0,tools:Ti(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},oe(o))}catch(b){if(b instanceof L){le(n,"anthropic",b);return}throw b}let p=(b,M)=>{n.destroyed||n.write(`event: ${b}
55
- data: ${JSON.stringify({type:b,...M})}
56
-
57
- `)};if(t.stream===!0){let b=r.track(v,l,o);cn(n),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let M=0,_="",x=0,P="none",N=()=>P,z=-1,ee=-1,ie=new _e,ge=[],q=()=>{P!=="none"&&(P="none",p("content_block_stop",{index:z}))},D=(B,Z)=>{q(),P=B,z=x++,p("content_block_start",{index:z,content_block:Z})};for await(let B of b){if(n.destroyed)break;ge.push(B);let Z=$e(B);if(B.type==="response.reasoning_text.delta"&&typeof B.delta=="string")N()!=="thinking"&&D("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:z,delta:{type:"thinking_delta",thinking:B.delta}});else if(B.type==="response.output_text.delta"&&typeof B.delta=="string")N()!=="text"&&D("text",{type:"text",text:""}),M+=1,_+=B.delta,p("content_block_delta",{index:z,delta:{type:"text_delta",text:B.delta}});else if(Z){let{call:he}=ie.add(Z);(N()!=="tool"||Z.tool_index!==ee)&&(ee=Z.tool_index,D("tool",{type:"tool_use",id:he.id??`call_${Z.tool_index}`,name:he.name??"",input:{}})),Z.delta&&p("content_block_delta",{index:z,delta:{type:"input_json_delta",partial_json:Z.delta}})}else if(B.type==="error"){o.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(B)}}),n.end();return}}if(n.destroyed)return;let Q=ae(ge),ve=Me(Q),O=Ee(c,ie.size+ve.length,_);if(O){o.streamError=!0,p("error",{error:{type:"api_error",message:Se(l,O)}}),n.end();return}q();let $=[];if(ie.size===0)try{$=ln(Q)}catch(B){o.streamError=!0,p("error",{error:{type:"api_error",message:String(B instanceof Error?B.message:B)}}),n.end();return}x===0&&$.length===0&&(D("text",{type:"text",text:""}),q()),$.forEach(B=>{let Z=x++;p("content_block_start",{index:Z,content_block:{...B,input:{}}}),p("content_block_delta",{index:Z,delta:{type:"input_json_delta",partial_json:JSON.stringify(B.input??{})}}),p("content_block_stop",{index:Z})});let W=ie.size>0||$.length>0,ce=It(Q);fe(o,Q),p("message_delta",{delta:{stop_reason:W?"tool_use":"end_turn"},usage:ce?{input_tokens:ce.input_tokens,output_tokens:ce.output_tokens}:{output_tokens:M}}),p("message_stop",{}),n.end();return}let w="",S="",k=[],m=new _e;for await(let b of r.track(v,l,o)){k.push(b),b.type==="response.output_text.delta"&&typeof b.delta=="string"&&(w+=b.delta),b.type==="response.reasoning_text.delta"&&typeof b.delta=="string"&&(S+=b.delta);let M=$e(b);if(M&&m.add(M),b.type==="error"){let _=b.error,x=_?.type==="invalid_request_error";de(n,x?400:502,x?"invalid_request_error":"api_error",_?.message??JSON.stringify(b));return}if(n.destroyed)break}if(n.destroyed)return;let g=ae(k);fe(o,g);let h;try{h=ln(g),h.length===0&&m.size>0&&(h=ln({output:m.items()}))}catch(b){de(n,502,"api_error",String(b instanceof Error?b.message:b));return}let E=Ee(c,h.length,w);if(E){de(n,502,"api_error",Se(l,E));return}let f=[],y=S||zr(g);y&&f.push({type:"thinking",thinking:y}),(w||h.length===0)&&f.push({type:"text",text:w}),f.push(...h),J(n,200,{id:a,type:"message",role:"assistant",content:f,model:i,stop_reason:h.length>0?"tool_use":"end_turn",usage:It(g)??{input_tokens:0,output_tokens:0}})}function Li(t){ye(process.stdout,t)}function Ui(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Li,a=t.observe,u=new ke;return(d,l)=>{let c=new URL(d.url??"/","http://localhost"),v=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),p=(g,h,E,f,y)=>v?de(l,g,f,h):V(l,g,h,E,y),w=Jt(c.pathname),S=c.pathname.startsWith("/partners/"),k=w||S?{id:Ge(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,sessionId:null,timing:null}:null;k&&(l.setHeader(jn,k.id),l.once("close",()=>{let g=Vn({turn:k,method:d.method??"",path:c.pathname,res:l});i(Wn(g)),a?.(g),qr({record:g,ledger:t.ledger??null,req:d})}));let m=()=>Hn(c.pathname,k);(async()=>{if(d.method==="GET"&&c.pathname==="/healthz"){J(l,200,{ok:!0});return}if(d.method==="GET"&&c.pathname==="/stats"){J(l,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let g=c.pathname===Ir?"canonical":c.pathname===nn?"huggingface":null;if(g){if(d.method!=="POST"){p(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let y=t.usage;if(!y){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 b=y.authorize(d),M;try{M=await Jr(d,Ar)}catch(P){if(P instanceof tt){p(413,P.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=P=>y.lookup(b,P),x;try{if(g==="canonical"){let P=Or(M),N=await _(P);kt(N,P),x={requests:N}}else x=await Pr(M,_)}catch(P){if(P instanceof we){p(P.status,P.message,"invalid_request_error","invalid_request_error");return}throw P}J(l,200,x);return}if(c.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${d.method} ${c.pathname} \u2014 the partner surface currently carries ${nn}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(k&&(k.org=h.tenant??null),d.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){if(!h.openRouterModels){p(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}J(l,200,await h.openRouterModels());return}J(l,200,await h.listModels());return}if(d.method==="GET"&&c.pathname===tr){if(!h.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}J(l,200,await h.listImageModels());return}if(er(c.pathname)){if(!h.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 y={clients:h,imageModels:h.supportsImages,stats:u,turn:m()};c.pathname===yt?await cr(d,l,y):await lr(d,l,y);return}if(d.method==="GET"&&c.pathname===wr){if(!h.listSpeechToTextModels){p(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}J(l,200,await h.listSpeechToTextModels());return}if(_r(c.pathname)){if(!h.supportsTranscription){p(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${bt}`,"not_implemented","not_implemented_error");return}let y={clients:h,transcriptionModels:h.supportsTranscription,stats:u,turn:m()};await xr(d,l,y);return}if(hr(c.pathname)){if(!h.supportsSpeech){p(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Xe}`,"not_implemented","not_implemented_error");return}let y={clients:h,speechModels:h.supportsSpeech,stats:u,turn:m()};await yr(d,l,y);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 Jr(d)}catch(y){if(y instanceof tt){p(413,y.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let f=Buffer.byteLength(JSON.stringify(E));if(c.pathname==="/v1/responses"){u.request("responses",f,f),await Si(E,h,Ve(h),l,u,m());return}if(c.pathname==="/v1/chat/completions"){u.request("chat_completions",f,f),await Ei(E,h,l,u,m(),d.headers[sn]);return}if(c.pathname==="/v1/systemone"){u.request("systemone",f,f),await Ai(E,h,l,u,m());return}if(c.pathname==="/v1/messages"){u.request("messages",f,f),await $i(E,h,l,u,m());return}if(c.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",f,f),de(l,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}p(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(g=>{let h=String(g instanceof Error?g.message:g);if(!l.headersSent){let E=o?.(g)??null;if(E){p(E.status,h,E.openaiType,E.anthropicType);return}if(g instanceof gi){let f=pt(g.code);if(f){let y=g.retryAfterSeconds??(f.status===429?30:void 0);y!==void 0&&l.setHeader("Retry-After",String(y)),p(f.status,Dt(f,g.code??void 0),f.openaiType,f.anthropicType,f.code);return}}if(g instanceof hi){let f=mt(g);if(f){let y=f.status===429?30:void 0;y!==void 0&&l.setHeader("Retry-After",String(y)),p(f.status,Dt(f,g.status.sessionId?`session ${g.status.sessionId}`:void 0),f.openaiType,f.anthropicType,f.code);return}}if(g instanceof K){p(502,h,"upstream_error","api_error");return}p(500,h,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0),l.destroyed||(v?l.write(`event: error
58
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h}})}
59
-
60
- `):l.write(`data: ${JSON.stringify({error:{message:h,type:"upstream_error"}})}
61
-
62
- `)),l.end()})}}function id(t){let{clients:e,apiKey:n}=t,r=fi(Ui(t)),o=Qn(r,{clients:e,apiKey:n,statusOf:t.statusOf}),s=Gt(r,{resolver:Wr(e,n)}),i=r.close.bind(r);return r.close=(a=>(o.close(),s(),i(a))),Cn(r,{clients:e,apiKey:n}),r}var rt=(t,e)=>Object.assign(new Error(e),{status:t});function Ni(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function Bi(t,e,n){if(!t.supportsAudio)throw rt(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let r;try{r=await t.supportsAudio(e)}catch(a){throw a instanceof L?rt(404,a.message):a}if(!r)throw rt(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw rt(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=await t.sessionHandle(e),s={audio:await t.openAudioOn(o,n)},i={clients:{createResponse:async a=>await t.createResponseOn(o,a)},voice:r,audioSession:s};return e!==void 0&&(i.model=e),i}function Wr(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,s=typeof o=="string"?o.trim():"",i=s.startsWith("Bearer ")?s.slice(7).trim():"";if(i===""||i!==e)throw rt(401,"invalid local proxy api key")}return Bi(t,Ni(n),r)}}}export{it as a,Cn as b,Hi as c,Ko as d,Qn as e,Zi as f,ao as g,ea as h,ta as i,na as j,ra as k,oa as l,sa as m,ia as n,aa as o,ua as p,uo as q,$n as r,da as s,po as t,la as u,ca as v,pa as w,ye as x,ma as y,fa as z,ga as A,He as B,Ht as C,Gt as D,Ni as E,Bi as F,Wr as G,Ir as H,K as I,xu as J,nn as K,Ou as L,Tu as M,Pu as N,Cu as O,Mu as P,Gr as Q,Ui as R,id as S};
@@ -1 +0,0 @@
1
- import{a as T}from"./chunk-K23AZPI4.js";import{a as I}from"./chunk-76BZLCGT.js";import{a as M,b as U,e as A,f as D,g as _,h as $,j}from"./chunk-TMQJY56F.js";import{c as C,f as x,g as F,p as G}from"./chunk-6M5JK4YC.js";import{c as y}from"./chunk-YSFSRI3D.js";y();import{App as B,createClientToken as ee,DEFAULT_WHEN_LIVE_TIMEOUT_MS as ne}from"@urun-sh/core";y();import{SessionFailedError as J}from"@urun-sh/core";var P=2;function Q(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function X(e){let t=e?.type;return t==="response.completed"||t==="error"}function W(e){return async function(i,p){return(async function*(){for(let d=1;d<=P;d++){let{app:c,entry:l,identity:r}=await e.sessionFor(i.model);p?.({sessionId:e.sessionIdOf?.(l)??null,identity:r});let m=!1,a=!1;try{let f=await e.createStream(l,i);for await(let g of f){if(X(g)&&(m=!0),Q(g)){if(d>1)continue}else a=!0;yield g}}catch(f){if(f instanceof J&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(c,l,f)}catch{}throw f}if(d<P&&!a){await e.evict(c,l);continue}throw f}if(m)return;if(d<P&&!a){await e.evict(c,l);continue}return}})()}}y();var Y=3,z="llm",Z=new Set(["paused","error"]);function N(e,t){let i=e.doc(z),p=typeof i.onConnectionState=="function",u=typeof e.onPhase=="function";if(!p&&!u)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let d=null,c=!1,l=new Set,r=[],m=a=>{if(!d){d=a;for(let f of[...l])f(a);l.clear()}};return p&&r.push(i.onConnectionState(a=>{c&&(a.consecutiveFailures<Y||m(new A(`the pooled session for app "${t}" is gone: its doc backhaul failed ${a.consecutiveFailures} consecutive times (last close ${a.lastCloseCode===null?"by provider liveness reap":`code ${a.lastCloseCode}`}${a.lastCloseReason?`, reason ${JSON.stringify(a.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),u&&r.push(e.onPhase(a=>{if(a.name==="live"){c=!0;return}c&&Z.has(a.name)&&m(new A(`the pooled session for app "${t}" lost its compute binding (phase "${a.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>d,onGone(a){return d?(a(d),()=>{}):(l.add(a),()=>l.delete(a))},dispose(){l.clear();for(let a of r.splice(0))a()}}}async function*E(e,t){let i=t.gone();if(i)throw i;let p=e[Symbol.asyncIterator](),u,d=new Promise((c,l)=>{u=t.onGone(r=>l(r))});d.catch(()=>{});try{for(;;){let c=await Promise.race([p.next(),d]);if(c.done)return;yield c.value}}finally{u?.(),p.return?.(void 0)}}function q(e,t,i,p){let u=e[i];if(typeof u!="function")throw new Error(`app "${t}" has no function "${i}" (set URUN_FUNCTION)`);let d=p?u(void 0,p):u();if(typeof d.end!="function")throw new Error(`app "${t}" function "${i}" returned a session without end()`);return d}function oe(e,t,i){let{baseUrl:p,orgId:u,auth:d}=e,c=typeof e.subject=="function"?e.subject():e.subject,l=i.startsWith(_)&&c!==void 0?`${c}:speech`:c,r=t.fnName??e.fnName,m=e.sessionStartOptions?.(i),a=t.sharedApp?{sharedApp:!0,...m}:m,f=o=>({session:o,responses:new I(o),gone:N(o,i)});if(d.lane==="jwt"){let o=B(t.appSlug,{baseUrl:p,orgId:u,jwt:d.jwt});return f(q(o,t.appSlug,r,a))}let{apiKey:g,gatewayUrl:n}=d,s=B(t.appSlug,{baseUrl:p,orgId:u,getAccessToken:async()=>(await ee(g,{baseUrl:n,expiresIn:300,allowedFunctions:[`${t.appSlug}/${r}`],...l===void 0?{}:{subject:l},...t.sharedApp?{sharedApp:!0}:{}})).token});return f(q(s,t.appSlug,r,a))}function se(e){let t=e.session.id;if(typeof t!="string"||t.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return t}function te(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let t=e.status.error?.httpStatus,i=e.status.error?.code;return t===410||t===409&&(i==="cancelled"||i==="expired")?!0:i==="client_ended"}var ie=new Set(["error","paused"]);function Pe(e){let{auth:t,catalog:i}=e,p=null,u=(c,l)=>{let r=oe(e,c,l);return e.onSessionOpen&&typeof r.session.id=="string"&&r.session.id!==""&&e.onSessionOpen(l,r.session.id),r.gone.onGone(()=>{p?.evict(l,r)}),r},d=new j({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:u,closeSession:async c=>{if(c.gone.dispose(),e.release==="detach"){if(typeof c.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');c.session.detach();return}await c.session.end()},listApps:t.lane==="api-key"?()=>D({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:i?()=>T(i):null,listPrices:i?()=>U(i):null,shared:t.lane==="api-key"?()=>M({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,sessionKey:se});return p=d,e.defaultApp!==null&&e.statelessDirect!==!0&&d.seed(e.defaultApp,u({appSlug:e.defaultApp},$({appSlug:e.defaultApp}))),d}async function O(e,t){let i=e.whenLive;if(typeof i!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await i.call(e,{timeout:ne,signal:t})}async function K(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function k(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Ee(e,t=F,i,p){let u=new WeakMap,d=new WeakMap,c=new WeakMap,l=new WeakMap,r=new WeakMap,m=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},a=n=>{let s=u.get(n);if(!s){let o={waiting:0,gone:new AbortController};r.set(n,o),s=(async()=>{if(await O(n.session,o.gone.signal),o.gone.signal.aborted)throw k(o.gone.signal);r.get(n)===o&&r.delete(n);let h=await C(n.session,await t());return Object.assign(h,{sessionId:n.session.id})})(),u.set(n,s),s.catch(()=>{u.get(n)===s&&u.delete(n)}),s.then(()=>{r.get(n)===o&&r.delete(n)},()=>{r.get(n)===o&&r.delete(n)})}return s},f=n=>{let s=l.get(n);return s||(s=(async()=>{let o=await a(n);return{appendInputAudio:h=>o.appendInputAudio(h),onOutputAudio:h=>o.onOutputAudio(h),sessionId:m(n)}})(),l.set(n,s),s.catch(()=>{l.get(n)===s&&l.delete(n)})),s},g=async(n,s,o)=>{if(o?.aborted){let S=r.get(n);throw(u.get(n)===void 0||S!==void 0&&S.waiting===0)&&await K(n.session),k(o)}let h=s(n),w=r.get(n);return w!==void 0&&w.waiting++,o===void 0?h:new Promise((S,v)=>{let L=()=>{w!==void 0&&--w.waiting===0&&r.get(n)===w&&(w.gone.abort(),r.delete(n),u.delete(n),l.delete(n),K(n.session).catch(()=>{})),v(k(o))};o.addEventListener("abort",L,{once:!0});let R=()=>o.removeEventListener("abort",L);h.then(b=>{R(),S(b)},b=>{R(),v(b)})})};return{createResponse:W({sessionFor:n=>e.sessionFor(n),sessionIdOf:n=>m(n),evict:(n,s)=>e.evict(n,s),onAdmissionVerdict:(n,s,o)=>{te(o)&&(e.evict(n,s),i?.(n,o.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>(await O(n.session),E(await n.responses.responses.create(s),n.gone))}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,s)=>e.supportsImages(n,s),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,s)=>{let{entry:o}=await e.sessionFor(n);return await g(o,a,s)},openAudioOn:async(n,s)=>{let{entry:o}=await e.sessionForHandle(n);return await g(o,f,s)},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),o=d.get(s);return o||(o=x(s.session),d.set(s,o)),o},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),o=c.get(s);return o||(o=G(s.session),c.set(s,o)),o},sessionHandle:async n=>(await e.handleFor(n)).handle,speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:o}=await e.sessionForHandle(n);await e.evict(s,o)},createResponseOn:async(n,s)=>{let{entry:o}=await e.sessionForHandle(n);return await O(o.session),E(await o.responses.responses.create(s),o.gone)},onSessionEnd:async(n,s)=>{let{entry:o}=await e.sessionForHandle(n),h=o.session;if(typeof h.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let w=!1;return h.onPhase(S=>{if(w||!ie.has(S.name))return;w=!0;let v=h.endsAt??null;s({timeLeftMs:v?Math.max(0,v.getTime()-Date.now()):null,reason:S.reason??`session ${S.name}`})})},...p?{stateless:p}:{}}}export{Pe as a,Ee as b};