@urun-sh/openai 0.6.49 → 0.6.51

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,92 +1,92 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ca=Object.create;var uo=Object.defineProperty;var Ma=Object.getOwnPropertyDescriptor;var $a=Object.getOwnPropertyNames;var La=Object.getPrototypeOf,Na=Object.prototype.hasOwnProperty;var Ua=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $a(e))!Na.call(t,o)&&o!==n&&uo(t,o,{get:()=>e[o],enumerable:!(r=Ma(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Ca(La(t)):{},Ua(e||!t||!t.__esModule?uo(n,"default",{value:t,enumerable:!0}):n,t));var Da=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,L=Da();var oo=require("child_process"),Ae=require("fs"),so=ot(require("path"),1),H=ot(require("process"),1);var oe=require("@urun-sh/core");var Ie=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ce=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var en=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};async function lo(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var go=require("@urun-sh/core/internal");function co(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Wn(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}function po(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var fo=require("@urun-sh/core/internal");var Fa="llm-resp";async function*mo(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let u=typeof i.index=="number"?i.index:0,a=r.get(u)??{};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),r.set(u,a),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${u}`,tool_index:u,call_id:a.id,name:a.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield po(s);return}}}async function*Kn(t,e){let n=`${Fa}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*mo(e,t.stream(n).messages())}finally{try{(0,fo.gcRequest)(t.doc("llm"),e)}catch{}}}var tn=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Wn(e,n,this.consumerId);return this.write(r),Kn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=co(e,n,r,this.consumerId);return this.write(o),Kn(this.session,r)})}cancelTurn(e){try{(0,go.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await lo(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var ho=0;function qa(){return ho+=1,`req_${Date.now().toString(36)}_${ho.toString(36)}`}var kt=class{transport;constructor(e,n){this.transport=new tn(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=qa(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var wo="audio",zn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function _o(t,e,n=1e4){try{return await ja(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function ja(t,e,n){let r=new zn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(wo);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Ha(t,n);return await r.startInbound(i),r}function Ha(t,e){let n=t.stream(wo);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=a=>{a!=null&&(clearTimeout(i),s?.(),r(a))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var yo="rt-video-in",Rt=256e3;function Xn(t){let e=t.stream(yo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${yo}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>Rt)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Rt}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var Ga=24e3,xt=480,Va=111,Ja=50,nn=null;async function Wa(){if(nn)return;let t=await import("opusscript");nn=t.default??t}function Ka(){if(!nn)throw new Error("[opus-guard] opusscript module not loaded");return new nn(Ga,1,2048)}var Yn=class{constructor(e=Ka){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=Ja}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function rn(){let t=await import("werift");await Wa();let e=new Yn;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:u=>{let a=new Int16Array(i.length+u.length);a.set(i,0),a.set(u,i.length);let l=0;for(;a.length-l>=xt;){let d=a.subarray(l,l+xt);l+=xt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,xt);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+xt>>>0;let m=new t.RtpHeader({version:2,payloadType:Va,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),g=new t.RtpPacket(m,p);n.writeRtp(g)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(a){if(e.wedged)throw a;return}let u=new Int16Array(i.length/2);for(let a=0;a<u.length;a++)u[a]=i.readInt16LE(a*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function vo(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var on=require("@urun-sh/core"),Qn="rt-video-out";var za="h264";function Ya(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function Xa(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ya(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var bo="urun.videoOut.v2-ws";function So(t){let e=t.stream(Qn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Qn}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=a=>{for(let l of r)l(a)},i=!1,u=async()=>{for await(let a of e.messages()){if(!(a instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Qn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Xa(a)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let a of o)a()};return{codec:za,onOutputFrame:a=>(n.add(a),i||(i=!0,u().catch(l=>s(l instanceof Error?l:new Error(String(l))))),()=>n.delete(a)),onLaneError:a=>(r.add(a),()=>r.delete(a)),onEnd:a=>(o.add(a),()=>o.delete(a))}}var ko={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},st=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function xo(t){let e=t.t;if(typeof e!="string"||!(e in ko))throw new st(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(ko).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function Qa(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new st(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new st(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return xo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new st(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return xo(t)}function Ro(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Za(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Eo(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Ro(e);let s=o.next();if(e!==void 0&&await Za(s,e)==="aborted")throw s.catch(()=>{}),Ro(e);let i=await s;if(i.done)return;yield Qa(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Ao=require("@urun-sh/core"),Zn=2;function eu(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function tu(t){let e=t?.type;return e==="response.completed"||e==="error"}function Io(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Zn;i++){let{app:u,entry:a,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(a,n);for await(let m of p){if(tu(m)&&(d=!0),eu(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Ao.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<Zn&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<Zn&&!c){await t.evict(u,a);continue}return}})()}}var yr=require("crypto");var ge=class extends Error{name="ModelPriceError"},er="per_million_input_tokens",tr="per_million_output_tokens",Oo="model_id,variant,unit,price_usd,effective_at,expires_at",To={per_request:!0,per_minute:!0,per_output_unit:!0},nu=5e3;function ru(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ge(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Po(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ge(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function ou(t,e,n){return t===null?null:Po(t,e,n)}function su(t,e){if(t===er)return"input";if(t===tr)return"output";if(typeof t=="string"&&Object.hasOwn(To,t))return null;throw new ge(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${er} | ${tr}) nor a known GPU-time unit (${Object.keys(To).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 iu(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.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:n}}function nr(t,e){return`${t}\0${e}`}function au(t){if(!Array.isArray(t))throw new ge(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ge(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Oo.split(","))if(!Object.hasOwn(s,l))throw new ge(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=su(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new ge(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new ge(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:ru(s.price_usd,o),effective_at:Po(s.effective_at,o,"effective_at"),expires_at:ou(s.expires_at,o,"expires_at")})}return e}function Co(t,e=Date.now(),n){let r=new Map,o=new Map;for(let a of t){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=r.get(a.model_id);l||(l=new Map,r.set(a.model_id,l),o.set(a.model_id,new Map));let d=a.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(a.model_id).set(d,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let s=[],i=[];for(let[a,l]of r){let d=l.get(""),c=(p,m,g)=>{let v=p&&p.length>0?p:d?.[m];if(!v||v.length===0)return null;let k=iu(v,m);return"reason"in k?k:k.rate.usd===0?m==="output"&&g!==null&&n?.has(nr(a,g))?k.rate:{reason:`the ${m} 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`}:k.rate};for(let[p,m]of o.get(a)){let g=l.get(p),v=c(g?.input,"input",m),k=c(g?.output,"output",m);if(v!==null&&"reason"in v){i.push({model_id:a,variant:m,reason:v.reason});continue}if(k!==null&&"reason"in k){i.push({model_id:a,variant:m,reason:k.reason});continue}v===null||k===null||s.push({model_id:a,variant:m,pricing:{input:v.usd,output:k.usd}})}}let u=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:s.sort(u),refusals:i.sort(u)}}function Et(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var At={prices:[],refusals:[]};async function Mo(t){let e=t.fetchImpl??fetch,n=`${er},${tr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Oo}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(nu)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return au(await r.json())}var Wo=require("crypto");var ee=class extends Error{},uu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function lu(t){if(typeof t!="string")return!1;let e=uu.exec(t);if(!e)return!1;let[,n,r,o,s,i,u]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let a=new Date(Date.UTC(n,r-1,o,s,i,u));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===o&&a.getUTCHours()===s&&a.getUTCMinutes()===i&&a.getUTCSeconds()===u}function du(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((u,a)=>{if(u===null||typeof u!="object")throw new ee(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(u)}`);let l=u;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new ee(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new ee(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new ee(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",lu(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new ee(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(u=>typeof u=="string"&&u.length>0)))throw new ee(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let u=s;if(typeof s!="object"||typeof u.zdr!="boolean"||typeof u.hipaa!="boolean")throw new ee(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let a of Object.keys(u))if(a!=="zdr"&&a!=="hipaa")throw new ee(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function it(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function $o(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=u=>new ee(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${u}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let u of["model_id","variant"]){let a=o[u];if(typeof a!="string"||a===""||a.includes(":"))throw i(`"${u}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function rr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let u=t.endpoints.filter(l=>l.model_id===o);if(u.length===0)return null;if(s!==void 0){let l=u.find(d=>d.variant===s);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(u.length===1)return{shared_org_id:t.shared_org_id,endpoint:u[0]};let a=u.filter(l=>l.compat_default===!0);if(a.length!==1)throw new ee(`shared model "${o}" has ${a.length} compat_default rows (exactly one required) among variants ${u.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:a[0]}}async function Lo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return du(await r.json())}function pe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Tt="/partners/openrouter/models",cu={chat:!0,code:!0,agent:!0,vl:!0},No={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function pu(t){let e=t.toLowerCase();return Object.hasOwn(No,e)?No[e]:null}var Uo={"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 fu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Uo,o)?Uo[o]:null;if(s===null){r.push(o);continue}n.some(u=>u.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Do={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Fo={2:"Llama2",3:"Llama3"};function mu(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(Do,s))return Do[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Fo,i))return Fo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var gu=["context_length","max_model_len"];function hu(t){let e=gu.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function sn(t){let e=t.map(hu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function yu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function or(t){if(t.length===0)return null;let e=t.map(yu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function sr(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function wu(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return It(n);let r=e.filter(s=>pe(s.model_id)===t);if(r.length>0)return It(r);let o=sr(t,e);return o.length>0?It(o):null}function It(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:_u(t),matches:t}:null}function _u(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var Le=class extends Error{name="ModelCreatedError"};function at(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new Le(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new Le(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new Le(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),u=Number(o[3]),a=Date.UTC(s,i-1,u),l=new Date(a);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==u)throw new Le(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function Ge(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function an(t,e,n){let r=wu(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=sn(s),u=at(s),a=Et(o.model_id,o.variant,n),l=jo(o,s),d=or(s);return Ge({id:t,object:"model",created:u,owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var vu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function jo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,u)=>i===r[u])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...vu],defect:o}:{published:[],defect:o}}function ir(t){let e=t.length>0?It(t):null;return e===null?{published:[],defect:null}:jo(e.row,e.matches)}function Bo(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function qo(t){return{input:[{type:"prompt",unit:"token",cost_usd:Bo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Bo(t.output)}]}}function bu(t,e,n,r){if(e.length===0)return null;let o=It(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||cu[s.task]!==!0)return null;let u=sn(i),a=Et(s.model_id,s.variant,n),l=mu(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return u!==null&&(d.max_tokens={type:"integer",min:1,max:u,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:at(i),quantization:pu(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...u!==null?{supported_inputs:{max_context_length:{value:u,unit:"token"}}}:{},...a?{pricing:qo(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:qo(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ho(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?it(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:fu(t?.regions,o),compliance:t?.compliance??null},u=[],a=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(a.has(d))continue;a.add(d);let c=bu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Ko="https://api.urun.sh/v1",J=class extends Error{},W=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},dr="credits_exhausted",cr="insufficient_credits",ur="urs1.";function Ct(t,e){return ur+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Ve(t){if(!t.startsWith(ur))return null;try{let e=JSON.parse(Buffer.from(t.slice(ur.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function zo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Go(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Ru(t);return e===null?[]:[e]}function Su(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
2
+ "use strict";var Ca=Object.create;var uo=Object.defineProperty;var Ma=Object.getOwnPropertyDescriptor;var $a=Object.getOwnPropertyNames;var La=Object.getPrototypeOf,Na=Object.prototype.hasOwnProperty;var Ua=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $a(e))!Na.call(t,o)&&o!==n&&uo(t,o,{get:()=>e[o],enumerable:!(r=Ma(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Ca(La(t)):{},Ua(e||!t||!t.__esModule?uo(n,"default",{value:t,enumerable:!0}):n,t));var Da=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,L=Da();var oo=require("child_process"),Ae=require("fs"),so=ot(require("path"),1),G=ot(require("process"),1);var oe=require("@urun-sh/core");var Ie=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ce=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var en=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};async function lo(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var go=require("@urun-sh/core/internal");function co(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),typeof o.model=="string"&&o.model&&(s.model=o.model),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Wn(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}function po(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,n=e.body??{},r=n.error,o=r?.message??n.message??`unreadable serve error body: ${JSON.stringify(e.body??null)}`;return{type:"error",error:{type:r?.type??"urun_error",code:e.code??r?.code??null,message:o}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var fo=require("@urun-sh/core/internal");var Fa="llm-resp";async function*mo(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let u=typeof i.index=="number"?i.index:0,a=r.get(u)??{};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),r.set(u,a),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${u}`,tool_index:u,call_id:a.id,name:a.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield po(s);return}}}async function*Kn(t,e){let n=`${Fa}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*mo(e,t.stream(n).messages())}finally{try{(0,fo.gcRequest)(t.doc("llm"),e)}catch{}}}var tn=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Wn(e,n,this.consumerId);return this.write(r),Kn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=co(e,n,r,this.consumerId);return this.write(o),Kn(this.session,r)})}cancelTurn(e){try{(0,go.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await lo(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var ho=0;function qa(){return ho+=1,`req_${Date.now().toString(36)}_${ho.toString(36)}`}var kt=class{transport;constructor(e,n){this.transport=new tn(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=qa(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var wo="audio",zn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function _o(t,e,n=1e4){try{return await ja(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function ja(t,e,n){let r=new zn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(wo);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Ha(t,n);return await r.startInbound(i),r}function Ha(t,e){let n=t.stream(wo);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=a=>{a!=null&&(clearTimeout(i),s?.(),r(a))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var yo="rt-video-in",Rt=256e3;function Xn(t){let e=t.stream(yo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${yo}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>Rt)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Rt}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var Ga=24e3,xt=480,Va=111,Ja=50,nn=null;async function Wa(){if(nn)return;let t=await import("opusscript");nn=t.default??t}function Ka(){if(!nn)throw new Error("[opus-guard] opusscript module not loaded");return new nn(Ga,1,2048)}var Yn=class{constructor(e=Ka){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=Ja}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function rn(){let t=await import("werift");await Wa();let e=new Yn;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:u=>{let a=new Int16Array(i.length+u.length);a.set(i,0),a.set(u,i.length);let l=0;for(;a.length-l>=xt;){let d=a.subarray(l,l+xt);l+=xt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,xt);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+xt>>>0;let m=new t.RtpHeader({version:2,payloadType:Va,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),g=new t.RtpPacket(m,p);n.writeRtp(g)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(a){if(e.wedged)throw a;return}let u=new Int16Array(i.length/2);for(let a=0;a<u.length;a++)u[a]=i.readInt16LE(a*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function vo(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var on=require("@urun-sh/core"),Qn="rt-video-out";var za="h264";function Ya(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function Xa(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ya(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var bo="urun.videoOut.v2-ws";function So(t){let e=t.stream(Qn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Qn}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=a=>{for(let l of r)l(a)},i=!1,u=async()=>{for await(let a of e.messages()){if(!(a instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Qn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Xa(a)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let a of o)a()};return{codec:za,onOutputFrame:a=>(n.add(a),i||(i=!0,u().catch(l=>s(l instanceof Error?l:new Error(String(l))))),()=>n.delete(a)),onLaneError:a=>(r.add(a),()=>r.delete(a)),onEnd:a=>(o.add(a),()=>o.delete(a))}}var ko={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},st=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function xo(t){let e=t.t;if(typeof e!="string"||!(e in ko))throw new st(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(ko).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function Qa(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new st(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new st(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return xo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new st(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return xo(t)}function Ro(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Za(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function Eo(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw Ro(e);let s=o.next();if(e!==void 0&&await Za(s,e)==="aborted")throw s.catch(()=>{}),Ro(e);let i=await s;if(i.done)return;yield Qa(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Ao=require("@urun-sh/core"),Zn=2;function eu(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function tu(t){let e=t?.type;return e==="response.completed"||e==="error"}function Io(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Zn;i++){let{app:u,entry:a,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(a,n);for await(let m of p){if(tu(m)&&(d=!0),eu(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Ao.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<Zn&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<Zn&&!c){await t.evict(u,a);continue}return}})()}}var yr=require("crypto");var ge=class extends Error{name="ModelPriceError"},er="per_million_input_tokens",tr="per_million_output_tokens",Oo="model_id,variant,unit,price_usd,effective_at,expires_at",To={per_request:!0,per_minute:!0,per_output_unit:!0},nu=5e3;function ru(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ge(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Po(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ge(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function ou(t,e,n){return t===null?null:Po(t,e,n)}function su(t,e){if(t===er)return"input";if(t===tr)return"output";if(typeof t=="string"&&Object.hasOwn(To,t))return null;throw new ge(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${er} | ${tr}) nor a known GPU-time unit (${Object.keys(To).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 iu(t,e){let n=t.reduce((o,s)=>s.effective_at>o.effective_at?s:o,t[0]),r=t.find(o=>o.effective_at===n.effective_at&&o.usd!==n.usd);return r?{reason:`two ${e} rates are effective at the same instant (${n.usd} and ${r.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:n}}function nr(t,e){return`${t}\0${e}`}function au(t){if(!Array.isArray(t))throw new ge(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ge(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Oo.split(","))if(!Object.hasOwn(s,l))throw new ge(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=su(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new ge(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new ge(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:ru(s.price_usd,o),effective_at:Po(s.effective_at,o,"effective_at"),expires_at:ou(s.expires_at,o,"expires_at")})}return e}function Co(t,e=Date.now(),n){let r=new Map,o=new Map;for(let a of t){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=r.get(a.model_id);l||(l=new Map,r.set(a.model_id,l),o.set(a.model_id,new Map));let d=a.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(a.model_id).set(d,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let s=[],i=[];for(let[a,l]of r){let d=l.get(""),c=(p,m,g)=>{let S=p&&p.length>0?p:d?.[m];if(!S||S.length===0)return null;let x=iu(S,m);return"reason"in x?x:x.rate.usd===0?m==="output"&&g!==null&&n?.has(nr(a,g))?x.rate:{reason:`the ${m} 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`}:x.rate};for(let[p,m]of o.get(a)){let g=l.get(p),S=c(g?.input,"input",m),x=c(g?.output,"output",m);if(S!==null&&"reason"in S){i.push({model_id:a,variant:m,reason:S.reason});continue}if(x!==null&&"reason"in x){i.push({model_id:a,variant:m,reason:x.reason});continue}S===null||x===null||s.push({model_id:a,variant:m,pricing:{input:S.usd,output:x.usd}})}}let u=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:s.sort(u),refusals:i.sort(u)}}function Et(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var At={prices:[],refusals:[]};async function Mo(t){let e=t.fetchImpl??fetch,n=`${er},${tr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Oo}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(nu)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return au(await r.json())}var Wo=require("crypto");var ee=class extends Error{},uu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function lu(t){if(typeof t!="string")return!1;let e=uu.exec(t);if(!e)return!1;let[,n,r,o,s,i,u]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let a=new Date(Date.UTC(n,r-1,o,s,i,u));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===o&&a.getUTCHours()===s&&a.getUTCMinutes()===i&&a.getUTCSeconds()===u}function du(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new ee(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new ee(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new ee(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((u,a)=>{if(u===null||typeof u!="object")throw new ee(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(u)}`);let l=u;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new ee(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new ee(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new ee(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",lu(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new ee(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(u=>typeof u=="string"&&u.length>0)))throw new ee(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let u=s;if(typeof s!="object"||typeof u.zdr!="boolean"||typeof u.hipaa!="boolean")throw new ee(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let a of Object.keys(u))if(a!=="zdr"&&a!=="hipaa")throw new ee(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function it(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function $o(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=u=>new ee(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${u}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let u of["model_id","variant"]){let a=o[u];if(typeof a!="string"||a===""||a.includes(":"))throw i(`"${u}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function rr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let u=t.endpoints.filter(l=>l.model_id===o);if(u.length===0)return null;if(s!==void 0){let l=u.find(d=>d.variant===s);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(u.length===1)return{shared_org_id:t.shared_org_id,endpoint:u[0]};let a=u.filter(l=>l.compat_default===!0);if(a.length!==1)throw new ee(`shared model "${o}" has ${a.length} compat_default rows (exactly one required) among variants ${u.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:a[0]}}async function Lo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new ee(`catalog read failed: GET ${n} \u2192 ${r.status}`);return du(await r.json())}function pe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Tt="/partners/openrouter/models",cu={chat:!0,code:!0,agent:!0,vl:!0},No={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function pu(t){let e=t.toLowerCase();return Object.hasOwn(No,e)?No[e]:null}var Uo={"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 fu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Uo,o)?Uo[o]:null;if(s===null){r.push(o);continue}n.some(u=>u.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Do={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Fo={2:"Llama2",3:"Llama3"};function mu(t){if(!t)return null;let e=t.split("@")[0],n=e.indexOf("/"),r=(n===-1?e:e.slice(n+1)).toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>0);for(let o=0;o<r.length;o+=1){let s=r[o];if(Object.hasOwn(Do,s))return Do[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Fo,i))return Fo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var gu=["context_length","max_model_len"];function hu(t){let e=gu.map(n=>t.engine_args?.[n]).filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0);return e.length===0?null:e.every(n=>n===e[0])?e[0]:null}function sn(t){let e=t.map(hu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function yu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function or(t){if(t.length===0)return null;let e=t.map(yu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function sr(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function wu(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return It(n);let r=e.filter(s=>pe(s.model_id)===t);if(r.length>0)return It(r);let o=sr(t,e);return o.length>0?It(o):null}function It(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:_u(t),matches:t}:null}function _u(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var Le=class extends Error{name="ModelCreatedError"};function at(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new Le(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new Le(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new Le(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),u=Number(o[3]),a=Date.UTC(s,i-1,u),l=new Date(a);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==u)throw new Le(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function Ge(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function an(t,e,n){let r=wu(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=sn(s),u=at(s),a=Et(o.model_id,o.variant,n),l=jo(o,s),d=or(s);return Ge({id:t,object:"model",created:u,owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var vu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function jo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,u)=>i===r[u])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...vu],defect:o}:{published:[],defect:o}}function ir(t){let e=t.length>0?It(t):null;return e===null?{published:[],defect:null}:jo(e.row,e.matches)}function Bo(t){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(t));if(!e)throw new Error(`unrenderable per-token price: ${String(t)}`);let[,n="",r="",o=""]=e,s=n+r,i=n.length-6+(o===""?0:Number(o));return(i<=0?`0.${"0".repeat(-i)}${s}`:`${s.slice(0,i)}.${s.slice(i).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function qo(t){return{input:[{type:"prompt",unit:"token",cost_usd:Bo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Bo(t.output)}]}}function bu(t,e,n,r){if(e.length===0)return null;let o=It(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||cu[s.task]!==!0)return null;let u=sn(i),a=Et(s.model_id,s.variant,n),l=mu(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return u!==null&&(d.max_tokens={type:"integer",min:1,max:u,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:at(i),quantization:pu(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...u!==null?{supported_inputs:{max_context_length:{value:u,unit:"token"}}}:{},...a?{pricing:qo(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:qo(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Ho(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?it(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:fu(t?.regions,o),compliance:t?.compliance??null},u=[],a=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(a.has(d))continue;a.add(d);let c=bu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Ko="https://api.urun.sh/v1",J=class extends Error{},W=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},dr="credits_exhausted",cr="insufficient_credits",ur="urs1.";function Ct(t,e){return ur+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Ve(t){if(!t.startsWith(ur))return null;try{let e=JSON.parse(Buffer.from(t.slice(ur.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function zo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function Go(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Ru(t);return e===null?[]:[e]}function Su(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
3
3
  `),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let u=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(u)||u<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
4
4
  `),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function ku(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||pe(`${r.model_id}-${r.variant}`)===e.appSlug||pe(r.model_id)===e.appSlug)),n?Su(n.engine_args?.pool):null}function ar(t,e,n,r,o){if(!o)throw new ee(`shared model "${t}" 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(e===void 0||n===void 0)throw new ee(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new ee(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Vo(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new ee(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var Yo="shared:",Jo="speech:",Mt="realtime:";function Ue(t){return t.sharedApp?Yo+t.appSlug:t.appSlug}function Pt(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function lr(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>pe(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function xu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Ru(t){let e=t.map(xu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Eu={stt:"stt",tts:"tts"};function Ne(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:Eu[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Xo(t,e){let n=lr(t,e);return n.length>0?n:sr(t,e)}function Ot(t,e){return Xo(t.appSlug,e)}function Au(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new ee(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var un=6e4,ln=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??un):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??un):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??un):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??un;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ge)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
5
5
  `),At}let r=Co(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
6
6
  `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(nr(r.model_id,r.variant));return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.serves==="openai"&&n.deployment_status==="active").map(n=>n.app_slug)}async availableIds(){let e=this.opts.defaultApp,n=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let o of this.servable(await this.deployedApps()))n.add(o);for(let o of this.pool.keys())o.startsWith(Yo)||o.startsWith(Jo)||n.add(o);let r=[...n].filter(o=>o!==e).sort();return e===null?r:[e,...r]}async noDefaultApp(e){let n=await this.availableIds(),r=n.length>0?n.join(", "):"(none deployed)";throw new J(e===""?`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: ${r}`:`model "${e}" 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: ${r}`)}async sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=rr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,u=pe(s),a=n.endpoints.filter(c=>pe(c.model_id)===u&&(i===void 0||c.variant===i)),l=new Set(a.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:rr(n,d,i)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};n=n.replace(/^urun\//i,"");let o=pe(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),u=this.servable(i);if(u.includes(o))return{appSlug:o};let a=u.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new J(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new J(`model "${n}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let u=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===pe(a.model_id)||o===pe(`${a.model_id}-${a.variant}`));if(u)throw new J(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${u.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=Pt(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return ku(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ue(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ue(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return Pt(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Jo+Ue(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Mt+(0,Wo.randomUUID)())}async evictHandle(e){let n=Ve(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:Pt(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Ct(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Ct(n,this.keyOf(r))}}async sessionForHandle(e){let n=Ve(e);if(!n)throw new W(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(u=>u,()=>null):null;if(i===null)throw new W(`the session behind this handle (app "${r}") 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(i)!==o&&this.mintedIds.get(i)!==o)throw new W(`the session behind this handle (app "${r}") 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:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:At;r.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)
7
- `);let a=(n?it(n):[]).map(l=>{let d=s.filter(S=>S.model_id===l.model_id&&S.variant===l.variant),c=sn(d),p=at(d),m=or(d),g=Et(l.model_id,l.variant,i),v=ir(d);return Ge({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>an(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ho(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=ar(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Vo(`${r.modelId}:${r.variant}`,s).includes(n)}return Go(lr(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ne(Ot(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ne(Ot(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ne(Ot(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return Au(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return ir(o)}async imageModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds()){let i=Go(lr(s,e));i.length!==0&&r.push(Ge({...an(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Vo(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds())Ne(Xo(s,e))==="stt"&&r.push(an(s,e,n));let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Ne(i)!=="stt")continue;let u=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var De=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},$t=class extends De{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},pr=class extends De{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},be=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},dn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new $t;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let a=r+n-Date.now();if(a<=0)throw new pr(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,a)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var fr=require("@urun-sh/core"),Se=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},pn=33e4;function Qo(t,e=pn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new cn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof W||l instanceof fr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof cn?(await r.return?.(void 0),new Se("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Se("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new Se("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var cn=class extends Error{constructor(){super("stream idle timeout")}};function Zo(t){return t instanceof Se?!1:t instanceof W?!0:t instanceof fr.SessionFailedError?t.kind==="transport-failed":!1}var Iu=require("http");var fn=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds};var mr=require("@urun-sh/core"),Tu="audio";function es(t){let e=t.streamEndpoint(Tu);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,mr.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,mr.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var ts=require("@urun-sh/core"),Ou="rt-video-in";function ns(t){let e=t.streamEndpoint(Ou);return{sendInputFrame:async n=>{e.send((0,ts.encodeStreamEnvelope)(n))}}}var Pu=3,Cu="llm",Mu=new Set(["paused","error"]);function rs(t,e,n){let r=t.doc(Cu),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" 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 i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<Pu||d(new W(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&Mu.has(c.name)&&d(new W(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`,{bindingLost:!0,reason:c.reason??null}))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*gr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var Lu=0,Nu=4,Uu=4;function ss(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Lu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Nu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Uu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function is(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return pn;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function hr(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function as(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=v=>({session:v,responses:new kt(v),gone:rs(v,n)});if(i.lane==="jwt"){let v=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(hr(v,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let v=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:k}=i,S=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),_=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(v,{baseUrl:k,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:S,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(_,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),g=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(g,e.appSlug,u,l))}function us(t){let e=t.session.id;if(typeof e!="string"||e.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 e}function wr(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var Du=new Set(["error","paused"]);function ls(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=as(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new ln({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>zo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>vo(n):null),listPrices:n?()=>Mo(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return $o(i)}:e.lane==="api-key"?()=>Lo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:us});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ue({appSlug:t.defaultApp}))),s}function ds(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
8
- `)},a=(d,c)=>{let p=o.get(c);if(p)return p;let m=new dn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async g=>{let v=as(t,d,c,{concurrencyKey:g.concurrencyKey});return v.gone.onGone(k=>k.bindingLost?m.evict(v):m.markSessionDead(v)),await gn(v.session),u(`slot attached pool=${c} slot=${g.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async g=>{g.gone.dispose(),g.audioDispose?.(),await g.session.end()},onDetach:(g,v)=>u(`slot detached pool=${c} slot=${g.concurrencyKey} reason=${v}`),terminalOpenFailure:g=>g instanceof oe.SessionFailedError&&wr(g)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);a(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){u(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ue(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ue(c),m=a(c,p);await l(c,p);let g=await m.acquire({timeoutMs:m.requestWaitMs}),v=i.get(g.entry)??[];return v.push(g),i.set(g.entry,v),{app:p,entry:g.entry,identity:Pt(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ue(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Fu(t){return(0,oe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:oe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function gn(t,e){let n=t.whenLive;if(typeof n!="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 n.call(t,{timeout:Fu(t.phase),signal:e})}async function Bu(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.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");t.detach()}async function os(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function mn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function cs(t,e=rn,n,r,o=pn,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let h=f.session.id;return typeof h=="string"&&h.length>0?h:null},p="lane",m=f=>{let h=Ve(f);if(!s||!h||h.app!==p)return null;let w=s.entryFor(h.key);if(!w)throw new W(`the lane behind this handle (${h.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:h.key,entry:w}},g=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let h=i.get(f);if(!h){let w={waiting:0,gone:new AbortController};d.set(f,w),h=(async()=>{if(await gn(f.session,w.gone.signal),w.gone.signal.aborted)throw mn(w.gone.signal);d.get(f)===w&&d.delete(f);let b=await _o(f.session,await e());return Object.assign(b,{sessionId:f.session.id})})(),i.set(f,h),h.then(b=>{i.get(f)===h&&(f.audioDispose=()=>b.dispose())},()=>{}),h.catch(()=>{i.get(f)===h&&i.delete(f)}),h.then(()=>{d.get(f)===w&&d.delete(f)},()=>{d.get(f)===w&&d.delete(f)})}return h},k=f=>{let h=l.get(f);return h||(h=(async()=>{let w=await v(f);return{appendInputAudio:(b,R)=>w.appendInputAudio(b,R),onOutputAudio:b=>w.onOutputAudio(b),sessionId:c(f)}})(),l.set(f,h),h.catch(()=>{l.get(f)===h&&l.delete(f)})),h},S=async(f,h,w,b=!1)=>{let R=()=>b?os(f.session):Bu(f.session);if(w?.aborted){let y=d.get(f);throw(i.get(f)===void 0||y!==void 0&&y.waiting===0)&&await R().catch(()=>{}),mn(w)}let E=h(f),A=d.get(f);return A!==void 0&&A.waiting++,w===void 0?E:new Promise((y,x)=>{let T=()=>{A!==void 0&&--A.waiting===0&&d.get(f)===A&&(A.gone.abort(),d.delete(f),i.delete(f),l.delete(f),R().catch(()=>{})),x(mn(w))};w.addEventListener("abort",T,{once:!0});let C=()=>w.removeEventListener("abort",T);E.then(B=>{C(),y(B)},B=>{C(),x(B)})})},_=async(f,h,w)=>{try{return await w}catch(b){throw(b instanceof W||b instanceof oe.SessionFailedError&&wr(b))&&(t.evict(f,h),b instanceof oe.SessionFailedError&&n?.(f,b.kind==="never-live"?"never-live":"create-failed")),b}};return{createResponse:Io({sessionFor:s?async f=>{let h=await t.resolveTargetFor(f);if(h.sharedApp)try{let w=await s.sessionFor(f,h);return{app:w.app,entry:w.entry,identity:w.identity}}catch(w){if(w instanceof en)return r?r.sessionFor(f):t.sessionFor(f);if(w instanceof fn)return console.error(`[pooler-fallback] pooler channel failed for ${f} (${w.name} ${w.code}: ${w.message}) \u2014 serving via the per-request path`),r?r.sessionFor(f):t.sessionFor(f);throw w}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,h)=>{s&&s.owns(h)?s.evict(h):r?r.evict(h):t.evict(f,h)},onAdmissionVerdict:(f,h,w)=>{wr(w)&&(s&&s.owns(h)?s.evict(h):r?r.markSessionDead(h):t.evict(f,h),n?.(f,w.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,h)=>{try{await gn(f.session);let w=Qo(gr(await f.responses.responses.create(h),f.gone),o);if(!r&&!s)return w;let b=f;return(async function*(){try{yield*w}catch(E){throw Zo(E)&&(s&&s.owns(b)?s.evict(b):r&&(E instanceof W&&!E.bindingLost?r.markSessionDead(b):r.evict(b))),E}finally{s&&s.owns(b)?s.release(b):r?.end(b)}})()}catch(w){throw s&&s.owns(f)?s.release(f):r&&r.end(f),w}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,h)=>t.supportsImages(f,h),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,h)=>{let{app:w,entry:b}=await t.sessionFor(f);return await _(w,b,S(b,v,h))},openAudioOn:async(f,h,w,b)=>{let R=m(f);if(R){let x=R.entry.session;return es(x)}let{app:E,entry:A}=await t.sessionForHandle(f);if(b&&A.session.phase?.name!=="live"){let x=A.session.phase?.name;b({status:x==="queued"||x==="waiting_for_capacity"?x:"pending",reason:`the dial's session is ${x??"not yet admitted"} \u2014 the connection waits for admission`})}let y=Ve(f)?.app.startsWith(Mt)??!1;return await _(E,A,S(A,k,h,y))},openTurnsOn:async function*(f,h){if(h?.aborted)throw mn(h);let w=await g(f);yield*Eo(w.session,h)},openVideoOn:async f=>{let h=m(f);if(h)return ns(h.entry.session);let{entry:w}=await t.sessionForHandle(f),b=u.get(w);return b||(b=Xn(w.session),u.set(w,b)),b},openVideo:async f=>{let{entry:h}=await t.sessionFor(f),w=u.get(h);return w||(w=Xn(h.session),u.set(h,w)),w},openVideoOut:async f=>{let{entry:h}=await t.sessionFor(f),w=a.get(h);return w||(w=So(h.session),a.set(h,w)),w},sessionHandle:async f=>{if(s){let h=await t.resolveTargetFor(f);if(h.sharedApp){let w=await s.sessionFor(f,h),b=c(w.entry);if(b===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Ct(p,b)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:w,entry:b}=await t.dedicatedSessionFor(f);return Ct(w,us(b))},releaseSessionHandle:f=>{let h=Ve(f);if(!h)return;if(h.app.startsWith(Mt)){(async()=>{let b=null;try{b=(await t.sessionForHandle(f)).entry}catch{return}await os(b.session).catch(()=>{}),await t.evict(h.app,b)})();return}if(!s||h.app!==p)return;let w=s.entryFor(h.key);w&&s.release(w)},endDedicatedSession:async f=>{let h=Ve(f);if(!h||!h.app.startsWith(Mt))return;let w=null;try{w=(await t.sessionForHandle(f)).entry}catch{return}if(typeof w.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let b=await w.session.end();return await t.evict(h.app,w),b},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:h,entry:w}=await t.sessionForHandle(f);await t.evict(h,w)},createResponseOn:async(f,h,w)=>{let b=await g(f);await gn(b.session);let R=w!==void 0&&m(f)?new kt({...b.session,consumerId:w},{sessionTag:w}):b.responses;return gr(await R.responses.create(h),b.gone)},onSessionEnd:async(f,h)=>{let w=m(f);if(w)return w.entry.gone.onGone(A=>h({timeLeftMs:null,reason:A.message}));let{entry:b}=await t.sessionForHandle(f),R=b.session;if(typeof R.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return R.onPhase(A=>{if(E||!Du.has(A.name))return;E=!0;let y=R.endsAt??null;h({timeLeftMs:y?Math.max(0,y.getTime()-Date.now()):null,reason:A.reason??`session ${A.name}`})})}}}var ba=require("http");var Os=require("crypto"),Ps=require("ws");var fs="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",qu=1007,ms=1008,Pe=1011,_n=1008,I=class extends Error{constructor(n,r=qu){super(n);this.closeCode=r}closeCode},re=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,hn=["setup","clientContent","realtimeInput","toolResponse"];function gs(t){let e;try{e=JSON.parse(t)}catch{throw new I("client message is not valid JSON")}let n=re(e);if(!n)throw new I("client message must be a JSON object");let r=hn.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!hn.includes(u));if(o.length>0)throw new I(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${hn.join(", ")}`);if(r.length!==1)throw new I(`client message must contain exactly one of ${hn.join(", ")} (got ${r.length})`);let s=r[0],i=re(n[s]);if(!i)throw new I(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function hs(t,e){if(typeof t=="string")return t;let n=re(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new I(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=re(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new I(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new I(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new I(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
7
+ `);let a=(n?it(n):[]).map(l=>{let d=s.filter(k=>k.model_id===l.model_id&&k.variant===l.variant),c=sn(d),p=at(d),m=or(d),g=Et(l.model_id,l.variant,i),S=ir(d);return Ge({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...S.published.length>0?{voices:[...S.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>an(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Ho(e,n,r,o=>this.warn(o))}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=ar(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Vo(`${r.modelId}:${r.variant}`,s).includes(n)}return Go(lr(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ne(Ot(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ne(Ot(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ne(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ne(Ot(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return Au(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Ot(n,r);return ir(o)}async imageModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds()){let i=Go(lr(s,e));i.length!==0&&r.push(Ge({...an(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Vo(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=At,r=[];for(let s of await this.availableIds())Ne(Xo(s,e))==="stt"&&r.push(an(s,e,n));let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ar(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Ne(i)!=="stt")continue;let u=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:at(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var De=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},$t=class extends De{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},pr=class extends De{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},be=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},dn=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new $t;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let a=r+n-Date.now();if(a<=0)throw new pr(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,a)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1,this.opts.onLease?.(n);let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.disposeDropped(e),this.signalDrain())}disposeDropped(e){this.opts.closeSlot(e).catch(()=>{})}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var fr=require("@urun-sh/core"),Se=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},pn=33e4;function Qo(t,e=pn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new cn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof W||l instanceof fr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof cn?(await r.return?.(void 0),new Se("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Se("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new Se("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var cn=class extends Error{constructor(){super("stream idle timeout")}};function Zo(t){return t instanceof Se?!1:t instanceof W?!0:t instanceof fr.SessionFailedError?t.kind==="transport-failed":!1}var Iu=require("http");var fn=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds};var mr=require("@urun-sh/core"),Tu="audio";function es(t){let e=t.streamEndpoint(Tu);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,mr.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,mr.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var ts=require("@urun-sh/core"),Ou="rt-video-in";function ns(t){let e=t.streamEndpoint(Ou);return{sendInputFrame:async n=>{e.send((0,ts.encodeStreamEnvelope)(n))}}}var Pu=3,Cu="llm",Mu=new Set(["paused","error"]);function rs(t,e,n){let r=t.doc(Cu),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" 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 i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<Pu||d(new W(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&Mu.has(c.name)&&d(new W(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`,{bindingLost:!0,reason:c.reason??null}))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*gr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var Lu=0,Nu=4,Uu=4;function ss(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Lu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Nu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Uu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function is(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return pn;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function hr(t,e,n,r){let o=t[n];if(typeof o!="function")throw new Error(`app "${e}" has no function "${n}" (set URUN_FUNCTION)`);let s=r?o(void 0,r):o();if(typeof s.end!="function")throw new Error(`app "${e}" function "${n}" returned a session without end()`);return s}function as(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l={...e.sharedApp?{sharedApp:!0}:{},...a,...r,presenceIdleMs:3e4},d=S=>({session:S,responses:new kt(S),gone:rs(S,n)});if(i.lane==="jwt"){let S=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(hr(S,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let S=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:x}=i,k=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),b=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(S,{baseUrl:x,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:k,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(b,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,yr.randomUUID)(),g=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(hr(g,e.appSlug,u,l))}function us(t){let e=t.session.id;if(typeof e!="string"||e.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 e}function wr(t){if(t.kind==="never-live")return!0;if(t.kind!=="create-failed")return!1;let e=t.status.error?.httpStatus,n=t.status.error?.code;return e===410||e===409&&(n==="cancelled"||n==="expired")?!0:n==="client_ended"}var Du=new Set(["error","paused"]);function ls(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=as(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new ln({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>zo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>vo(n):null),listPrices:n?()=>Mo(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return $o(i)}:e.lane==="api-key"?()=>Lo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:us});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ue({appSlug:t.defaultApp}))),s}function ds(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
8
+ `)},a=(d,c)=>{let p=o.get(c);if(p)return p;let m=new dn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,onLease:g=>g.session.activity?.(),openSlot:async g=>{let S=as(t,d,c,{concurrencyKey:g.concurrencyKey});return S.gone.onGone(x=>x.bindingLost?m.evict(S):m.markSessionDead(S)),await gn(S.session),u(`slot attached pool=${c} slot=${g.concurrencyKey} session=${S.session.id??"(no id)"}`),S},closeSlot:async g=>{g.gone.dispose(),g.audioDispose?.(),await g.session.end()},onDetach:(g,S)=>u(`slot detached pool=${c} slot=${g.concurrencyKey} reason=${S}`),terminalOpenFailure:g=>g instanceof oe.SessionFailedError&&wr(g)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);a(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){u(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ue(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ue(c),m=a(c,p);await l(c,p);let g=await m.acquire({timeoutMs:m.requestWaitMs}),S=i.get(g.entry)??[];return S.push(g),i.set(g.entry,S),{app:p,entry:g.entry,identity:Pt(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ue(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Fu(t){return(0,oe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:oe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function gn(t,e){let n=t.whenLive;if(typeof n!="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 n.call(t,{timeout:Fu(t.phase),signal:e})}async function Bu(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.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");t.detach()}async function os(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function mn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function cs(t,e=rn,n,r,o=pn,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new Map,c=new WeakMap,p=f=>{let y=f.session.id;return typeof y=="string"&&y.length>0?y:null},m="lane",g=f=>{let y=Ve(f);if(!s||!y||y.app!==m)return null;let h=s.entryFor(y.key);if(!h)throw new W(`the lane behind this handle (${y.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:y.key,entry:h}},S=async f=>g(f)?.entry??(await t.sessionForHandle(f)).entry,x=f=>{let y=i.get(f);if(!y){let h={waiting:0,gone:new AbortController};c.set(f,h),y=(async()=>{if(await gn(f.session,h.gone.signal),h.gone.signal.aborted)throw mn(h.gone.signal);c.get(f)===h&&c.delete(f);let _=await _o(f.session,await e());return Object.assign(_,{sessionId:f.session.id})})(),i.set(f,y),y.then(_=>{i.get(f)===y&&(f.audioDispose=()=>_.dispose())},()=>{}),y.catch(()=>{i.get(f)===y&&i.delete(f)}),y.then(()=>{c.get(f)===h&&c.delete(f)},()=>{c.get(f)===h&&c.delete(f)})}return y},k=f=>{let y=l.get(f);return y||(y=(async()=>{let h=await x(f);return{appendInputAudio:(_,R)=>h.appendInputAudio(_,R),onOutputAudio:_=>h.onOutputAudio(_),sessionId:p(f)}})(),l.set(f,y),y.catch(()=>{l.get(f)===y&&l.delete(f)})),y},b=async(f,y,h,_=!1)=>{let R=()=>_?os(f.session):Bu(f.session);if(h?.aborted){let E=c.get(f);throw(i.get(f)===void 0||E!==void 0&&E.waiting===0)&&await R().catch(()=>{}),mn(h)}let T=y(f),w=c.get(f);return w!==void 0&&w.waiting++,h===void 0?T:new Promise((E,A)=>{let C=()=>{w!==void 0&&--w.waiting===0&&c.get(f)===w&&(w.gone.abort(),c.delete(f),i.delete(f),l.delete(f),R().catch(()=>{})),A(mn(h))};h.addEventListener("abort",C,{once:!0});let q=()=>h.removeEventListener("abort",C);T.then(B=>{q(),E(B)},B=>{q(),A(B)})})},v=async(f,y,h)=>{try{return await h}catch(_){throw(_ instanceof W||_ instanceof oe.SessionFailedError&&wr(_))&&(t.evict(f,y),_ instanceof oe.SessionFailedError&&n?.(f,_.kind==="never-live"?"never-live":"create-failed")),_}};return{createResponse:Io({sessionFor:s?async f=>{let y=await t.resolveTargetFor(f);if(y.sharedApp)try{let h=await s.sessionFor(f,y);return{app:h.app,entry:h.entry,identity:h.identity}}catch(h){if(h instanceof en)return r?r.sessionFor(f):t.sessionFor(f);if(h instanceof fn)return console.error(`[pooler-fallback] pooler channel failed for ${f} (${h.name} ${h.code}: ${h.message}) \u2014 serving via the per-request path`),r?r.sessionFor(f):t.sessionFor(f);throw h}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>p(f),evict:(f,y)=>{s&&s.owns(y)?s.evict(y):r?r.evict(y):t.evict(f,y)},onAdmissionVerdict:(f,y,h)=>{wr(h)&&(s&&s.owns(y)?s.evict(y):r?r.markSessionDead(y):t.evict(f,y),n?.(f,h.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,y)=>{try{await gn(f.session);let h=Qo(gr(await f.responses.responses.create(y),f.gone),o);if(!r&&!s)return h;let _=f;return(async function*(){try{yield*h}catch(T){throw Zo(T)&&(s&&s.owns(_)?s.evict(_):r&&(T instanceof W&&!T.bindingLost?r.markSessionDead(_):r.evict(_))),T}finally{s&&s.owns(_)?s.release(_):r?.end(_)}})()}catch(h){throw s&&s.owns(f)?s.release(f):r&&r.end(f),h}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,y)=>t.supportsImages(f,y),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,y)=>{let{app:h,entry:_}=await t.sessionFor(f);return await v(h,_,b(_,x,y))},openAudioOn:async(f,y,h,_)=>{let R=g(f);if(R){let A=R.entry.session;return es(A)}let{app:T,entry:w}=await t.sessionForHandle(f);if(_&&w.session.phase?.name!=="live"){let A=w.session.phase?.name;_({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let E=Ve(f)?.app.startsWith(Mt)??!1;return await v(T,w,b(w,k,y,E))},openTurnsOn:async function*(f,y){if(y?.aborted)throw mn(y);let h=await S(f);yield*Eo(h.session,y)},openVideoOn:async f=>{let y=g(f);if(y)return ns(y.entry.session);let{entry:h}=await t.sessionForHandle(f),_=u.get(h);return _||(_=Xn(h.session),u.set(h,_)),_},openVideo:async f=>{let{entry:y}=await t.sessionFor(f),h=u.get(y);return h||(h=Xn(y.session),u.set(y,h)),h},openVideoOut:async f=>{let{entry:y}=await t.sessionFor(f),h=a.get(y);return h||(h=So(y.session),a.set(y,h)),h},sessionHandle:async f=>{if(s){let y=await t.resolveTargetFor(f);if(y.sharedApp){let h=await s.sessionFor(f,y),_=p(h.entry);if(_===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Ct(m,_)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:h,entry:_}=await t.dedicatedSessionFor(f);return Ct(h,us(_))},touchSessionPresence:(f,y)=>{(async()=>{let h=d.get(f);h||(h=new Map,d.set(f,h)),h.set(y,Date.now());let _=null;try{_=await S(f)}catch{return}_.session.activity?.()})()},detachSessionPresence:(f,y)=>{(async()=>{let h=d.get(f);if(h?.delete(y),h&&h.size===0&&d.delete(f),h&&h.size>0)return;let _=null;try{_=await S(f)}catch{return}_.session.presenceDetach?.()})()},releaseSessionHandle:f=>{let y=Ve(f);if(!y)return;if(y.app.startsWith(Mt)){(async()=>{let _=null;try{_=(await t.sessionForHandle(f)).entry}catch{return}await os(_.session).catch(()=>{}),await t.evict(y.app,_)})();return}if(!s||y.app!==m)return;let h=s.entryFor(y.key);h&&s.release(h)},endDedicatedSession:async f=>{let y=Ve(f);if(!y||!y.app.startsWith(Mt))return;let h=null;try{h=(await t.sessionForHandle(f)).entry}catch{return}if(typeof h.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let _=await h.session.end();return await t.evict(y.app,h),_},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:y,entry:h}=await t.sessionForHandle(f);await t.evict(y,h)},createResponseOn:async(f,y,h)=>{let _=await S(f);await gn(_.session);let R=h!==void 0&&g(f)?new kt({..._.session,consumerId:h},{sessionTag:h}):_.responses;return gr(await R.responses.create(y),_.gone)},onSessionEnd:async(f,y)=>{let h=g(f);if(h)return h.entry.gone.onGone(w=>y({timeLeftMs:null,reason:w.message}));let{entry:_}=await t.sessionForHandle(f),R=_.session;if(typeof R.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let T=!1;return R.onPhase(w=>{if(T||!Du.has(w.name))return;T=!0;let E=R.endsAt??null;y({timeLeftMs:E?Math.max(0,E.getTime()-Date.now()):null,reason:w.reason??`session ${w.name}`})})}}}var ba=require("http");var Os=require("crypto"),Ps=require("ws");var fs="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",qu=1007,ms=1008,Pe=1011,_n=1008,I=class extends Error{constructor(n,r=qu){super(n);this.closeCode=r}closeCode},re=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,hn=["setup","clientContent","realtimeInput","toolResponse"];function gs(t){let e;try{e=JSON.parse(t)}catch{throw new I("client message is not valid JSON")}let n=re(e);if(!n)throw new I("client message must be a JSON object");let r=hn.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!hn.includes(u));if(o.length>0)throw new I(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${hn.join(", ")}`);if(r.length!==1)throw new I(`client message must contain exactly one of ${hn.join(", ")} (got ${r.length})`);let s=r[0],i=re(n[s]);if(!i)throw new I(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function hs(t,e){if(typeof t=="string")return t;let n=re(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new I(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=re(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new I(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new I(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new I(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
9
9
  `)}var ju={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},We="urun.videoOut";function ys(t){return{framing:bo,codec:t}}function ws(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[We]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Hu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Gu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",We],ps=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Vu(t){let e=re(t);if(!e)throw new I("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new I(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=re(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new I("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new I(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new I("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!ps.includes(e.activityHandling))throw new I(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ps.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Ju=["temperature","maxOutputTokens","responseModalities"];function _s(t){for(let[c,p]of Object.entries(Hu))if(t[c]!==void 0)throw new I(p);for(let c of Object.keys(t))if(!Gu.includes(c))throw new I(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new I('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=re(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new I("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Ju.includes(c))throw new I(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new I("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new I("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new I(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:hs(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new I("setup.tools must be an array");u=[];for(let c of t.tools){let p=re(c);if(!p)throw new I("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new I(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new I("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let g=re(m);if(!g||typeof g.name!="string")throw new I("functionDeclarations entries require a string name");u.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=re(t.sessionResumption);if(!c)throw new I("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new I(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new I("sessionResumption.handle must be a non-empty string when present");a={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?ju:Vu(t.realtimeInputConfig),d=!1;if(t[We]!==void 0){if(!re(t[We]))throw new I(`setup["${We}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:u,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:a,videoOut:d}}function vs(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function bs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ss(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new I(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new I("clientContent.turns must be an array");let n=[];for(let r of e){let o=re(r);if(!o)throw new I("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new I(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:hs(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var yn=16e3,ks=24e3,Wu=`audio/pcm;rate=${ks}`,xs=Buffer.alloc(960).toString("base64");function Ku(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let u=0;u<r;u++){let a=u*s,l=Math.floor(a);if(l>=i){o[u]=t[i];continue}let d=a-l;o[u]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function zu(t){let e=re(t);if(!e)throw new I("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new I("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Yu(t){let e=re(t);if(!e)throw new I("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==yn)throw new I(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${yn} Hz (audio/pcm;rate=${yn})`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new I(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Ku(o,yn,ks);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Rs(t){if(t.mediaChunks!==void 0)throw new I('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new I("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=re(t[o]);if(!s||Object.keys(s).length!==0)throw new I(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new I(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new I(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Yu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:zu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new I("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new I("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Es(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new I(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new I("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=re(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new I("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function As(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Is(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Wu,data:t}}]}}}}function Ts(t){let e=re(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=re(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=re(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=re(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new I(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Pe);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new I(`upstream function_call arguments are not valid JSON: ${c}`,Pe)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let u=re(e.usage),a={serverContent:{turnComplete:!0}};if(u){let l={};typeof u.input_tokens=="number"&&(l.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(l.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(l.totalTokenCount=u.total_tokens),Object.keys(l).length>0&&(a.usageMetadata=l)}return i.push(a),{messages:i,assistantItems:o}}var Xu=256,_r=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Xu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Qu="local",Lt=t=>t.slice(0,120),vr=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 J){this.ws.close(ms,Lt(e.message));return}if(e instanceof W){this.ws.close(_n,Lt(e.message));return}if(e instanceof I){this.ws.close(e.closeCode,Lt(e.message));return}this.ws.close(Pe,Lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=gs(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 I(`"${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}=Ss(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Rs(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:xs);return}this.transcript.push(...Es(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new I("setup may only be sent once, as the first client message");let n=_s(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new I("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",_n);if(s.model!==n.model)throw new I(`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 I("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 I(`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`,_n);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),u=i.onOutputFrame(l=>this.send(ws(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[We]=ys(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 I("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new I("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Pe);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Is(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 I("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new I("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Pe);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 I(`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 I("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 I("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=(0,Os.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(vs(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(bs(e.timeLeftMs)),this.ws.close(Pe,Lt(`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 a of r){if(n.interrupted)break;let l=a;if(l.type==="error")throw new I(`upstream error: ${JSON.stringify(l)}`,Pe);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=As(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new I("upstream produced no response.completed event",Pe);let{messages:i,assistantItems:u}=Ts(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ke=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Zu(t,e,n){let r=new Set;(a=>{if(typeof a=="string")a!==""&&r.add(a);else if(Array.isArray(a))for(let l of a)l!==""&&r.add(l)})(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 Ke(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 Ke(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 u;for(let a of r)u=a;if(u===void 0&&n)throw new Ke(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function Cs(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 Ps.WebSocketServer({noServer:!0}),o=new _r;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===fs&&(u.on("error",()=>{}),(async()=>{let d=Zu(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ke(401,"invalid local proxy api key");c={clients:e.clients,scope:Qu}}r.handleUpgrade(i,u,a,p=>{new vr(p,c,o)})})().catch(d=>{let c=502;(d instanceof Ke||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);u.destroyed||(u.write(`HTTP/1.1 ${c} ${p}\r
10
10
  Connection: close\r
11
11
  \r
12
12
  ${m}\r
13
13
  `),u.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,u)=>r.close(a=>a===void 0?i():u(a)))})(),s)}var Be=require("ws");var Ms=require("crypto"),$s="Inference-Id";function Nt(){return(0,Ms.randomUUID)()}function br(t){return t==="/v1"||t.startsWith("/v1/")}function Ls(t,e){if(!br(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 Ut(t){return`resp_${t}`}function Ns(t){return`chatcmpl-${t}`}function Us(t){return`msg_${t}`}function he(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Ds(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,output_seconds:t.turn.outputSeconds??null,session_seconds:null,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,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Fs(t){return`${JSON.stringify(t)}
14
- `}var el=256,tl=128;function ue(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,tl)}var ze=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>=el?"(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,u=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.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)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),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}}}},nl=256;function rl(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 Ye=class extends Error{},ut=class{conversations=new Map;thread(e,n){let r=rl(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ye(`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<=nl)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Bs=new WeakMap;function Dt(t){let e=Bs.get(t);return e||(e=new ut,Bs.set(t,e)),e}function lt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Te(t){return t.find(e=>e.type==="response.completed")?.response??null}function dt(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 Fe=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}))}},ol=["<tool_call>","<function="];function sl(t){return ol.find(e=>t.includes(e))}function Xe(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 Qe(t,e,n){if(!(!t||e>0))return sl(n)}function ct(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 Ce(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function il(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 Sr(t,e){let n=il(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ye=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function pt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ye?new ye(n.message,"previous_response_not_found",400,"previous_response_id"):new ye(String(n instanceof Error?n.message:n),"invalid_input")}}function qs(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function kr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ye("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}:{},...qs(e)!==void 0?{response_format:qs(e)}:{}},o)}async function Ft(t){let{body:e,clients:n,store:r,stats:o}=t,s=pt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ue(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await kr(n,e,s,!0,c?he(c):void 0);return{responseId:i,events:dl({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function al(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?ll(o[i++],a):a),...ul(r,n)]}function ul(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function ll(t,e){let n=u=>u!==null&&typeof u=="object"&&u.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(u=>n(u)?{...u,text:s.text}:u),i}async function*dl(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,m=!1,g=!1,v=0;function*k(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let S=[],_=(M,q)=>{S.push({output_index:M,item:q})},f=!1,h=0,w="",b=0,R="";function*E(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:w,output_index:h,content_index:0,text:R};let M={id:w,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:R}],status:"completed"};yield{type:"response.output_item.done",output_index:h,item:M},_(h,M),R=""}let A=!1,y=0,x="",T=0,C="",B="";function*V(M){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:x,output_index:y,content_index:0,text:C},yield{type:"response.content_part.done",item_id:x,output_index:y,content_index:0,part:{type:"output_text",text:C}};let q={id:x,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:y,item:q},_(y,q),C=""}let N=new Fe,$=null,D=-1;function*j(M){if(!$)return;let q=$;$=null,yield{type:"response.function_call_arguments.done",item_id:q.fcId,output_index:q.outputIndex,arguments:q.args};let z={id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:q.args,status:M};yield{type:"response.output_item.done",output_index:q.outputIndex,item:z},_(q.outputIndex,z)}let X=!1;for await(let M of l.track(e,o,t.turn)){d.push(M);let q=String(M.type??"");if(q==="response.created"||q==="response.in_progress"){m=!0,yield c(M);continue}if(q==="response.output_item.added"){g=!0,yield c(M);continue}if(q==="response.reasoning_text.delta"&&!g){yield*k(),f||(f=!0,h=v++,b+=1,w=b===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${b}`,yield{type:"response.output_item.added",output_index:h,item:{id:w,type:"reasoning",summary:[],content:[],status:"in_progress"}}),R+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:w,output_index:h,content_index:0,delta:M.delta};continue}if(q==="response.output_text.delta"&&!g){yield*k(),yield*E(),A||(A=!0,y=v++,T+=1,x=T===1?p:`${p}_${T}`,yield{type:"response.output_item.added",output_index:y,item:{id:x,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:x,output_index:y,content_index:0,part:{type:"output_text",text:""}}),C+=String(M.delta??""),B+=String(M.delta??""),yield{type:q,item_id:x,output_index:y,content_index:0,delta:M.delta};continue}let z=g?null:dt(M);if(z){if(yield*k(),yield*E(),yield*V("completed"),N.add(z),z.tool_index!==D){yield*j("completed"),D=z.tool_index;let je=v++;$={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:je,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:je,item:{id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:"",status:"in_progress"}}}$&&(z.call_id&&($.callId=z.call_id),z.name&&($.name=z.name),$.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:$.fcId,output_index:$.outputIndex,delta:z.delta});continue}if(q==="response.completed"&&!g){let je=lt(M.response),rt=Qe(s,N.size+je.length,B);if(rt){X=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(o,rt)}};break}if(yield*E(),yield*V("completed"),yield*j("completed"),N.size===0)for(let ne of je){let ve=v++,He=ne.id??ne.call_id??`fc_${ve}`,Jn=ne.arguments??"",io={id:He,type:"function_call",call_id:ne.call_id??He,name:ne.name??""};yield{type:"response.output_item.added",output_index:ve,item:{...io,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:He,output_index:ve,delta:Jn},yield{type:"response.function_call_arguments.done",item_id:He,output_index:ve,arguments:Jn};let ao={...io,arguments:Jn,status:"completed"};yield{type:"response.output_item.done",output_index:ve,item:ao},_(ve,ao)}let Q=al(S,M.response);yield Q.length>0?c({...M,response:{...M.response,output:Q}}):c(M);continue}yield c(M)}if(yield*E(),yield*V("incomplete"),yield*j("incomplete"),i&&!X){let M=Te(d);a.remember(r,n,Sr(M,ct(d,M)),u)}}var cl=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ke(t){return!cl.some(e=>e.test(t))}function xe(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function fe(t,e){if(t instanceof W)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=js(t);return n||{message:xe(e?.inferenceId??null),redacted:!0}}function js(t){return t instanceof Le?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof ee?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof J?{message:t.message,redacted:!1}:t instanceof Ie?{message:t.message,redacted:!1}:t instanceof De?{message:t.message,redacted:!1}:t instanceof Se?ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof be?{message:t.message,redacted:!1}:t instanceof ce?{message:t.message,redacted:!1}:null}function ft(t,e,n){let r=n??(i=>console.error(i)),o=js(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed while serving this request`)}function Oe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ke(e)?e:null}function we(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var pl="/v1/responses",fl=64*1024*1024,ml=8*1024*1024,gl=16,Hs=32,Gs=3600*1e3,hl=/^[A-Za-z0-9._-]{1,256}$/;function le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var yl=le(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 Er(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function wl(t){for(;t.bufferedAmount>ml&&t.readyState===Be.WebSocket.OPEN;){let{promise:e,resolve:n}=Er();setTimeout(n,5),await e}}var xr=class extends ut{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 Ye))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)}},Rr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new xr(Dt(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Gs/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Gs).unref?.()}ws;clients;stats;statusOf;operatorLog;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(le(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(le(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(le(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(le(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(le(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(le(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"||!hl.test(o.stream_id)){this.sendFrame(yl);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Hs){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Hs}). 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),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=Nt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Ft({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ut(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Be.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await wl(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=Nt(),o=Ut(r);try{let s=pt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:we(e);if(e instanceof ye)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof J)return le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof W){let u=fe(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),le(s.status,{type:s.openaiType,message:o},n);let i=fe(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Oe(o),u=i??xe(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=gl;){let{promise:e,resolve:n}=Er();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!==Be.WebSocket.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!==Be.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function vn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
14
+ `}var el=256,tl=128;function ue(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,tl)}var ze=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>=el?"(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,u=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.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)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),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}}}},nl=256;function rl(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 Ye=class extends Error{},ut=class{conversations=new Map;thread(e,n){let r=rl(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ye(`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<=nl)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Bs=new WeakMap;function Dt(t){let e=Bs.get(t);return e||(e=new ut,Bs.set(t,e)),e}function lt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Te(t){return t.find(e=>e.type==="response.completed")?.response??null}function dt(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 Fe=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}))}},ol=["<tool_call>","<function="];function sl(t){return ol.find(e=>t.includes(e))}function Xe(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 Qe(t,e,n){if(!(!t||e>0))return sl(n)}function ct(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 Ce(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function il(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 Sr(t,e){let n=il(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ye=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function pt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ye?new ye(n.message,"previous_response_not_found",400,"previous_response_id"):new ye(String(n instanceof Error?n.message:n),"invalid_input")}}function qs(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function kr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ye("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}:{},...qs(e)!==void 0?{response_format:qs(e)}:{}},o)}async function Ft(t){let{body:e,clients:n,store:r,stats:o}=t,s=pt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ue(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await kr(n,e,s,!0,c?he(c):void 0);return{responseId:i,events:dl({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function al(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?ll(o[i++],a):a),...ul(r,n)]}function ul(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function ll(t,e){let n=u=>u!==null&&typeof u=="object"&&u.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(u=>n(u)?{...u,text:s.text}:u),i}async function*dl(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,m=!1,g=!1,S=0;function*x(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let k=[],b=(M,j)=>{k.push({output_index:M,item:j})},v=!1,f=0,y="",h=0,_="";function*R(){if(!v)return;v=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:f,content_index:0,text:_};let M={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:_}],status:"completed"};yield{type:"response.output_item.done",output_index:f,item:M},b(f,M),_=""}let T=!1,w=0,E="",A=0,C="",q="";function*B(M){if(!T)return;T=!1,yield{type:"response.output_text.done",item_id:E,output_index:w,content_index:0,text:C},yield{type:"response.content_part.done",item_id:E,output_index:w,content_index:0,part:{type:"output_text",text:C}};let j={id:E,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:w,item:j},b(w,j),C=""}let N=new Fe,$=null,D=-1;function*H(M){if(!$)return;let j=$;$=null,yield{type:"response.function_call_arguments.done",item_id:j.fcId,output_index:j.outputIndex,arguments:j.args};let z={id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:j.args,status:M};yield{type:"response.output_item.done",output_index:j.outputIndex,item:z},b(j.outputIndex,z)}let X=!1;for await(let M of l.track(e,o,t.turn)){d.push(M);let j=String(M.type??"");if(j==="response.created"||j==="response.in_progress"){m=!0,yield c(M);continue}if(j==="response.output_item.added"){g=!0,yield c(M);continue}if(j==="response.reasoning_text.delta"&&!g){yield*x(),v||(v=!0,f=S++,h+=1,y=h===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${h}`,yield{type:"response.output_item.added",output_index:f,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),_+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:f,content_index:0,delta:M.delta};continue}if(j==="response.output_text.delta"&&!g){yield*x(),yield*R(),T||(T=!0,w=S++,A+=1,E=A===1?p:`${p}_${A}`,yield{type:"response.output_item.added",output_index:w,item:{id:E,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:E,output_index:w,content_index:0,part:{type:"output_text",text:""}}),C+=String(M.delta??""),q+=String(M.delta??""),yield{type:j,item_id:E,output_index:w,content_index:0,delta:M.delta};continue}let z=g?null:dt(M);if(z){if(yield*x(),yield*R(),yield*B("completed"),N.add(z),z.tool_index!==D){yield*H("completed"),D=z.tool_index;let je=S++;$={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:je,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:je,item:{id:$.fcId,type:"function_call",call_id:$.callId??$.fcId,name:$.name??"",arguments:"",status:"in_progress"}}}$&&(z.call_id&&($.callId=z.call_id),z.name&&($.name=z.name),$.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:$.fcId,output_index:$.outputIndex,delta:z.delta});continue}if(j==="response.completed"&&!g){let je=lt(M.response),rt=Qe(s,N.size+je.length,q);if(rt){X=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(o,rt)}};break}if(yield*R(),yield*B("completed"),yield*H("completed"),N.size===0)for(let ne of je){let ve=S++,He=ne.id??ne.call_id??`fc_${ve}`,Jn=ne.arguments??"",io={id:He,type:"function_call",call_id:ne.call_id??He,name:ne.name??""};yield{type:"response.output_item.added",output_index:ve,item:{...io,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:He,output_index:ve,delta:Jn},yield{type:"response.function_call_arguments.done",item_id:He,output_index:ve,arguments:Jn};let ao={...io,arguments:Jn,status:"completed"};yield{type:"response.output_item.done",output_index:ve,item:ao},b(ve,ao)}let Q=al(k,M.response);yield Q.length>0?c({...M,response:{...M.response,output:Q}}):c(M);continue}yield c(M)}if(yield*R(),yield*B("incomplete"),yield*H("incomplete"),i&&!X){let M=Te(d);a.remember(r,n,Sr(M,ct(d,M)),u)}}var cl=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ke(t){return!cl.some(e=>e.test(t))}function xe(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function fe(t,e){if(t instanceof W)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=js(t);return n||{message:xe(e?.inferenceId??null),redacted:!0}}function js(t){return t instanceof Le?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof ee?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof J?{message:t.message,redacted:!1}:t instanceof Ie?{message:t.message,redacted:!1}:t instanceof De?{message:t.message,redacted:!1}:t instanceof Se?ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof be?{message:t.message,redacted:!1}:t instanceof ce?{message:t.message,redacted:!1}:null}function ft(t,e,n){let r=n??(i=>console.error(i)),o=js(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed while serving this request`)}function Oe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ke(e)?e:null}function we(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var pl="/v1/responses",fl=64*1024*1024,ml=8*1024*1024,gl=16,Hs=32,Gs=3600*1e3,hl=/^[A-Za-z0-9._-]{1,256}$/;function le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var yl=le(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 Er(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function wl(t){for(;t.bufferedAmount>ml&&t.readyState===Be.WebSocket.OPEN;){let{promise:e,resolve:n}=Er();setTimeout(n,5),await e}}var xr=class extends ut{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 Ye))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)}},Rr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new xr(Dt(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Gs/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Gs).unref?.()}ws;clients;stats;statusOf;operatorLog;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(le(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(le(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(le(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(le(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(le(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(le(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"||!hl.test(o.stream_id)){this.sendFrame(yl);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Hs){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Hs}). 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),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=Nt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Ft({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ut(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Be.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await wl(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=Nt(),o=Ut(r);try{let s=pt(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:we(e);if(e instanceof ye)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof J)return le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof W){let u=fe(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),le(s.status,{type:s.openaiType,message:o},n);let i=fe(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Oe(o),u=i??xe(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=gl;){let{promise:e,resolve:n}=Er();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!==Be.WebSocket.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!==Be.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function vn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
15
15
  `;t.end(`HTTP/1.1 ${e} ${r}\r
16
16
  Connection: close\r
17
17
  Content-Type: text/plain; charset=utf-8\r
18
18
  Content-Length: ${Buffer.byteLength(o)}\r
19
19
  \r
20
- ${o}`)}function Vs(t,e){let n=new Be.WebSocketServer({noServer:!0,maxPayload:fl}),r=new ze,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{vn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==pl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){vn(c,401,"invalid local proxy api key");return}let v;try{v=await u(d)}catch(k){let S=e.statusOf?.(k)??null;vn(c,S?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,k=>{s.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new Rr(k,v,r,e.statusOf,e.operatorLog??(S=>console.error(S)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&vn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Er();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Be.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var jr=require("@urun-sh/core");var Js=require("@urun-sh/core"),_l={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},vl={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Bt(t,e){let n=vl[t.code];return e?`${n} (${e})`:n}function bn(t){if(t==null)return null;let e=_l[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Sn(t){if(t.kind==="create-failed")return bn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Js.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return bn(e?"cold_start_exceeded":"queue_timeout")}var Ks=ot(require("os"),1),zs=ot(require("path"),1),Ys=require("url"),Xs=require("util");var Ws="0.6.49";var Qs=4141,Sl=Ws,xn={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 Tr(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 Zs(t,e,n){let r={...t,...Tr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function ei(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(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function ti(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ni(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function ri(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=(0,Ys.fileURLToPath)(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 oi(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 si(t){if(t[0]!=="--port")return null;let e=oi(t[1]);return t.splice(0,2),e}function Or(t){let e=t.indexOf("--port");if(e===-1)return Qs;let n=oi(t[e+1]);return t.splice(e,2),n}function ii(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 Ar(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 mt(t){let e=kl(Ar(t,"URUN_BASE_URL")),n=Ar(t,"URUN_ORG_ID"),r=Ar(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?kn(s,"URUN_API_URL"):Ko,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?kn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,gatewayUrl:d}}}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 kl(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 kn(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 Pr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Sl}}function xl(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 Rl=250;async function Cr(t,e=Rl){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:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var ai=2e3;async function El(t,e=ai){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 ui(t,e,n=Qs,r=ai){if(t!=null)return{mode:"spawn",port:t};let o=await Cr(n);if(o!==null&&xl(o,e)){let s=await El(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 Mr(t,e=Ks.default.homedir()){return zs.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Ir=["log","info","warn","error","debug","trace"];function li(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Ir.map(u=>[u,n[u]]));for(let u of Ir)n[u]=(...a)=>{t.write(`${(0,Xs.format)(...a)}
20
+ ${o}`)}function Vs(t,e){let n=new Be.WebSocketServer({noServer:!0,maxPayload:fl}),r=new ze,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{vn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==pl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){vn(c,401,"invalid local proxy api key");return}let S;try{S=await u(d)}catch(x){let k=e.statusOf?.(x)??null;vn(c,k?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,x=>{s.delete(c),o.add(x),x.on("close",()=>o.delete(x));try{new Rr(x,S,r,e.statusOf,e.operatorLog??(k=>console.error(k)))}catch{o.delete(x),x.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&vn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Er();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Be.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var jr=require("@urun-sh/core");var Js=require("@urun-sh/core"),_l={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},vl={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Bt(t,e){let n=vl[t.code];return e?`${n} (${e})`:n}function bn(t){if(t==null)return null;let e=_l[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Sn(t){if(t.kind==="create-failed")return bn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Js.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return bn(e?"cold_start_exceeded":"queue_timeout")}var Ks=ot(require("os"),1),zs=ot(require("path"),1),Ys=require("url"),Xs=require("util");var Ws="0.6.51";var Qs=4141,Sl=Ws,xn={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 Tr(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 Zs(t,e,n){let r={...t,...Tr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function ei(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(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function ti(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ni(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function ri(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=(0,Ys.fileURLToPath)(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 oi(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 si(t){if(t[0]!=="--port")return null;let e=oi(t[1]);return t.splice(0,2),e}function Or(t){let e=t.indexOf("--port");if(e===-1)return Qs;let n=oi(t[e+1]);return t.splice(e,2),n}function ii(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 Ar(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 mt(t){let e=kl(Ar(t,"URUN_BASE_URL")),n=Ar(t,"URUN_ORG_ID"),r=Ar(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?kn(s,"URUN_API_URL"):Ko,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?kn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,gatewayUrl:d}}}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 kl(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 kn(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 Pr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Sl}}function xl(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 Rl=250;async function Cr(t,e=Rl){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:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var ai=2e3;async function El(t,e=ai){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 ui(t,e,n=Qs,r=ai){if(t!=null)return{mode:"spawn",port:t};let o=await Cr(n);if(o!==null&&xl(o,e)){let s=await El(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 Mr(t,e=Ks.default.homedir()){return zs.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Ir=["log","info","warn","error","debug","trace"];function li(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Ir.map(u=>[u,n[u]]));for(let u of Ir)n[u]=(...a)=>{t.write(`${(0,Xs.format)(...a)}
21
21
  `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Ir)n[u]=i[u]}}var Al=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function di(t){let e=t?.code;return typeof e=="string"&&Al.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(di(n))return!1;throw n}}function ci(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{di(i)&&(e[r]=!0);let u=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(u??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
22
22
  `)}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 pi(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}
23
23
  `)}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}
24
24
  `)}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
25
- `)}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 fi(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}`}var Ht=require("ws");var yi=require("@urun-sh/core");var gi=require("crypto");function O(t){return`${t}_${(0,gi.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Rn=4*1024*1024,$r=8*1024*1024,Lr=512,En=20*1024*1024;function Z(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Me(t,e){return{type:"server_error",code:t,message:e}}function K(t){return{type:"error",event_id:O("event"),error:t}}function Nr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Il={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Tl={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ol={format:!0,voice:!0,speed:!0};function Pl(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function gt(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function mi(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Cl=10;function Ur(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Cl})}function qt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in Il));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=gt(o.modalities,"modalities"),a=gt(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new P("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new P(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new P('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new P(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=gt(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Pl(a))throw new P(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new P("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new P("instructions must be a string or null","instructions");i.instructions=Ur(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new P(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new P("temperature must be a finite number or null","temperature");i.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 P(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new P("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new P("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new P("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new P(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new P(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new P("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 P("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new P(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new P("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 l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Tl))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&mi(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=qt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=qt({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new P("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ol))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&mi(d.format,"audio.output.format"),d.speed!==void 0)throw new P("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 i.voice;else{if(typeof d.voice!="string")throw new P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function An(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Dr(t,e){let n=t;if(!n||typeof n!="object")throw new P("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 P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:O("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 P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("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 P("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 P(`${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 P("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 P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new P("input_image content is only valid on user message items","item.content.type","invalid_request");let u=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof u!="string"||u.length===0)throw new P("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!u.startsWith("data:image/"))throw new P("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let a=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:u,...a!==void 0?{detail:a}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:O("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function In(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 Ml=1001,$l=1011,Ll=15e3,Nl=3e5;var Tn=class extends Error{},On=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ze=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},Fr=t=>t.slice(0,120),Ul=/^[A-Za-z0-9+/=]*$/,Dl=2;function Fl(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Dl)return!1;return!0}var jt=class{id=O("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Nr();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Ll,this.responseDeadlineMs=e.responseDeadlineMs??Nl,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===dr&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:O("event"),session:An(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:O("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof W&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(K(Me("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:O("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:O("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:O("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:O("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=O("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(Z("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Rn){this.fail(Z("frame_too_large",`frame exceeds the ${Rn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Z("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Z("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(K({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Tn){this.fail(Me(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
26
- ${o?.stack??we(o)}`),this.send(K(Me(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let n=qt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(K(Z("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:O("event"),session:An(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Dr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(K(Z("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:O("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(K(Z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:O("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(K(Z("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:O("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(K(Z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ul.test(e.audio)){this.send(K(Z("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>En){this.send(K(Z("buffer_full",`uncommitted input audio exceeds the ${En}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:O("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(K(Z("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=O("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(K(Z("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(K(Z("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(K(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,Fr("session ended by client"))}catch{}});return}default:this.send(K(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(K(Z("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Tn("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(K({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,u=new Promise((d,c)=>{i=setTimeout(()=>c(new On),this.turnStallMs)}),a=n.next();a.catch(()=>{}),s=await(r?Promise.race([a,u,r]):Promise.race([a,u])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}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,...u}=e;return await o.createResponse({...u,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(K(Z("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?gt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?gt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(K(Z("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let i=()=>{},u=new Promise((R,E)=>{i=()=>E(new Ze)});this.turnCancelled=u,this.wakeTurnCancelled=()=>i(),u.catch(()=>{});let a=()=>{},l=new Promise((R,E)=>{a=()=>E(new Ze)});this.turnDialGate=l,this.wakeTurnDialGate=()=>a(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=O("req"),p=`resp_${c}`;this.activeResponseId=p,this.activeRequestId=c;let m=this.binding.composite===!0,g=m?0:this.items.length,v=m?null:In(this.items),k=Ur(typeof n.instructions=="string"?n.instructions:this.config.instructions),S=typeof n.temperature=="number"?n.temperature:this.config.temperature,_=n.max_output_tokens??this.config.maxOutputTokens,f=_==="inf"||_===void 0?void 0:_,h=n.tools!==void 0?n.tools:this.config.tools,w=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,b={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},...S!==void 0?{temperature:S}:{},...f!==void 0?{max_output_tokens:f}:{},...h!==void 0?{tools:h}:{},...w!==void 0?{tool_choice:w}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:R,captureWallMs:E}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(R,E);this.inFlight=(async()=>{let R=[],E=C=>{this.responseFlushed?this.send(C):R.push(C)},A=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:O("event"),response:this.responseObject(p,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(p,"in_progress")});for(let C of R)this.send(C);R.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},x=null,T=()=>{this.closeOpenItems(p,y,g),A(),this.send({type:"response.done",event_id:O("event"),response:this.responseObject(p,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise($=>{this.pendingTranscriptSettled=$}),this.cancelled||this.closed))throw new Ze;g=this.items.length,v=In(this.items)}let{input:C,sawAudioOnlyItem:B}=v??{input:[],sawAudioOnlyItem:!1},V={...b,input:C,...m?this.compositeTurnAsk(n):{}};B&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let N;try{let $=this.upstreamStream(V,c);Promise.resolve($).catch(D=>{D instanceof W&&this.failSessionGone(D)}),N=await Promise.race([$,l])}catch($){if($ instanceof Ze){this.deadlineFired&&!this.closed&&T();return}this.upstreamTurnFault($,p);return}A();try{for await(let $ of this.stallBoundedTurn(N)){if(this.cancelled)break;let D=$;if(D.type==="error"){let j=this.upstreamErrorBody(D);y.contentFlowed?this.send(K(j)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(p,j)});return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){A(),y.contentFlowed=!0,y.messageOpen||(this.beginMessageItem(p,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&E({type:"response.output_text.delta",event_id:O("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,E({type:"response.output_audio_transcript.delta",event_id:O("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta})),y.messageText+=D.delta;continue}if(D.type==="response.function_call_arguments.delta"){A(),y.contentFlowed=!0;let j=typeof D.delta=="string"?D.delta:"",X=typeof D.call_id=="string"&&D.call_id.length>0?D.call_id:`${p}_fc_${y.nextOutputIndex}`,M=y.tools.get(X);if(!M){let q=typeof D.name=="string"&&D.name.length>0?D.name:void 0;M={outputIndex:y.nextOutputIndex++,name:q,args:""},y.tools.set(X,M);let z={id:X,object:"realtime.item",type:"function_call",call_id:X,name:q??"",arguments:"",status:"in_progress"};E({type:"response.output_item.added",event_id:O("event"),response_id:p,output_index:M.outputIndex,item:z}),this.emitAssistantItemAdded(z)}typeof D.name=="string"&&D.name.length>0&&(M.name=D.name),M.args+=j,E({type:"response.function_call_arguments.delta",event_id:O("event"),item_id:X,response_id:p,output_index:M.outputIndex,call_id:X,name:M.name??"",delta:j});continue}if(D.type==="response.completed"){x=D.response??null;continue}}}catch($){if(this.closed)return;if($ instanceof Ze){this.deadlineFired&&T();return}if(this.cancelled)return;if($ instanceof On)this.operatorLog(`[realtime] turn ${p} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault($,p);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&T();return}this.closeOpenItems(p,y,g),A(),this.send({type:"response.done",event_id:O("event"),response:this.doneResponse(p,g,x)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Fl(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(K({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:O("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:O("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:O("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:O("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`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:O("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,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:O("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:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}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:O("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}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=Oe(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??xe(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Me(cr,"the organization is out of credits \u2014 top up to continue"),cr))}failSessionGone(e){if(e instanceof W&&e.reason===dr){this.failInsufficientCredits();return}let n=e instanceof Error&&ke(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${we(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Me("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof W){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof yi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Me(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(K(r)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(K(Z("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:O("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Lr&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(K(Z("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Rt){this.send(K(Z("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Rt}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(K(Z("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(K(Me(null,s instanceof Error?s.message:String(s)))))}}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}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{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>$r){this.ws.close(Ml,Fr("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=fe(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${we(e)}`),r.message}fail(e,n){this.send(K(e)),this.ws.close($l,Fr(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>hi(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),hi(this.id,e)}},Br=[];function hi(t,e){Br.push({id:t,reason:e}),Br.length>256&&Br.shift()}var Hr="/v1/realtime",wi="urun.admission",_i=t=>t.slice(0,120);function Bl(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
25
+ `)}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 fi(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}`}var Ht=require("ws");var yi=require("@urun-sh/core");var gi=require("crypto");function O(t){return`${t}_${(0,gi.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Rn=4*1024*1024,$r=8*1024*1024,Lr=512,En=20*1024*1024;function Z(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Me(t,e){return{type:"server_error",code:t,message:e}}function K(t){return{type:"error",event_id:O("event"),error:t}}function Nr(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Il={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Tl={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ol={format:!0,voice:!0,speed:!0};function Pl(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function gt(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function mi(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Cl=10;function Ur(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Cl})}function qt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in Il));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=gt(o.modalities,"modalities"),a=gt(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new P("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new P(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new P('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new P(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=gt(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Pl(a))throw new P(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new P("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new P("instructions must be a string or null","instructions");i.instructions=Ur(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new P(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new P("temperature must be a finite number or null","temperature");i.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 P(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new P("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new P("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new P("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new P(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new P(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new P("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 P("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new P(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new P("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 l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Tl))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&mi(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=qt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=qt({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new P("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ol))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&mi(d.format,"audio.output.format"),d.speed!==void 0)throw new P("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 i.voice;else{if(typeof d.voice!="string")throw new P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function An(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Dr(t,e){let n=t;if(!n||typeof n!="object")throw new P("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 P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:O("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 P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("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 P("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 P(`${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 P("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 P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new P("input_image content is only valid on user message items","item.content.type","invalid_request");let u=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof u!="string"||u.length===0)throw new P("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!u.startsWith("data:image/"))throw new P("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let a=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:u,...a!==void 0?{detail:a}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:O("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function In(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 Ml=1001,$l=1011,Ll=6e4,Nl=3e5;var Tn=class extends Error{},On=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Ze=class extends Error{constructor(){super("the turn was cut through"),this.name="TurnCutError"}},Fr=t=>t.slice(0,120),Ul=/^[A-Za-z0-9+/=]*$/,Dl=2;function Fl(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Dl)return!1;return!0}var jt=class{id=O("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Nr();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Ll,this.responseDeadlineMs=e.responseDeadlineMs??Nl,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.binding.onSessionEnd?.(n=>{n.reason===dr&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:O("event"),session:An(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:O("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof W&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(K(Me("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:O("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:O("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:O("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:O("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=O("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(Z("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Rn){this.fail(Z("frame_too_large",`frame exceeds the ${Rn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(Z("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(Z("missing_type",'event is missing a string "type"'),"invalid_frame");return}this.binding.presence?.touch(this.id);try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(K({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof Tn){this.fail(Me(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
26
+ ${o?.stack??we(o)}`),this.send(K(Me(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=qt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(K(Z("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:O("event"),session:An(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Dr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(K(Z("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:O("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(K(Z("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:O("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(K(Z("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:O("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(K(Z("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ul.test(e.audio)){this.send(K(Z("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>En){this.send(K(Z("buffer_full",`uncommitted input audio exceeds the ${En}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:O("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(K(Z("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=O("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(K(Z("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(K(Z("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:"seam-absent \u2014 the binding wired no endSession; unknown_event answered"})),this.send(K(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).then(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:n==null?"none":n instanceof Error?`error: ${n.message}`:n}))}).catch(n=>{this.operatorLog(JSON.stringify({event:"realtime_session_end",ts:new Date().toISOString(),conn:this.id,result:`error: ${n instanceof Error?n.message:String(n)}`}))}).finally(()=>{try{this.ws.close(1e3,Fr("session ended by client"))}catch{}});return}case"ping":return;default:this.send(K(Z("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(K(Z("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Tn("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(K({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0){o=!1;let i=n.next();i.catch(()=>{}),s=r?await Promise.race([i,r]):await i}else{let i,u=new Promise((d,c)=>{i=setTimeout(()=>c(new On),this.turnStallMs)}),a=n.next();a.catch(()=>{}),s=await(r?Promise.race([a,u,r]):Promise.race([a,u])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return this.config.model&&s.model===void 0&&(s.model=this.config.model),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,...u}=e;return await o.createResponse({...u,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(K(Z("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?gt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?gt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(K(Z("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.deadlineFired=!1;let i=()=>{},u=new Promise((_,R)=>{i=()=>R(new Ze)});this.turnCancelled=u,this.wakeTurnCancelled=()=>i(),u.catch(()=>{});let a=()=>{},l=new Promise((_,R)=>{a=()=>R(new Ze)});this.turnDialGate=l,this.wakeTurnDialGate=()=>a(),l.catch(()=>{});let d=this.responseDeadlineMs>0?setTimeout(()=>{this.closed||this.inFlight===null||(this.deadlineFired=!0,this.cancelled=!0,this.operatorLog(`[realtime] response ${this.activeResponseId??""} exceeded its ${this.responseDeadlineMs}ms lifetime bound \u2014 ending it visibly (status incomplete)`),this.cutThroughTurnWaits(!0))},this.responseDeadlineMs):void 0;this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let c=O("req"),p=`resp_${c}`;this.activeResponseId=p,this.activeRequestId=c;let m=this.binding.composite===!0,g=m?0:this.items.length,S=m?null:In(this.items),x=Ur(typeof n.instructions=="string"?n.instructions:this.config.instructions),k=typeof n.temperature=="number"?n.temperature:this.config.temperature,b=n.max_output_tokens??this.config.maxOutputTokens,v=b==="inf"||b===void 0?void 0:b,f=n.tools!==void 0?n.tools:this.config.tools,y=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,h={stream:!0,...this.config.model?{model:this.config.model}:{},...x!==void 0?{instructions:x}:{},...k!==void 0?{temperature:k}:{},...v!==void 0?{max_output_tokens:v}:{},...f!==void 0?{tools:f}:{},...y!==void 0?{tool_choice:y}:{}};if(!(m&&!this.ensureVoice())){for(let{audio:_,captureWallMs:R}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(_,R);this.inFlight=(async()=>{let _=[],R=C=>{this.responseFlushed?this.send(C):_.push(C)},T=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:O("event"),response:this.responseObject(p,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(p,"in_progress")});for(let C of _)this.send(C);_.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},E=null,A=()=>{this.closeOpenItems(p,w,g),T(),this.send({type:"response.done",event_id:O("event"),response:this.responseObject(p,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(m){if(this.pendingTranscriptItemId!==null&&(await new Promise($=>{this.pendingTranscriptSettled=$}),this.cancelled||this.closed))throw new Ze;g=this.items.length,S=In(this.items)}let{input:C,sawAudioOnlyItem:q}=S??{input:[],sawAudioOnlyItem:!1},B={...h,input:C,...m?this.compositeTurnAsk(n):{}};q&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let N;try{let $=this.upstreamStream(B,c);Promise.resolve($).catch(D=>{D instanceof W&&this.failSessionGone(D)}),N=await Promise.race([$,l])}catch($){if($ instanceof Ze){this.deadlineFired&&!this.closed&&A();return}this.upstreamTurnFault($,p);return}T();try{for await(let $ of this.stallBoundedTurn(N)){if(this.cancelled)break;let D=$;if(D.type==="error"){let H=this.upstreamErrorBody(D);w.contentFlowed?this.send(K(H)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(p,H)});return}if(D.type==="response.output_text.delta"&&typeof D.delta=="string"){T(),w.contentFlowed=!0,w.messageOpen||(this.beginMessageItem(p,w.nextOutputIndex++),w.messageOpen=!0),this.config.outputModalities.includes("text")&&R({type:"response.output_text.delta",event_id:O("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta}),this.turnOutputIsAudio()&&(w.transcriptDelta=!0,R({type:"response.output_audio_transcript.delta",event_id:O("event"),item_id:`${p}_msg_0`,response_id:p,output_index:0,content_index:0,delta:D.delta})),w.messageText+=D.delta;continue}if(D.type==="response.function_call_arguments.delta"){T(),w.contentFlowed=!0;let H=typeof D.delta=="string"?D.delta:"",X=typeof D.call_id=="string"&&D.call_id.length>0?D.call_id:`${p}_fc_${w.nextOutputIndex}`,M=w.tools.get(X);if(!M){let j=typeof D.name=="string"&&D.name.length>0?D.name:void 0;M={outputIndex:w.nextOutputIndex++,name:j,args:""},w.tools.set(X,M);let z={id:X,object:"realtime.item",type:"function_call",call_id:X,name:j??"",arguments:"",status:"in_progress"};R({type:"response.output_item.added",event_id:O("event"),response_id:p,output_index:M.outputIndex,item:z}),this.emitAssistantItemAdded(z)}typeof D.name=="string"&&D.name.length>0&&(M.name=D.name),M.args+=H,R({type:"response.function_call_arguments.delta",event_id:O("event"),item_id:X,response_id:p,output_index:M.outputIndex,call_id:X,name:M.name??"",delta:H});continue}if(D.type==="response.completed"){E=D.response??null;continue}}}catch($){if(this.closed)return;if($ instanceof Ze){this.deadlineFired&&A();return}if(this.cancelled)return;if($ instanceof On)this.operatorLog(`[realtime] turn ${p} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault($,p);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&A();return}this.closeOpenItems(p,w,g),T(),this.send({type:"response.done",event_id:O("event"),response:this.doneResponse(p,g,E)})}finally{clearTimeout(d),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Fl(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(K({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:O("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:O("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:O("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:O("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`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:O("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,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:O("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:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}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:O("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}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=Oe(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??xe(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failInsufficientCredits(){this.closed||(this.operatorLog(`[credits-cutoff] realtime connection (conn ${this.id}, session ${this.sessionId}) closing: the organization is out of credits \u2014 surfacing the terminal insufficient_credits close`),this.fail(Me(cr,"the organization is out of credits \u2014 top up to continue"),cr))}failSessionGone(e){if(e instanceof W&&e.reason===dr){this.failInsufficientCredits();return}let n=e instanceof Error&&ke(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${we(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Me("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof W){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof yi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Me(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(K(r)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(n,r)})}cutThroughTurnWaits(e){e&&this.wakeTurnDialGate?.(),this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.()}cancelResponse(){let e=this.inFlight;if(!e){this.send(K(Z("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.cutThroughTurnWaits(!1);let n=this.activeResponseId??"resp_";e.finally(()=>{this.deadlineFired||this.send({type:"response.cancelled",event_id:O("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Lr&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(K(Z("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Rt){this.send(K(Z("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Rt}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(K(Z("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(K(Me(null,s instanceof Error?s.message:String(s)))))}}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}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{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>$r){this.ws.close(Ml,Fr("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=fe(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${we(e)}`),r.message}fail(e,n){this.send(K(e)),this.ws.close($l,Fr(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.cancelled=!0,this.cutThroughTurnWaits(!0);let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.binding.presence?.detach(this.id),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>hi(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),hi(this.id,e)}},Br=[];function hi(t,e){Br.push({id:t,reason:e}),Br.length>256&&Br.shift()}var Hr="/v1/realtime",wi="urun.admission",_i=t=>t.slice(0,120);function Bl(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
27
27
  Connection: close\r
28
28
  Content-Type: text/plain\r
29
29
  \r
30
30
  ${_i(n)}\r
31
31
  `),t.destroy()}function ql(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
32
- `}function jl(t){Re(process.stdout,t)}function Hl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function qr(t){return t.audioSession?.audio.sessionId??void 0}function Gr(t,e){let n=new Ht.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Hr)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=O("rtup"),l=Hl(o),d=y=>{(e.log??jl)(ql(y))};d({stage:"accept",conn:a,model:l}),s.resume();let c=new AbortController,p=null,m=y=>{p??=y,c.abort(new Error(p))},g=()=>m("client socket closed"),v=()=>m("client socket closed (half-close)"),k=y=>m(`client socket error: ${y.message}`);s.once("close",g),s.once("end",v),s.once("error",k);let S=()=>{s.removeListener("close",g),s.removeListener("end",v),s.removeListener("error",k)},_=y=>{d({stage:"close",conn:a,model:l,...y})},f=null,h=!1,w=null,b=y=>JSON.stringify({type:wi,event_id:O("event"),...y}),R=y=>{if(f!==null){f.readyState===Ht.WebSocket.OPEN&&f.send(b(y));return}h||(h=!0,n.handleUpgrade(o,s,i,x=>{f=x,w=[],x.on("message",T=>{w?.push(String(T))}),d({stage:"waiting",conn:a,model:l,status:y.status}),x.send(b(y))}))},E=y=>{let x=y,T=x.session!=null&&typeof x.session.sendResponseCreate=="function",C=x.clients!=null&&typeof x.clients.createResponse=="function";if(!T&&!C)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((B,V)=>{let N=($,D)=>{try{let j=Date.now();new jt({ws:$,binding:y,operatorLog:e.operatorLog,...D.length>0?{replayFrames:D}:{},onClosed:(X,M)=>{_({while:"live",reason:M.reason});try{e.onSessionEnded?.({req:o,binding:y,connected_ms:Math.max(0,Date.now()-j),reason:M.reason})}catch(q){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${q instanceof Error?q.message:String(q)}
33
- `)}}}),d({stage:"admit",conn:a,model:l,...qr(y)===void 0?{}:{session:qr(y)}}),B()}catch(j){V(j)}};if(f!==null){let $=w??[];w=null,N(f,$);return}n.handleUpgrade(o,s,i,$=>N($,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,R).then(async y=>{if(c.signal.aborted){S();let x=qr(y);try{await y.release?.()}catch(T){_({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",release_failed:T instanceof Error?T.message:String(T)});return}_({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",released:!0}),s.destroy();return}S(),await E(y)}).catch(y=>{let x=y instanceof jr.SessionFailedError?Sn(y):null,T=null;if(y!==null&&typeof y=="object"&&"status"in y){let N=y.status;typeof N=="number"&&(T=N)}let C=T??x?.status??502,B=y instanceof Error?y.message:String(y),V=T!==null?B:x!==null?Bt(x,y instanceof jr.SessionFailedError&&y.status.sessionId?`session ${y.status.sessionId}`:void 0):fe(y).message;if(_({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:B,status:C}}),f!==null&&!c.signal.aborted){let N=JSON.stringify({type:wi,event_id:O("event"),status:C<500?"rejected":"failed",reason:V});f.readyState===Ht.WebSocket.OPEN&&f.send(N),f.close(1011,_i(V));return}s.destroyed||Bl(s,C,V)}).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()))}}var xi=require("crypto");var Jr="x-urun-profile",Gt="voice";var de=class extends Error{status=400},Gl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Vl=/\s/;function Jl(t){return Gl.test(t)}function Vr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new de(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function vi(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 de(`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 de(`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 de(`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 bi(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 de(`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 l=n.trim();if(l==="")throw new de(`the ${Jr} header is empty \u2014 the only profile this lane accepts is "${Gt}" (omit the header for the ordinary lane)`);if(l!==Gt)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Gt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Gt)throw new de(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Gt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new de("the voice profile is streaming-only \u2014 send stream: true");let u=o?.voice;if(u!==void 0&&(typeof u!="object"||u===null||Array.isArray(u)))throw new de("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let a=u??{};return{flushMaxChars:vi(a,"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:vi(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Vr(a,"sentence_flush",!0),includeReasoning:Vr(a,"include_reasoning",!1),metadata:Vr(a,"metadata",!1)}}var ht=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&&Jl(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(Vl.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)}};var $e=(t,e)=>Object.assign(new Error(e),{status:t}),zl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Kr=(t,e,n)=>new W(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Wr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof J?$e(404,n.message):n}};async function Si(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw $e(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${zl}`);if(o==="transcription")throw $e(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw $e(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw $e(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof J?$e(404,m.message):m}if(!p)throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof J?$e(404,m.message):m}if(p!=="stt")throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Wr(t,n.stt),i=await Wr(t,e),u=await Wr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Yl({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{a.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof W?Kr("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function ki(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Vt=class extends Error{};async function*Yl(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:u,companions:a}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,g=null,v=null,k=[],S=null,_=new Promise((x,T)=>{n&&n.addEventListener("abort",()=>T(new Vt),{once:!0})}),f=()=>m||n?.aborted===!0,h=async x=>{if(f())return;let T;try{T=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:x}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(B){throw B instanceof W?Kr("tts",a.tts,B):B}let C=T[Symbol.asyncIterator]();v=C;try{for(;;){let B=C.next(),V;try{V=await Promise.race([B,_])}catch($){if(B.catch(()=>{}),$ instanceof Vt)return;throw $}if(V.done)return;let N=V.value;if(N.type==="error"){let $=N.error&&typeof N.error.message=="string"?N.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${$}`)}if(N.type==="response.completed")return}}finally{v===C&&(v=null)}},w=async()=>{for(;k.length>0&&!f();){let x=k.shift();await h(x)}},b=x=>{if(x===""||f()||(k.push(x),S!==null))return;let T=w();S=T,T.then(()=>{S===T&&(S=null)},C=>{S===T&&(S=null),g??=C})},R=()=>{m=!0,k.length=0;let x=v;if(v=null,x){let T=x.return?.();T&&T.catch(()=>{})}},E=async()=>{for(;k.length>0||S!==null;){let x=S;if(x===null){await h(k.shift());continue}await x}},A=p?new ht({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},x=>b(x)):null,y=null;try{let x;try{x=await o.createResponseOn(s,d)}catch(C){throw C instanceof W?Kr("chat",u,C):C}let T=x[Symbol.asyncIterator]();try{for(;;){let C=T.next(),B;try{B=await Promise.race([C,_])}catch($){if(C.catch(()=>{}),$ instanceof Vt)break;throw $}if(B.done)break;let V=B.value;if(f())return;let N=V;if(N.type==="error"){yield V;return}if(N.type==="response.output_text.delta"&&typeof N.delta=="string"){yield V,A?.push(N.delta);continue}if(N.type==="response.function_call_arguments.delta"){A?.flush(),yield V;continue}if(N.type==="response.completed"){y=V.response;continue}}}finally{Promise.resolve(T.return?.()).catch(()=>{})}A?.flush(),A?.dispose(),p&&await E(),y!==null&&(yield{type:"response.completed",response:y})}finally{A?.dispose(),R();try{if(g instanceof W)throw g}finally{r?.()}}}var me=(t,e)=>Object.assign(new Error(e),{status:t});function Xl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Ql(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Zl='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ed(t,e,n,r,o){if(!t.supportsAudio)throw me(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(m){throw m instanceof J?me(404,m.message):m}if(!s){let m=null;if(t.realtimeCompanionsFor)try{m=await t.realtimeCompanionsFor(e)}catch(g){throw g instanceof J?me(404,g.message):g}if(m!==null)return await Si(t,e,m,n,r);throw me(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw me(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 i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(m){throw m instanceof J?me(404,m.message):m}if(i&&!t.openTurnsOn)throw me(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let m;try{m=await t.transcriptStreamFor(e)}catch(g){throw g instanceof J?me(404,g.message):g}if(m!=="stt")throw me(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw me(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Zl}`);if(r==="transcription"&&!i)throw me(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let u;try{u=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(m){throw m instanceof ce?me(503,m.message):m}let a=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,xi.randomUUID)()}`,c={audio:await t.openAudioOn(u,n,l,o).catch(m=>{throw t.releaseSessionHandle?.(u),m})},p={clients:{createResponse:async m=>await t.createResponseOn(u,m,l)},voice:s,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(u,n)),i&&(p.turns=m=>t.openTurnsOn(u,m)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(u)),t.endDedicatedSession&&(p.endSession=()=>t.endDedicatedSession(u)),t.onSessionEnd&&(p.onSessionEnd=m=>t.onSessionEnd(u,m)),e!==void 0&&(p.model=e),a!==null&&(p.catalog=a),p}function Ri(t,e,n){let r=ki(t,n);return{resolve:async(o,s,i)=>{if(e!==void 0){let u=o.headers.authorization,a=typeof u=="string"?u.trim():"",l=a.startsWith("Bearer ")?a.slice(7).trim():"";if(l===""||l!==e)throw me(401,"invalid local proxy api key")}return ed(r,Xl(o),s,Ql(o),i)}}}var U=class extends Error{},_e=class extends Error{};function se(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function yt(t,e){if(t!=null)throw new U(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function zr(t){let e=Pn(t);return e!==null&&e<=1?e:null}function Ei(t,e){if(!se(t))throw new U("decisions requires a JSON object body");yt(t.prompt_cache_key,"prompt_cache_key"),yt(t.prompt_cache_options,"prompt_cache_options"),yt(t.safety_identifier,"safety_identifier");let n=[],r=td(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new U("decisions requires a questions array of 1 to 400 questions");let s={},i=[],u=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=sd(o[l],l,o.length,n);if(u.has(c.key))throw new U(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);u.add(c.key),s[c.key]=d,i.push(c)}let a={model:e,state:r,questions:s};return n.length>0&&(a.media=n),{systemone:a,specs:i}}function td(t,e){if(typeof t=="string")return t;if(!se(t)&&!Array.isArray(t))throw new U("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)rd(o,r,e);return nd(r)}function nd(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
32
+ `}function jl(t){Re(process.stdout,t)}function Hl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function qr(t){return t.audioSession?.audio.sessionId??void 0}function Gr(t,e){let n=new Ht.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Hr)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=O("rtup"),l=Hl(o),d=w=>{(e.log??jl)(ql(w))};d({stage:"accept",conn:a,model:l}),s.resume();let c=new AbortController,p=null,m=w=>{p??=w,c.abort(new Error(p))},g=()=>m("client socket closed"),S=()=>m("client socket closed (half-close)"),x=w=>m(`client socket error: ${w.message}`);s.once("close",g),s.once("end",S),s.once("error",x);let k=()=>{s.removeListener("close",g),s.removeListener("end",S),s.removeListener("error",x)},b=w=>{d({stage:"close",conn:a,model:l,...w})},v=null,f=!1,y=null,h=w=>JSON.stringify({type:wi,event_id:O("event"),...w}),_=w=>{if(v!==null){v.readyState===Ht.WebSocket.OPEN&&v.send(h(w));return}f||(f=!0,n.handleUpgrade(o,s,i,E=>{v=E,y=[],E.on("message",A=>{y?.push(String(A))}),d({stage:"waiting",conn:a,model:l,status:w.status}),E.send(h(w))}))},R=w=>{let E=w,A=E.session!=null&&typeof E.session.sendResponseCreate=="function",C=E.clients!=null&&typeof E.clients.createResponse=="function";if(!A&&!C)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((q,B)=>{let N=($,D)=>{try{let H=Date.now();new jt({ws:$,binding:w,operatorLog:e.operatorLog,...D.length>0?{replayFrames:D}:{},onClosed:(X,M)=>{b({while:"live",reason:M.reason});try{e.onSessionEnded?.({req:o,binding:w,connected_ms:Math.max(0,Date.now()-H),reason:M.reason})}catch(j){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${j instanceof Error?j.message:String(j)}
33
+ `)}}}),d({stage:"admit",conn:a,model:l,...qr(w)===void 0?{}:{session:qr(w)}}),q()}catch(H){B(H)}};if(v!==null){let $=y??[];y=null,N(v,$);return}n.handleUpgrade(o,s,i,$=>N($,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,_).then(async w=>{if(c.signal.aborted){k();let E=qr(w);try{await w.release?.()}catch(A){b({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",release_failed:A instanceof Error?A.message:String(A)});return}b({while:"queued",...E===void 0?{}:{session:E},reason:p??"client socket closed",released:!0}),s.destroy();return}k(),await R(w)}).catch(w=>{let E=w instanceof jr.SessionFailedError?Sn(w):null,A=null;if(w!==null&&typeof w=="object"&&"status"in w){let N=w.status;typeof N=="number"&&(A=N)}let C=A??E?.status??502,q=w instanceof Error?w.message:String(w),B=A!==null?q:E!==null?Bt(E,w instanceof jr.SessionFailedError&&w.status.sessionId?`session ${w.status.sessionId}`:void 0):fe(w).message;if(b({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:q,status:C}}),v!==null&&!c.signal.aborted){let N=JSON.stringify({type:wi,event_id:O("event"),status:C<500?"rejected":"failed",reason:B});v.readyState===Ht.WebSocket.OPEN&&v.send(N),v.close(1011,_i(B));return}s.destroyed||Bl(s,C,B)}).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()))}}var xi=require("crypto");var Jr="x-urun-profile",Gt="voice";var de=class extends Error{status=400},Gl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Vl=/\s/;function Jl(t){return Gl.test(t)}function Vr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new de(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function vi(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 de(`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 de(`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 de(`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 bi(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 de(`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 l=n.trim();if(l==="")throw new de(`the ${Jr} header is empty \u2014 the only profile this lane accepts is "${Gt}" (omit the header for the ordinary lane)`);if(l!==Gt)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Gt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Gt)throw new de(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Gt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new de("the voice profile is streaming-only \u2014 send stream: true");let u=o?.voice;if(u!==void 0&&(typeof u!="object"||u===null||Array.isArray(u)))throw new de("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let a=u??{};return{flushMaxChars:vi(a,"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:vi(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Vr(a,"sentence_flush",!0),includeReasoning:Vr(a,"include_reasoning",!1),metadata:Vr(a,"metadata",!1)}}var ht=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&&Jl(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(Vl.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)}};var $e=(t,e)=>Object.assign(new Error(e),{status:t}),zl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Kr=(t,e,n)=>new W(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Wr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof J?$e(404,n.message):n}};async function Si(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw $e(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${zl}`);if(o==="transcription")throw $e(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw $e(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw $e(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof J?$e(404,m.message):m}if(!p)throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof J?$e(404,m.message):m}if(p!=="stt")throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Wr(t,n.stt),i=await Wr(t,e),u=await Wr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Yl({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{a.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof W?Kr("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function ki(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Vt=class extends Error{};async function*Yl(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:u,companions:a}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,g=null,S=null,x=[],k=null,b=new Promise((E,A)=>{n&&n.addEventListener("abort",()=>A(new Vt),{once:!0})}),v=()=>m||n?.aborted===!0,f=async E=>{if(v())return;let A;try{A=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:E}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(q){throw q instanceof W?Kr("tts",a.tts,q):q}let C=A[Symbol.asyncIterator]();S=C;try{for(;;){let q=C.next(),B;try{B=await Promise.race([q,b])}catch($){if(q.catch(()=>{}),$ instanceof Vt)return;throw $}if(B.done)return;let N=B.value;if(N.type==="error"){let $=N.error&&typeof N.error.message=="string"?N.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${$}`)}if(N.type==="response.completed")return}}finally{S===C&&(S=null)}},y=async()=>{for(;x.length>0&&!v();){let E=x.shift();await f(E)}},h=E=>{if(E===""||v()||(x.push(E),k!==null))return;let A=y();k=A,A.then(()=>{k===A&&(k=null)},C=>{k===A&&(k=null),g??=C})},_=()=>{m=!0,x.length=0;let E=S;if(S=null,E){let A=E.return?.();A&&A.catch(()=>{})}},R=async()=>{for(;x.length>0||k!==null;){let E=k;if(E===null){await f(x.shift());continue}await E}},T=p?new ht({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},E=>h(E)):null,w=null;try{let E;try{E=await o.createResponseOn(s,d)}catch(C){throw C instanceof W?Kr("chat",u,C):C}let A=E[Symbol.asyncIterator]();try{for(;;){let C=A.next(),q;try{q=await Promise.race([C,b])}catch($){if(C.catch(()=>{}),$ instanceof Vt)break;throw $}if(q.done)break;let B=q.value;if(v())return;let N=B;if(N.type==="error"){yield B;return}if(N.type==="response.output_text.delta"&&typeof N.delta=="string"){yield B,T?.push(N.delta);continue}if(N.type==="response.function_call_arguments.delta"){T?.flush(),yield B;continue}if(N.type==="response.completed"){w=B.response;continue}}}finally{Promise.resolve(A.return?.()).catch(()=>{})}T?.flush(),T?.dispose(),p&&await R(),w!==null&&(yield{type:"response.completed",response:w})}finally{T?.dispose(),_();try{if(g instanceof W)throw g}finally{r?.()}}}var me=(t,e)=>Object.assign(new Error(e),{status:t});function Xl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Ql(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Zl='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function ed(t,e,n,r,o){if(!t.supportsAudio)throw me(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(m){throw m instanceof J?me(404,m.message):m}if(!s){let m=null;if(t.realtimeCompanionsFor)try{m=await t.realtimeCompanionsFor(e)}catch(g){throw g instanceof J?me(404,g.message):g}if(m!==null)return await Si(t,e,m,n,r);throw me(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw me(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 i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(m){throw m instanceof J?me(404,m.message):m}if(i&&!t.openTurnsOn)throw me(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let m;try{m=await t.transcriptStreamFor(e)}catch(g){throw g instanceof J?me(404,g.message):g}if(m!=="stt")throw me(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw me(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Zl}`);if(r==="transcription"&&!i)throw me(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let u;try{u=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(m){throw m instanceof ce?me(503,m.message):m}let a=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,xi.randomUUID)()}`,c={audio:await t.openAudioOn(u,n,l,o).catch(m=>{throw t.releaseSessionHandle?.(u),m})},p={clients:{createResponse:async m=>await t.createResponseOn(u,m,l)},voice:s,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(u,n)),i&&(p.turns=m=>t.openTurnsOn(u,m)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(u)),(t.touchSessionPresence||t.detachSessionPresence)&&(p.presence={touch:m=>t.touchSessionPresence?.(u,m),detach:m=>t.detachSessionPresence?.(u,m)}),t.endDedicatedSession&&(p.endSession=()=>t.endDedicatedSession(u)),t.onSessionEnd&&(p.onSessionEnd=m=>t.onSessionEnd(u,m)),e!==void 0&&(p.model=e),a!==null&&(p.catalog=a),p}function Ri(t,e,n){let r=ki(t,n);return{resolve:async(o,s,i)=>{if(e!==void 0){let u=o.headers.authorization,a=typeof u=="string"?u.trim():"",l=a.startsWith("Bearer ")?a.slice(7).trim():"";if(l===""||l!==e)throw me(401,"invalid local proxy api key")}return ed(r,Xl(o),s,Ql(o),i)}}}var U=class extends Error{},_e=class extends Error{};function se(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function yt(t,e){if(t!=null)throw new U(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function zr(t){let e=Pn(t);return e!==null&&e<=1?e:null}function Ei(t,e){if(!se(t))throw new U("decisions requires a JSON object body");yt(t.prompt_cache_key,"prompt_cache_key"),yt(t.prompt_cache_options,"prompt_cache_options"),yt(t.safety_identifier,"safety_identifier");let n=[],r=td(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new U("decisions requires a questions array of 1 to 400 questions");let s={},i=[],u=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=sd(o[l],l,o.length,n);if(u.has(c.key))throw new U(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);u.add(c.key),s[c.key]=d,i.push(c)}let a={model:e,state:r,questions:s};return n.length>0&&(a.media=n),{systemone:a,specs:i}}function td(t,e){if(typeof t=="string")return t;if(!se(t)&&!Array.isArray(t))throw new U("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)rd(o,r,e);return nd(r)}function nd(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
34
34
 
35
- `)}function rd(t,e,n){if(!se(t))throw new U("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){od(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){Ai(s,e,n,void 0,!1);return}throw new U(`${o} output must be a string or an array of parts`)}default:throw new U(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function od(t,e,n,r){e==="assistant"&&yt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new U(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!se(s))throw new U("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new U(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}Ai(o,n,r,e)}function Ai(t,e,n,r,o=!0){for(let s of t){if(!se(s))throw new U("decisions content parts must be JSON objects");switch(yt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new U("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new U("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new U("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Ii(s));break}default:throw new U(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Ii(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new U("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new U("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new U("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new U("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new U("input_image detail must be low, high, auto, or original");let u={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(u.detail=i),u}function sd(t,e,n,r){if(!se(t))throw new U(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new U(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new U(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=id(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:a,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:u,name:i}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new U(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let v of l){if(!se(v))throw new U(`questions[${e}] choices must be JSON objects`);let k=v.value;if(typeof k!="string"&&typeof k!="boolean")throw new U(`questions[${e}] choice value must be a string or boolean`);let S=String(k);if(c.has(S))throw new U(`questions[${e}] has duplicate choice value ${JSON.stringify(S)} (choices must be unique)`);c.add(S);let _=v.description;if(_!==void 0&&typeof _!="string")throw new U(`questions[${e}] choice description must be a string`);d.push(k),p.push(_)}let m=l.map((v,k)=>({name:String(d[k]),description:p[k]??String(d[k])}));return{entry:{kind:"choice",prompt:a,options:m},spec:{type:o,key:u,name:i,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new U(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!se(m)||typeof m.label!="string")throw new U(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new U(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let g=m.description;if(g!==void 0&&typeof g!="string")throw new U(`questions[${e}] score level description must be a string`);let v=g!==void 0?`${m.label}: ${g}`:m.label;if(c.includes(v))throw new U(`questions[${e}] has duplicate score criterion ${JSON.stringify(v)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(v)}return{entry:{kind:"score",prompt:a,criteria:c},spec:{type:o,key:u,name:i,levelLabels:d}}}}}function id(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new U(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!se(s))throw new U(`questions[${e}] instruction parts must be JSON objects`);switch(yt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new U(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new U(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Ii(s));break}case"input_json":{let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new U(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new U(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
35
+ `)}function rd(t,e,n){if(!se(t))throw new U("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){od(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){Ai(s,e,n,void 0,!1);return}throw new U(`${o} output must be a string or an array of parts`)}default:throw new U(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function od(t,e,n,r){e==="assistant"&&yt(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new U(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!se(s))throw new U("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new U(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}Ai(o,n,r,e)}function Ai(t,e,n,r,o=!0){for(let s of t){if(!se(s))throw new U("decisions content parts must be JSON objects");switch(yt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new U("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new U("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new U("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Ii(s));break}default:throw new U(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Ii(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new U("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new U("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new U("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new U("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new U("input_image detail must be low, high, auto, or original");let u={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(u.detail=i),u}function sd(t,e,n,r){if(!se(t))throw new U(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new U(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new U(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=id(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:a,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:u,name:i}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new U(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let S of l){if(!se(S))throw new U(`questions[${e}] choices must be JSON objects`);let x=S.value;if(typeof x!="string"&&typeof x!="boolean")throw new U(`questions[${e}] choice value must be a string or boolean`);let k=String(x);if(c.has(k))throw new U(`questions[${e}] has duplicate choice value ${JSON.stringify(k)} (choices must be unique)`);c.add(k);let b=S.description;if(b!==void 0&&typeof b!="string")throw new U(`questions[${e}] choice description must be a string`);d.push(x),p.push(b)}let m=l.map((S,x)=>({name:String(d[x]),description:p[x]??String(d[x])}));return{entry:{kind:"choice",prompt:a,options:m},spec:{type:o,key:u,name:i,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new U(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!se(m)||typeof m.label!="string")throw new U(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new U(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let g=m.description;if(g!==void 0&&typeof g!="string")throw new U(`questions[${e}] score level description must be a string`);let S=g!==void 0?`${m.label}: ${g}`:m.label;if(c.includes(S))throw new U(`questions[${e}] has duplicate score criterion ${JSON.stringify(S)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(S)}return{entry:{kind:"score",prompt:a,criteria:c},spec:{type:o,key:u,name:i,levelLabels:d}}}}}function id(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new U(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!se(s))throw new U(`questions[${e}] instruction parts must be JSON objects`);switch(yt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new U(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new U(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Ii(s));break}case"input_json":{let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new U(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new U(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
36
36
 
37
- `)}function Ti(t,e){if(!se(e))throw new _e("decision answer was not a JSON object");let n=e.answers;if(!se(n))throw new _e("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!se(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=se(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=zr(s.noul);if(u===null)throw new _e(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let u=o.choiceValues??[],a=s.choice;if(typeof a!="string")throw new _e(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new _e(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=Pn(s.confidence);if(d===null)throw new _e(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let m=zr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:u[l],confidence:d,probabilities:c});continue}case"score":{let u=o.levelLabels??[],a=Pn(s.score);if(a===null)throw new _e(`the score answer for "${o.key}" carries no numeric score to translate`);let l=Pn(s.confidence);if(l===null)throw new _e(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<u.length;c++){let p=zr(i[String(c)]);p!==null&&d.push({value:c,label:u[c],probability:p})}r.push({type:"score",name:o.name,score:a,confidence:l,probabilities:d});continue}}}return r}var ie=class extends Error{};async function Cn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ie(`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 ie(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Mn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new ie(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Oi="/v1/images/generations",$n="/v1/images/edits";function Pi(t){return t===Oi||t===$n}var Ci="/v1/images/models";async function Mi(t,e,n){if(t){if(t.model=ue({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 G=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ad=16*1024*1024,$i=64*1024*1024;function Li(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 Jt(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 Ni(t,e,n,r,o,s){let i=s??(g=>console.error(g)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),a=null;for await(let g of u){if(g.type==="error"){let v=g.error??{},k=typeof v.message=="string"&&v.message.length>0&&ke(v.message)?v.message:null;throw k===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(g)}`),new G(502,"the image upstream failed while serving this request")):new G(502,`image upstream error: ${k}`)}if(g.type==="response.completed"){a=g.response??null;break}}if(a===null)throw new G(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ce(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new G(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Li(p)===null)throw new G(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Ui(t,e){if(t instanceof G)return t;if(t instanceof Ie)throw t;return t instanceof J?new G(404,t.message):new G(502,ft("image",t,e))}async function Di(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 Jt(r,new G(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 Fi(t,e){t&&(t.outputUnits=e.images.length)}function Bi(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 ud={model:!0,prompt:!0,response_format:!0,n:!0};async function qi(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??$i;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${Oi}`);let s;try{s=JSON.parse((await Cn(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new G(413,p.message):new G(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new G(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!ud[p])throw new G(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let u=i.prompt;if(typeof u!="string"||u.trim().length===0)throw new G(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new G(400,"model must be a string","model");await Mi(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new G(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new G(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",u.length,u.length),!await Di(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await Ni(n.clients,a,c,n.turn?he(n.turn):void 0,n.turn,r);Fi(n.turn,p),Bi(e,p)}catch(p){throw Ui(p,r)}}catch(s){if(s instanceof ie){Jt(e,new G(413,s.message));return}if(s instanceof G){Jt(e,s);return}throw s}}var ld={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ji(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??$i,s=n.maxImagePartBytes??ad;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${$n}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new G(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Mn(t,o)}catch(g){throw g instanceof ie?new G(413,g.message):new G(400,String(g instanceof Error?g.message:g))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new G(400,"prompt is required and must be a non-empty string field","prompt");let l=u.get("model");if(l!==null&&typeof l!="string")throw new G(400,"model must be a string field","model");let d=l===null?void 0:l;await Mi(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new G(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let g of u.keys())if(!ld[g])throw new G(400,`form field "${g}" 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[]).`,g);let p=[];for(let g of["image","image[]"])for(let v of u.getAll(g)){if(!(v instanceof File))throw new G(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",g);if(v.size>s)throw new G(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let k=new Uint8Array(await v.arrayBuffer()),S=Li(k);if(S===null)throw new G(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",g);p.push({bytes:k,mime:S})}if(p.length===0)throw new G(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Di(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:g,mime:v}of p)m.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(g).toString("base64")}`});try{let g=await Ni(n.clients,d,m,n.turn?he(n.turn):void 0,n.turn,r);Fi(n.turn,g),Bi(e,g)}catch(g){throw Ui(g,r)}}catch(i){if(i instanceof ie){Jt(e,new G(413,i.message));return}if(i instanceof G){Jt(e,i);return}throw i}}var Wt="/v1/audio/speech";function Xi(t){return t===Wt}var Hi=4096,Gi=18e4,Vi=5e3,dd=64*1024*1024,Ji=8,Wi=5,Ki=1024*1024,wt="voice_applied",Nn="X-Urun-Voice-Applied",F=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Yr(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 Un=class extends F{constructor(e){super(502,e)}};function Qi(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Zi(t){return new F(502,`the runtime's ${wt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Nn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function cd(t,e,n){if(t){if(t.model=ue({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 ea(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var pd=2;function fd(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>pd)return!1;return!0}function md(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 zi=new WeakMap,Ln=new WeakMap;function gd(t,e){let n=Ln.get(t)??0;if(n>=Ji)throw new F(503,`this model's speech queue is full \u2014 ${Ji} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Wi}s`,void 0,Wi);Ln.set(t,n+1);let r=zi.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return zi.set(t,s),(async()=>{await r;try{return await e()}finally{Ln.set(t,(Ln.get(t)??1)-1),o()}})()}async function hd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new F(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 W))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(()=>{clearTimeout(s)})}function et(t,e){if(t instanceof F)return t;if(t instanceof Ie)throw t;return t instanceof J?new F(404,t.message):new F(502,ft("speech",t,e))}async function Yi(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return gd(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,g=!1,v,k=new Promise(x=>{v=x}),S=[],_,f=!1,h=null,w=()=>{h!==null&&(clearTimeout(_),_=setTimeout(()=>{f=!0,h?.()},o.capMs))},b=()=>{m&&!g&&S.length>=o.quietRunFrames&&(g=!0,v())},R=e.onOutputAudio(x=>{let T=Buffer.from(x,"base64");if(T.byteLength===0)return;w();let C=fd(T);if(!p){if(C)return;p=!0}if(C){S.push(T),b();return}for(let B of S)c(B);S.length=0,c(T),b()}),E=null,A,y;try{y=(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 T=()=>(clearTimeout(A),new Promise(N=>{A=setTimeout(N,s.capMs)})),C=T(),B=!1;for(;;){let N=y.next(),$=await Promise.race([N,C]);if($===void 0){B=!0,N.catch(()=>{});break}if($.done)break;let D=$.value;if(C=T(),D.type==="error"){let j=D.error??{};await y.return?.();let X=typeof j.message=="string"&&j.message.length>0&&ke(j.message)?j.message:null;throw X===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(D)}`),new F(502,"the speech upstream failed while serving this request")):new F(502,`speech upstream error: ${X}`)}if(D.type==="response.completed"){E=D.response??null,m=!0,a?.(E),b(),await y.return?.();break}}if(clearTimeout(A),B)throw new F(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(E===null)throw new F(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let V=new Promise(N=>{h=N});if(w(),await Promise.race([k,V]),clearTimeout(_),_=void 0,h=null,r.voice!==void 0){let N=E[wt];if(typeof N!="string"||N!==r.voice){let $=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof N=="string"?`${wt} ${JSON.stringify(N)}`:`no ${wt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new Un($):new F(502,$)}}if(!p)throw new F(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(f&&!g&&S.length<1)throw new F(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return E}catch(x){throw x instanceof Un||await hd(t,n,y,s.returnBoundMs),x}finally{clearTimeout(_),clearTimeout(A),R()}})}function yd(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Nn)),t.write(u,a=>{a||(s+=u.byteLength,ea(e,s))}),t.writableLength>Ki&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Ki} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[wt];if(typeof a=="string"){if(!Qi(a))throw Zi(a);t.addTrailers({[Nn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function wd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw et(s,r)}return o?!0:(Yr(n,new F(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 _d={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},vd="wav, pcm";async function ta(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??dd,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${Wt}`);let u;try{u=JSON.parse((await Cn(t,o)).toString("utf8")||"{}")}catch(h){throw h instanceof ie?new F(413,h.message):new F(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new F(400,"request body must be a JSON object");let a=u;for(let h of Object.keys(a))if(!_d[h])throw new F(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 l=a.input;if(typeof l!="string"||l.trim().length===0)throw new F(400,"input is required and must be a non-empty string","input");if(l.length>Hi)throw new F(400,`input is ${l.length} chars \u2014 over the ${Hi}-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 F(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new F(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new F(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 ${Wt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(h){throw et(h,r)}if(p.defect!==null)throw new F(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new F(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let g=a.response_format??"wav";if(g!=="wav"&&g!=="pcm")throw new F(400,`response_format ${JSON.stringify(g)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${vd} \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 F(400,"stream_format, when present, must be a string","stream_format");let v=a.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new F(400,"speed, when present, must be a number","speed");if(v!==1)throw new F(400,`speed=${JSON.stringify(v)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let k=a.instructions;if(k!==void 0){if(typeof k!="string")throw new F(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new F(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 cd(n.turn,n.clients,d);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await wd(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new F(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 F(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 F(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(i())return;let _;try{_=await n.clients.speechSessionHandle(d)}catch(h){throw et(h,r)}let f;try{f=await n.clients.openAudioOn(_)}catch(h){throw et(h,r)}n.turn&&(n.turn.sessionId=f.sessionId);try{if(g==="wav"){let h=[],w=await Yi(n.clients,f,_,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Gi,returnBoundMs:n.turnReturnBoundMs??Vi},i,R=>h.push(R),R=>{n.turn&&(n.turn.outputSeconds=Ce(R))},r);if(w===null||i())return;let b=Buffer.concat(h);if(m===void 0){let R=w[wt];if(typeof R=="string"){if(!Qi(R))throw Zi(R);e.setHeader(Nn,R)}}ea(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([md(b.byteLength),b]))}else{let h=yd(e,n.turn,i,m===void 0),w;try{w=await Yi(n.clients,f,_,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Gi,returnBoundMs:n.turnReturnBoundMs??Vi},i,h.sink,b=>{n.turn&&(n.turn.outputSeconds=Ce(b))},r)}catch(b){let R=et(b,r);if(!h.started())throw R;n.turn&&(n.turn.streamError=!0),h.fail(R);return}if(w===null)return;try{await h.finish(w)}catch(b){let R=et(b,r);n.turn&&(n.turn.streamError=!0),h.fail(R);return}}}catch(h){throw et(h,r)}}catch(u){if(u instanceof ie){Yr(e,new F(413,u.message));return}if(u instanceof F){Yr(e,u);return}throw u}}var Dn="/v1/audio/transcriptions";function na(t){return t===Dn}var ra="/v1/audio/models",bd=16*1024*1024,Sd=64*1024*1024,te=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Xr(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 oa(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 kd(t){if(!oa(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,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,l=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,d=t[u+14]|t[u+15]<<8;n={sampleRate:l,channels:a,bitsPerSample:d}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+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 xd(t,e,n){if(t){if(t.model=ue({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 Rd(t,e){t&&(t.outputUnits=e.seconds)}async function Ed(t,e,n,r,o,s,i){let u=i??(c=>console.error(c)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of a){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",g=typeof p.message=="string"&&p.message.length>0&&ke(p.message)?p.message:null;throw g===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new te(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new te(m==="invalid_request_error"?400:502,`transcription upstream error: ${g}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new te(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Ce(d)),ct(l,d)}function sa(t,e){if(t instanceof te)return t;if(t instanceof Ie)throw t;return t instanceof J?new te(404,t.message):new te(502,ft("transcription",t,e))}async function Ad(t,e,n,r){let o;try{o=await t(e)}catch(s){throw sa(s,r)}return o?!0:(Xr(n,new te(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 Id=new Set(["file","model","language","response_format"]);async function ia(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Sd,s=n.maxAudioPartBytes??bd;try{if(t.method!=="POST")throw new te(405,`${String(t.method)} is not supported on ${Dn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new te(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Mn(t,o)}catch(_){throw _ instanceof ie?new te(413,_.message):new te(400,String(_ instanceof Error?_.message:_))}let a=new Map;for(let _ of u.keys()){if(!Id.has(_))throw new te(400,`form field "${_}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,_);a.set(_,(a.get(_)??0)+1)}for(let[_,f]of a)if(f>1)throw new te(400,`form field "${_}" appears ${f} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,_);let l=u.get("model");if(l!==null&&typeof l!="string")throw new te(400,"model must be a string field","model");let d=l===null?void 0:l,c=u.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new te(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=u.get("response_format")??"json";if(m!=="json")throw new te(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let g=u.get("file");if(!(g instanceof File))throw new te(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(g.size>s)throw new te(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await g.arrayBuffer());if(!oa(v))throw new te(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 k=kd(v);if(k===null)throw new te(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 xd(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await Ad(n.transcriptionModels,d,e,r))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let _=await Ed(n.clients,d,S,p,n.turn?he(n.turn):void 0,n.turn,r);Rd(n.turn,k),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:_}))}catch(_){throw sa(_,r)}}catch(i){if(i instanceof ie){Xr(e,new te(413,i.message));return}if(i instanceof te){Xr(e,i);return}throw i}}var ua="/v1/usage/requests",aa=1e4,Td=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,qe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},_t=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var la=1024*1024;function Qr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new qe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new qe(`"${e}" must be an array of uuid strings`);if(n.length>aa)throw new qe(`"${e}" carries ${n.length} ids; at most ${aa} 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"||!Td.test(s))throw new qe(`"${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 da(t){return Qr(t,"inference_ids")}function Fn(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 _t(`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 _t(`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)}}var Hn=require("@urun-sh/core");var Zr="/partners/huggingface/v1/billing/requests";function Od(t){return Qr(t,"requestIds")}function Pd(t){return t>=200&&t<=399}function Cd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Pd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ca(t,e){let n=Od(t),r=await e(n);return Fn(r,n),Cd(r)}var Md={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function $d(t){return Md[t]??null}var ga=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ld(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Nd(t){return t==="surface"}function Ud(t){let e=t?.ledgerFailureReason;return ga.includes(e)?e:"unknown"}var Dd=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],pa=["priced","unpriced"],Fd={written:pa,already_written:pa,skipped:Dd,failed:ga},og=Object.entries(Fd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Bd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function qd(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 jd=256,fa=4096,zt=12e4,Hd=250,Gd=8e3,Yt=[],ma=new Set,Xt=0,Kt=!1;var Vd=new Set;function Jd(){return Xt===0&&Yt.length===0}function Wd(){if(Jd()){Kt=!1;for(let t of[...Vd])t()}}function ha(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
38
- `}function Kd(t){Re(process.stdout,t)}function ya(t,e){try{t(e)}catch{}}function wa(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Kd,o=$d(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ya(r,ha("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,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 u=e.catalog;if(u.kind==="unresolved"){i("model_unresolved",u.reason);return}let a;if(u.kind==="catalog")a={model_id:u.model_id,identity_kind:"catalog_model",variant:u.variant};else{if(u.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}a={model_id:u.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:qd(e),completed_at:e.ts,billable_outcome:Bd(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Yt.length>=fa){i("queue_full",`${Yt.length} ledger writes are already waiting (capacity ${fa}, ${Xt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Yt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Xt<jd&&(Xt+=1,zd())}async function zd(){try{for(;;){let t=Yd();if(t===void 0)return;ma.add(t);try{await Xd(t)}finally{ma.delete(t)}}}finally{Xt-=1,Wd()}}function Yd(){let t=Date.now();for(;;){let e=Yt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<zt)return e;vt(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 ${zt}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 Xd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);vt(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=Ld(o);if(s!==null){vt(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=Ud(o),u=Date.now()-t.queuedAt;if(Kt){vt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:u,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(Nd(i)&&u<zt){if(await Zd(Qd(t.attempts)),Kt||Date.now()-t.queuedAt>=zt){let a=Date.now()-t.queuedAt;vt(t,{outcome:"failed",reason:Kt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Kt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${zt}ms dwell bound (waited ${a}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}vt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:u,error:o instanceof Error?o.message:String(o)});return}}}function Qd(t){return Math.min(Gd,Hd*2**Math.max(0,t-1))}function Zd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function vt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ya(t.report,ha(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function no(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ec(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 ae(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Y(t,e,n,r="invalid_request_error",o){ae(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function ro(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Oe(r),u=i??xe(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let a=r?.code??null,l=o==="invalid_request_error"?400:a==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),ae(t,l,{error:{message:u,type:o,code:a}})}function Ee(t,e,n,r){ae(t,e,{type:"error",error:{type:n,message:r}})}function bt(t,e,n){if(e==="anthropic"){ae(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ae(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var tc=64*1024*1024,Qt=class extends Error{};async function _a(t,e=tc){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Qt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function tt(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 Sa(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:null,o=r(n.input_tokens),s=r(n.output_tokens),i=a=>a??0,u=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let a={input_tokens:i(o),output_tokens:i(s),total_tokens:u};return o===null||s===null?{kind:"partial",usage:a}:{kind:"counts",usage:a}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:u}}}function Bn(t){let e=Sa(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function va(t){let e=Bn(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:nc(t)},completion_tokens_details:{reasoning_tokens:0}}}function nc(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function rc(t,e){let n=Sa(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function oc(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let l=n[a];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),u=r("total_ms");return o===null||s===null||i===null||u===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:u}}function sc(t,e){let n=oc(e);n&&(t.timing=n),t.outputSeconds=Ce(e)}function nt(t,e){rc(t,e),sc(t,e)}async function Gn(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 ka(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 ic(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 qn=class extends Error{};function ac(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 qn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function uc(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:ac(n.role,n.content)})}return e}function eo(t){return lt(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 lc(t,e,n,r,o,s,i){let u=Ut(s.id),a=t.stream===!0;if(s.model=ue(t),s.stream=a,await Gn(s,e,typeof t.model=="string"?t.model:void 0),a){let _;try{_=await Ft({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(f){if(f instanceof J){bt(r,"openai",f);return}if(f instanceof ye){Y(r,f.status,f.message);return}if(f instanceof be||f instanceof ce){r.setHeader("retry-after","2"),Y(r,503,f.message,"capacity_error");return}throw f}no(r);for await(let f of _.events){if(f.type==="error"){s.streamError=!0;let h=f.error,w=Oe(h),b=w??xe(s.id);w===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(f)}`),r.write(`event: error
39
- data: ${JSON.stringify({error:{message:b,type:h?.type??"upstream_error",code:h?.code??null}})}
37
+ `)}function Ti(t,e){if(!se(e))throw new _e("decision answer was not a JSON object");let n=e.answers;if(!se(n))throw new _e("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!se(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=se(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=zr(s.noul);if(u===null)throw new _e(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let u=o.choiceValues??[],a=s.choice;if(typeof a!="string")throw new _e(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new _e(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=Pn(s.confidence);if(d===null)throw new _e(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let m=zr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:u[l],confidence:d,probabilities:c});continue}case"score":{let u=o.levelLabels??[],a=Pn(s.score);if(a===null)throw new _e(`the score answer for "${o.key}" carries no numeric score to translate`);let l=Pn(s.confidence);if(l===null)throw new _e(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<u.length;c++){let p=zr(i[String(c)]);p!==null&&d.push({value:c,label:u[c],probability:p})}r.push({type:"score",name:o.name,score:a,confidence:l,probabilities:d});continue}}}return r}var ie=class extends Error{};async function Cn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ie(`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 ie(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Mn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new ie(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Oi="/v1/images/generations",$n="/v1/images/edits";function Pi(t){return t===Oi||t===$n}var Ci="/v1/images/models";async function Mi(t,e,n){if(t){if(t.model=ue({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 V=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},ad=16*1024*1024,$i=64*1024*1024;function Li(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 Jt(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 Ni(t,e,n,r,o,s){let i=s??(g=>console.error(g)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),a=null;for await(let g of u){if(g.type==="error"){let S=g.error??{},x=typeof S.message=="string"&&S.message.length>0&&ke(S.message)?S.message:null;throw x===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(g)}`),new V(502,"the image upstream failed while serving this request")):new V(502,`image upstream error: ${x}`)}if(g.type==="response.completed"){a=g.response??null;break}}if(a===null)throw new V(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ce(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new V(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Li(p)===null)throw new V(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Ui(t,e){if(t instanceof V)return t;if(t instanceof Ie)throw t;return t instanceof J?new V(404,t.message):new V(502,ft("image",t,e))}async function Di(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 Jt(r,new V(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 Fi(t,e){t&&(t.outputUnits=e.images.length)}function Bi(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 ud={model:!0,prompt:!0,response_format:!0,n:!0};async function qi(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??$i;try{if(t.method!=="POST")throw new V(405,`${String(t.method)} is not supported on ${Oi}`);let s;try{s=JSON.parse((await Cn(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new V(413,p.message):new V(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new V(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!ud[p])throw new V(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let u=i.prompt;if(typeof u!="string"||u.trim().length===0)throw new V(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new V(400,"model must be a string","model");await Mi(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new V(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new V(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",u.length,u.length),!await Di(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await Ni(n.clients,a,c,n.turn?he(n.turn):void 0,n.turn,r);Fi(n.turn,p),Bi(e,p)}catch(p){throw Ui(p,r)}}catch(s){if(s instanceof ie){Jt(e,new V(413,s.message));return}if(s instanceof V){Jt(e,s);return}throw s}}var ld={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ji(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??$i,s=n.maxImagePartBytes??ad;try{if(t.method!=="POST")throw new V(405,`${String(t.method)} is not supported on ${$n}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new V(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Mn(t,o)}catch(g){throw g instanceof ie?new V(413,g.message):new V(400,String(g instanceof Error?g.message:g))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new V(400,"prompt is required and must be a non-empty string field","prompt");let l=u.get("model");if(l!==null&&typeof l!="string")throw new V(400,"model must be a string field","model");let d=l===null?void 0:l;await Mi(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new V(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let g of u.keys())if(!ld[g])throw new V(400,`form field "${g}" 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[]).`,g);let p=[];for(let g of["image","image[]"])for(let S of u.getAll(g)){if(!(S instanceof File))throw new V(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",g);if(S.size>s)throw new V(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let x=new Uint8Array(await S.arrayBuffer()),k=Li(x);if(k===null)throw new V(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",g);p.push({bytes:x,mime:k})}if(p.length===0)throw new V(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Di(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:g,mime:S}of p)m.push({type:"input_image",image_url:`data:${S};base64,${Buffer.from(g).toString("base64")}`});try{let g=await Ni(n.clients,d,m,n.turn?he(n.turn):void 0,n.turn,r);Fi(n.turn,g),Bi(e,g)}catch(g){throw Ui(g,r)}}catch(i){if(i instanceof ie){Jt(e,new V(413,i.message));return}if(i instanceof V){Jt(e,i);return}throw i}}var Wt="/v1/audio/speech";function Xi(t){return t===Wt}var Hi=4096,Gi=18e4,Vi=5e3,dd=64*1024*1024,Ji=8,Wi=5,Ki=1024*1024,wt="voice_applied",Nn="X-Urun-Voice-Applied",F=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Yr(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 Un=class extends F{constructor(e){super(502,e)}};function Qi(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Zi(t){return new F(502,`the runtime's ${wt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Nn} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function cd(t,e,n){if(t){if(t.model=ue({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 ea(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var pd=2;function fd(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>pd)return!1;return!0}function md(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 zi=new WeakMap,Ln=new WeakMap;function gd(t,e){let n=Ln.get(t)??0;if(n>=Ji)throw new F(503,`this model's speech queue is full \u2014 ${Ji} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Wi}s`,void 0,Wi);Ln.set(t,n+1);let r=zi.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return zi.set(t,s),(async()=>{await r;try{return await e()}finally{Ln.set(t,(Ln.get(t)??1)-1),o()}})()}async function hd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new F(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 W))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(()=>{clearTimeout(s)})}function et(t,e){if(t instanceof F)return t;if(t instanceof Ie)throw t;return t instanceof J?new F(404,t.message):new F(502,ft("speech",t,e))}async function Yi(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return gd(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,g=!1,S,x=new Promise(E=>{S=E}),k=[],b,v=!1,f=null,y=()=>{f!==null&&(clearTimeout(b),b=setTimeout(()=>{v=!0,f?.()},o.capMs))},h=()=>{m&&!g&&k.length>=o.quietRunFrames&&(g=!0,S())},_=e.onOutputAudio(E=>{let A=Buffer.from(E,"base64");if(A.byteLength===0)return;y();let C=fd(A);if(!p){if(C)return;p=!0}if(C){k.push(A),h();return}for(let q of k)c(q);k.length=0,c(A),h()}),R=null,T,w;try{w=(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 A=()=>(clearTimeout(T),new Promise(N=>{T=setTimeout(N,s.capMs)})),C=A(),q=!1;for(;;){let N=w.next(),$=await Promise.race([N,C]);if($===void 0){q=!0,N.catch(()=>{});break}if($.done)break;let D=$.value;if(C=A(),D.type==="error"){let H=D.error??{};await w.return?.();let X=typeof H.message=="string"&&H.message.length>0&&ke(H.message)?H.message:null;throw X===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(D)}`),new F(502,"the speech upstream failed while serving this request")):new F(502,`speech upstream error: ${X}`)}if(D.type==="response.completed"){R=D.response??null,m=!0,a?.(R),h(),await w.return?.();break}}if(clearTimeout(T),q)throw new F(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(R===null)throw new F(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let B=new Promise(N=>{f=N});if(y(),await Promise.race([x,B]),clearTimeout(b),b=void 0,f=null,r.voice!==void 0){let N=R[wt];if(typeof N!="string"||N!==r.voice){let $=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof N=="string"?`${wt} ${JSON.stringify(N)}`:`no ${wt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new Un($):new F(502,$)}}if(!p)throw new F(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(v&&!g&&k.length<1)throw new F(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return R}catch(E){throw E instanceof Un||await hd(t,n,w,s.returnBoundMs),E}finally{clearTimeout(b),clearTimeout(T),_()}})}function yd(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Nn)),t.write(u,a=>{a||(s+=u.byteLength,ea(e,s))}),t.writableLength>Ki&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Ki} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[wt];if(typeof a=="string"){if(!Qi(a))throw Zi(a);t.addTrailers({[Nn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function wd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw et(s,r)}return o?!0:(Yr(n,new F(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 _d={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},vd="wav, pcm";async function ta(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??dd,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${Wt}`);let u;try{u=JSON.parse((await Cn(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof ie?new F(413,f.message):new F(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new F(400,"request body must be a JSON object");let a=u;for(let f of Object.keys(a))if(!_d[f])throw new F(400,`request field "${f}" 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.`,f);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new F(400,"input is required and must be a non-empty string","input");if(l.length>Hi)throw new F(400,`input is ${l.length} chars \u2014 over the ${Hi}-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 F(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new F(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new F(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 ${Wt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(f){throw et(f,r)}if(p.defect!==null)throw new F(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new F(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let g=a.response_format??"wav";if(g!=="wav"&&g!=="pcm")throw new F(400,`response_format ${JSON.stringify(g)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${vd} \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 F(400,"stream_format, when present, must be a string","stream_format");let S=a.speed;if(S!==void 0){if(typeof S!="number"||!Number.isFinite(S))throw new F(400,"speed, when present, must be a number","speed");if(S!==1)throw new F(400,`speed=${JSON.stringify(S)} 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 x=a.instructions;if(x!==void 0){if(typeof x!="string")throw new F(400,"instructions, when present, must be a string","instructions");if(x.trim().length>0)throw new F(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 cd(n.turn,n.clients,d);let k=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",k,k),!await wd(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new F(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 F(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 F(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(i())return;let b;try{b=await n.clients.speechSessionHandle(d)}catch(f){throw et(f,r)}let v;try{v=await n.clients.openAudioOn(b)}catch(f){throw et(f,r)}n.turn&&(n.turn.sessionId=v.sessionId);try{if(g==="wav"){let f=[],y=await Yi(n.clients,v,b,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Gi,returnBoundMs:n.turnReturnBoundMs??Vi},i,_=>f.push(_),_=>{n.turn&&(n.turn.outputSeconds=Ce(_))},r);if(y===null||i())return;let h=Buffer.concat(f);if(m===void 0){let _=y[wt];if(typeof _=="string"){if(!Qi(_))throw Zi(_);e.setHeader(Nn,_)}}ea(n.turn,h.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([md(h.byteLength),h]))}else{let f=yd(e,n.turn,i,m===void 0),y;try{y=await Yi(n.clients,v,b,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Gi,returnBoundMs:n.turnReturnBoundMs??Vi},i,f.sink,h=>{n.turn&&(n.turn.outputSeconds=Ce(h))},r)}catch(h){let _=et(h,r);if(!f.started())throw _;n.turn&&(n.turn.streamError=!0),f.fail(_);return}if(y===null)return;try{await f.finish(y)}catch(h){let _=et(h,r);n.turn&&(n.turn.streamError=!0),f.fail(_);return}}}catch(f){throw et(f,r)}}catch(u){if(u instanceof ie){Yr(e,new F(413,u.message));return}if(u instanceof F){Yr(e,u);return}throw u}}var Dn="/v1/audio/transcriptions";function na(t){return t===Dn}var ra="/v1/audio/models",bd=16*1024*1024,Sd=64*1024*1024,te=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Xr(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 oa(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 kd(t){if(!oa(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,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,l=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,d=t[u+14]|t[u+15]<<8;n={sampleRate:l,channels:a,bitsPerSample:d}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+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 xd(t,e,n){if(t){if(t.model=ue({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 Rd(t,e){t&&(t.outputUnits=e.seconds)}async function Ed(t,e,n,r,o,s,i){let u=i??(c=>console.error(c)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of a){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",g=typeof p.message=="string"&&p.message.length>0&&ke(p.message)?p.message:null;throw g===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new te(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new te(m==="invalid_request_error"?400:502,`transcription upstream error: ${g}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new te(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Ce(d)),ct(l,d)}function sa(t,e){if(t instanceof te)return t;if(t instanceof Ie)throw t;return t instanceof J?new te(404,t.message):new te(502,ft("transcription",t,e))}async function Ad(t,e,n,r){let o;try{o=await t(e)}catch(s){throw sa(s,r)}return o?!0:(Xr(n,new te(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 Id=new Set(["file","model","language","response_format"]);async function ia(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Sd,s=n.maxAudioPartBytes??bd;try{if(t.method!=="POST")throw new te(405,`${String(t.method)} is not supported on ${Dn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new te(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Mn(t,o)}catch(b){throw b instanceof ie?new te(413,b.message):new te(400,String(b instanceof Error?b.message:b))}let a=new Map;for(let b of u.keys()){if(!Id.has(b))throw new te(400,`form field "${b}" 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.`,b);a.set(b,(a.get(b)??0)+1)}for(let[b,v]of a)if(v>1)throw new te(400,`form field "${b}" appears ${v} 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`,b);let l=u.get("model");if(l!==null&&typeof l!="string")throw new te(400,"model must be a string field","model");let d=l===null?void 0:l,c=u.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new te(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=u.get("response_format")??"json";if(m!=="json")throw new te(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let g=u.get("file");if(!(g instanceof File))throw new te(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(g.size>s)throw new te(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let S=new Uint8Array(await g.arrayBuffer());if(!oa(S))throw new te(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 x=kd(S);if(x===null)throw new te(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 xd(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",S.length,S.length),!await Ad(n.transcriptionModels,d,e,r))return;let k=[{type:"input_audio",input_audio:{data:Buffer.from(S).toString("base64"),format:"wav"}}];try{let b=await Ed(n.clients,d,k,p,n.turn?he(n.turn):void 0,n.turn,r);Rd(n.turn,x),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw sa(b,r)}}catch(i){if(i instanceof ie){Xr(e,new te(413,i.message));return}if(i instanceof te){Xr(e,i);return}throw i}}var ua="/v1/usage/requests",aa=1e4,Td=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,qe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},_t=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var la=1024*1024;function Qr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new qe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new qe(`"${e}" must be an array of uuid strings`);if(n.length>aa)throw new qe(`"${e}" carries ${n.length} ids; at most ${aa} 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"||!Td.test(s))throw new qe(`"${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 da(t){return Qr(t,"inference_ids")}function Fn(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 _t(`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 _t(`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)}}var Hn=require("@urun-sh/core");var Zr="/partners/huggingface/v1/billing/requests";function Od(t){return Qr(t,"requestIds")}function Pd(t){return t>=200&&t<=399}function Cd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Pd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ca(t,e){let n=Od(t),r=await e(n);return Fn(r,n),Cd(r)}var Md={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function $d(t){return Md[t]??null}var ga=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Ld(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Nd(t){return t==="surface"}function Ud(t){let e=t?.ledgerFailureReason;return ga.includes(e)?e:"unknown"}var Dd=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],pa=["priced","unpriced"],Fd={written:pa,already_written:pa,skipped:Dd,failed:ga},og=Object.entries(Fd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Bd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function qd(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 jd=256,fa=4096,zt=12e4,Hd=250,Gd=8e3,Yt=[],ma=new Set,Xt=0,Kt=!1;var Vd=new Set;function Jd(){return Xt===0&&Yt.length===0}function Wd(){if(Jd()){Kt=!1;for(let t of[...Vd])t()}}function ha(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
38
+ `}function Kd(t){Re(process.stdout,t)}function ya(t,e){try{t(e)}catch{}}function wa(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Kd,o=$d(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ya(r,ha("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,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 u=e.catalog;if(u.kind==="unresolved"){i("model_unresolved",u.reason);return}let a;if(u.kind==="catalog")a={model_id:u.model_id,identity_kind:"catalog_model",variant:u.variant};else{if(u.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}a={model_id:u.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:qd(e),completed_at:e.ts,billable_outcome:Bd(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Yt.length>=fa){i("queue_full",`${Yt.length} ledger writes are already waiting (capacity ${fa}, ${Xt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Yt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Xt<jd&&(Xt+=1,zd())}async function zd(){try{for(;;){let t=Yd();if(t===void 0)return;ma.add(t);try{await Xd(t)}finally{ma.delete(t)}}}finally{Xt-=1,Wd()}}function Yd(){let t=Date.now();for(;;){let e=Yt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<zt)return e;vt(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 ${zt}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 Xd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);vt(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=Ld(o);if(s!==null){vt(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=Ud(o),u=Date.now()-t.queuedAt;if(Kt){vt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:u,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(Nd(i)&&u<zt){if(await Zd(Qd(t.attempts)),Kt||Date.now()-t.queuedAt>=zt){let a=Date.now()-t.queuedAt;vt(t,{outcome:"failed",reason:Kt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Kt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${zt}ms dwell bound (waited ${a}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}vt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:u,error:o instanceof Error?o.message:String(o)});return}}}function Qd(t){return Math.min(Gd,Hd*2**Math.max(0,t-1))}function Zd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function vt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ya(t.report,ha(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function no(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ec(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 ae(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Y(t,e,n,r="invalid_request_error",o){ae(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function ro(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Oe(r),u=i??xe(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let a=r?.code??null,l=o==="invalid_request_error"?400:a==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),ae(t,l,{error:{message:u,type:o,code:a}})}function Ee(t,e,n,r){ae(t,e,{type:"error",error:{type:n,message:r}})}function bt(t,e,n){if(e==="anthropic"){ae(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ae(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var tc=64*1024*1024,Qt=class extends Error{};async function _a(t,e=tc){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Qt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function tt(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 Sa(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:null,o=r(n.input_tokens),s=r(n.output_tokens),i=a=>a??0,u=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let a={input_tokens:i(o),output_tokens:i(s),total_tokens:u};return o===null||s===null?{kind:"partial",usage:a}:{kind:"counts",usage:a}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:u}}}function Bn(t){let e=Sa(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function va(t){let e=Bn(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:nc(t)},completion_tokens_details:{reasoning_tokens:0}}}function nc(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function rc(t,e){let n=Sa(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function oc(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let l=n[a];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),u=r("total_ms");return o===null||s===null||i===null||u===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:u}}function sc(t,e){let n=oc(e);n&&(t.timing=n),t.outputSeconds=Ce(e)}function nt(t,e){rc(t,e),sc(t,e)}async function Gn(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 ka(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 ic(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 qn=class extends Error{};function ac(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 qn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function uc(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:ac(n.role,n.content)})}return e}function eo(t){return lt(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 lc(t,e,n,r,o,s,i){let u=Ut(s.id),a=t.stream===!0;if(s.model=ue(t),s.stream=a,await Gn(s,e,typeof t.model=="string"?t.model:void 0),a){let b;try{b=await Ft({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(v){if(v instanceof J){bt(r,"openai",v);return}if(v instanceof ye){Y(r,v.status,v.message);return}if(v instanceof be||v instanceof ce){r.setHeader("retry-after","2"),Y(r,503,v.message,"capacity_error");return}throw v}no(r);for await(let v of b.events){if(v.type==="error"){s.streamError=!0;let f=v.error,y=Oe(f),h=y??xe(s.id);y===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(v)}`),r.write(`event: error
39
+ data: ${JSON.stringify({error:{message:h,type:f?.type??"upstream_error",code:f?.code??null}})}
40
40
 
41
- `),r.end();return}f.type==="response.completed"&&nt(s,f.response),r.write(`event: ${String(f.type??"message")}
42
- data: ${JSON.stringify(f)}
41
+ `),r.end();return}v.type==="response.completed"&&nt(s,v.response),r.write(`event: ${String(v.type??"message")}
42
+ data: ${JSON.stringify(v)}
43
43
 
44
44
  `)}r.write(`data: [DONE]
45
45
 
46
- `),r.end();return}let l;try{l=pt(n,t)}catch(_){if(_ instanceof ye){Y(r,_.status,_.message);return}throw _}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ue(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await kr(e,t,l,!1,he(s))}catch(_){if(_ instanceof J){bt(r,"openai",_);return}if(_ instanceof ye){Y(r,_.status,_.message);return}if(_ instanceof be||_ instanceof ce){r.setHeader("retry-after","2"),Y(r,503,_.message,"capacity_error");return}throw _}let g=[],v=null;for await(let _ of o.track(m,c,s)){if(g.push(_),_.type==="error"){ro(r,_,{inferenceId:s.id,operatorError:i});return}_.type==="response.completed"&&(v=_.response)}if(v==null){Y(r,502,"upstream produced no response.completed event","upstream_error");return}nt(s,v);let k=ct(g,v),S=Qe(p,lt(v).length,k);if(S){Y(r,502,Xe(c,S),"upstream_error");return}d&&n.remember(u,l,Sr(v,k),d),ae(r,200,{...v,id:u})}async function dc(t,e,n,r,o,s,i){let u=t.messages;if(!Array.isArray(u)){Y(n,400,"chat/completions requires a messages array");return}let a;try{a=bi(s,t)}catch(y){if(y instanceof de){Y(n,y.status,y.message);return}throw y}let l=String(t.model??"urun"),d=Ns(o.id),c;try{c=uc(u)}catch(y){if(y instanceof qn){Y(n,400,y.message);return}throw y}let p=ue(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Gn(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:c,stream:!0,tools:ic(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}:{}},he(o))}catch(y){if(y instanceof J){bt(n,"openai",y);return}if(y instanceof be||y instanceof ce){n.setHeader("retry-after","2"),Y(n,503,y.message,"capacity_error");return}throw y}if(t.stream===!0){a?ec(n):no(n);let y=[],x=new Fe,T="",C=a?new ht(a,V=>{n.write(`data: ${JSON.stringify(tt(d,l,{content:V},null))}
46
+ `),r.end();return}let l;try{l=pt(n,t)}catch(b){if(b instanceof ye){Y(r,b.status,b.message);return}throw b}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ue(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await kr(e,t,l,!1,he(s))}catch(b){if(b instanceof J){bt(r,"openai",b);return}if(b instanceof ye){Y(r,b.status,b.message);return}if(b instanceof be||b instanceof ce){r.setHeader("retry-after","2"),Y(r,503,b.message,"capacity_error");return}throw b}let g=[],S=null;for await(let b of o.track(m,c,s)){if(g.push(b),b.type==="error"){ro(r,b,{inferenceId:s.id,operatorError:i});return}b.type==="response.completed"&&(S=b.response)}if(S==null){Y(r,502,"upstream produced no response.completed event","upstream_error");return}nt(s,S);let x=ct(g,S),k=Qe(p,lt(S).length,x);if(k){Y(r,502,Xe(c,k),"upstream_error");return}d&&n.remember(u,l,Sr(S,x),d),ae(r,200,{...S,id:u})}async function dc(t,e,n,r,o,s,i){let u=t.messages;if(!Array.isArray(u)){Y(n,400,"chat/completions requires a messages array");return}let a;try{a=bi(s,t)}catch(w){if(w instanceof de){Y(n,w.status,w.message);return}throw w}let l=String(t.model??"urun"),d=Ns(o.id),c;try{c=uc(u)}catch(w){if(w instanceof qn){Y(n,400,w.message);return}throw w}let p=ue(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Gn(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:c,stream:!0,tools:ic(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}:{}},he(o))}catch(w){if(w instanceof J){bt(n,"openai",w);return}if(w instanceof be||w instanceof ce){n.setHeader("retry-after","2"),Y(n,503,w.message,"capacity_error");return}throw w}if(t.stream===!0){a?ec(n):no(n);let w=[],E=new Fe,A="",C=a?new ht(a,B=>{n.write(`data: ${JSON.stringify(tt(d,l,{content:B},null))}
47
47
 
48
- `)}):null,B=V=>{C?.flush(),n.write(V),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
48
+ `)}):null,q=B=>{C?.flush(),n.write(B),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
49
49
 
50
50
  `),n.write(`data: ${JSON.stringify(tt(d,l,{role:"assistant"},null))}
51
51
 
52
- `);for await(let j of r.track(g,p,o)){y.push(j);let X=dt(j);if(j.type==="response.output_text.delta"&&typeof j.delta=="string")T+=j.delta,C?C.push(j.delta):n.write(`data: ${JSON.stringify(tt(d,l,{content:j.delta},null))}
52
+ `);for await(let H of r.track(g,p,o)){w.push(H);let X=dt(H);if(H.type==="response.output_text.delta"&&typeof H.delta=="string")A+=H.delta,C?C.push(H.delta):n.write(`data: ${JSON.stringify(tt(d,l,{content:H.delta},null))}
53
53
 
54
- `);else if(j.type==="response.reasoning_text.delta"&&typeof j.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(tt(d,l,{reasoning_content:j.delta},null))}
54
+ `);else if(H.type==="response.reasoning_text.delta"&&typeof H.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(tt(d,l,{reasoning_content:H.delta},null))}
55
55
 
56
- `);else if(X){C?.flush();let{call:M,isNew:q}=x.add(X),z=q?{index:X.tool_index,id:M.id??`call_${X.tool_index}`,type:"function",function:{name:M.name??"",arguments:X.delta}}:{index:X.tool_index,function:{arguments:X.delta}};n.write(`data: ${JSON.stringify(tt(d,l,{tool_calls:[z]},null))}
56
+ `);else if(X){C?.flush();let{call:M,isNew:j}=E.add(X),z=j?{index:X.tool_index,id:M.id??`call_${X.tool_index}`,type:"function",function:{name:M.name??"",arguments:X.delta}}:{index:X.tool_index,function:{arguments:X.delta}};n.write(`data: ${JSON.stringify(tt(d,l,{tool_calls:[z]},null))}
57
57
 
58
- `)}else if(j.type==="error"){o.streamError=!0;let M=j.error??{},q=Oe(M),z=q??xe(o.id);q===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(j)}`),B(`data: ${JSON.stringify({error:{message:z,type:M.type??"upstream_error",code:M.code??null}})}
58
+ `)}else if(H.type==="error"){o.streamError=!0;let M=H.error??{},j=Oe(M),z=j??xe(o.id);j===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(H)}`),q(`data: ${JSON.stringify({error:{message:z,type:M.type??"upstream_error",code:M.code??null}})}
59
59
 
60
- `);return}}let V=eo(Te(y)),N=Qe(m,x.size+V.length,T);if(N){o.streamError=!0,B(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(p,N)}})}
60
+ `);return}}let B=eo(Te(w)),N=Qe(m,E.size+B.length,A);if(N){o.streamError=!0,q(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(p,N)}})}
61
61
 
62
- `);return}C?.flush(),x.size===0&&V.length>0&&n.write(`data: ${JSON.stringify(tt(d,l,{tool_calls:V},null))}
62
+ `);return}C?.flush(),E.size===0&&B.length>0&&n.write(`data: ${JSON.stringify(tt(d,l,{tool_calls:B},null))}
63
63
 
64
- `);let $=x.size>0||V.length>0;n.write(`data: ${JSON.stringify(tt(d,l,{},$?"tool_calls":"stop"))}
64
+ `);let $=E.size>0||B.length>0;n.write(`data: ${JSON.stringify(tt(d,l,{},$?"tool_calls":"stop"))}
65
65
 
66
- `);let D=Bn(Te(y));nt(o,Te(y)),D&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:va(Te(y))})}
66
+ `);let D=Bn(Te(w));nt(o,Te(w)),D&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:va(Te(w))})}
67
67
 
68
68
  `),n.write(`data: [DONE]
69
69
 
70
- `),n.end();return}finally{C?.flush(),C?.dispose()}}let v="",k="",S=[],_=new Fe;for await(let y of r.track(g,p,o)){S.push(y),y.type==="response.output_text.delta"&&typeof y.delta=="string"&&(v+=y.delta),y.type==="response.reasoning_text.delta"&&typeof y.delta=="string"&&(k+=y.delta);let x=dt(y);if(x&&_.add(x),y.type==="error"){ro(n,y,{inferenceId:o.id,operatorError:i});return}}let f=Te(S);nt(o,f);let h=eo(f),w=h.length>0?h:eo({output:_.items()}),b=Qe(m,w.length,v);if(b){Y(n,502,Xe(p,b),"upstream_error");return}let R=w.map(({index:y,...x})=>x),E={role:"assistant",content:v||null},A=k||ka(f);A&&(E.reasoning_content=A),R.length>0&&(E.tool_calls=R),ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:E,finish_reason:R.length>0?"tool_calls":"stop"}],usage:va(f)})}var xa="sense-latest";async function cc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){Y(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:xa,u=ue({model:i});if(o.model=u,o.stream=!1,t.state===void 0||t.state===null){Y(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){Y(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){Y(n,400,"systemone media, when present, must be an array");return}let l=await Ra(t,i,u,e,n,r,o,s);l!==null&&ae(n,200,l.answer)}async function Ra(t,e,n,r,o,s,i,u){let a={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=a;let l=performance.now();s.model(n),await Gn(i,r,e),a.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},he(i))}catch(S){if(S instanceof J)return bt(o,"openai",S),null;if(S instanceof be||S instanceof ce)return o.setHeader("retry-after","2"),Y(o,503,S.message,"capacity_error"),null;throw S}a.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let S of s.track(d,n,i))if(m===null&&(m=performance.now(),a.first_event_ms=Math.round(m-c)),p.push(S),S.type==="error")return ro(o,S,{inferenceId:i.id,operatorError:u}),null}catch(S){if(S instanceof J)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),bt(o,"openai",S),null;if(S instanceof be||S instanceof ce)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),Y(o,503,S.message,"capacity_error"),null;throw m!==null&&(a.stream_ms=Math.round(performance.now()-m)),S}m!==null&&(a.stream_ms=Math.round(performance.now()-m));let g=Te(p);if(g==null)return Y(o,502,"upstream produced no response.completed event","upstream_error"),null;nt(i,g);let v=ct(p,g),k;try{k=JSON.parse(v)}catch{return Y(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(k===null||typeof k!="object"||Array.isArray(k))return Y(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"timing"in k){let S=k.timing;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"question_fwd_ms"in S&&"head_ms"in S){let _=f=>typeof f=="number"&&Number.isFinite(f)&&f>=0?Math.round(f):null;a.question_fwd_ms=_(S.question_fwd_ms),a.head_ms=_(S.head_ms)}}return{answer:k,completed:g}}async function pc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){Y(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:xa,u=ue({model:i});o.model=u,o.stream=!1;let a;try{a=Ei(t,i)}catch(p){if(p instanceof U){Y(n,400,p.message);return}throw p}let l=await Ra(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=Ti(a.specs,l.answer)}catch(p){if(p instanceof _e){Y(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;ae(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function fc(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Zt=class extends Error{};function jn(t){return new Zt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function mc(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 gc(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 Zt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function hc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw jn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw jn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function yc(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 jn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let u=String(i.type??"");if(u==="text")o+=String(i.text??"");else if(u==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(u==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:hc(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw jn(u)}}return s(),r}function to(t){return lt(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 wc(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ee(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){Ee(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ee(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(E=>typeof E!="string"))){Ee(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=Us(o.id),l=[],d;try{t.system&&l.push({role:"system",content:fc(t.system)});for(let E of i)l.push(...yc(E));d=gc(t.tool_choice)}catch(E){if(E instanceof Zt){Ee(n,400,"invalid_request_error",E.message);return}throw E}let c=ue(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Gn(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:mc(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},he(o))}catch(E){if(E instanceof J){bt(n,"anthropic",E);return}if(E instanceof be||E instanceof ce){n.setHeader("retry-after","2"),Ee(n,503,"capacity_error",E.message);return}throw E}let g=(E,A)=>{n.destroyed||n.write(`event: ${E}
71
- data: ${JSON.stringify({type:E,...A})}
70
+ `),n.end();return}finally{C?.flush(),C?.dispose()}}let S="",x="",k=[],b=new Fe;for await(let w of r.track(g,p,o)){k.push(w),w.type==="response.output_text.delta"&&typeof w.delta=="string"&&(S+=w.delta),w.type==="response.reasoning_text.delta"&&typeof w.delta=="string"&&(x+=w.delta);let E=dt(w);if(E&&b.add(E),w.type==="error"){ro(n,w,{inferenceId:o.id,operatorError:i});return}}let v=Te(k);nt(o,v);let f=eo(v),y=f.length>0?f:eo({output:b.items()}),h=Qe(m,y.length,S);if(h){Y(n,502,Xe(p,h),"upstream_error");return}let _=y.map(({index:w,...E})=>E),R={role:"assistant",content:S||null},T=x||ka(v);T&&(R.reasoning_content=T),_.length>0&&(R.tool_calls=_),ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:R,finish_reason:_.length>0?"tool_calls":"stop"}],usage:va(v)})}var xa="sense-latest";async function cc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){Y(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:xa,u=ue({model:i});if(o.model=u,o.stream=!1,t.state===void 0||t.state===null){Y(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){Y(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){Y(n,400,"systemone media, when present, must be an array");return}let l=await Ra(t,i,u,e,n,r,o,s);l!==null&&ae(n,200,l.answer)}async function Ra(t,e,n,r,o,s,i,u){let a={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=a;let l=performance.now();s.model(n),await Gn(i,r,e),a.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},he(i))}catch(k){if(k instanceof J)return bt(o,"openai",k),null;if(k instanceof be||k instanceof ce)return o.setHeader("retry-after","2"),Y(o,503,k.message,"capacity_error"),null;throw k}a.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let k of s.track(d,n,i))if(m===null&&(m=performance.now(),a.first_event_ms=Math.round(m-c)),p.push(k),k.type==="error")return ro(o,k,{inferenceId:i.id,operatorError:u}),null}catch(k){if(k instanceof J)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),bt(o,"openai",k),null;if(k instanceof be||k instanceof ce)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),Y(o,503,k.message,"capacity_error"),null;throw m!==null&&(a.stream_ms=Math.round(performance.now()-m)),k}m!==null&&(a.stream_ms=Math.round(performance.now()-m));let g=Te(p);if(g==null)return Y(o,502,"upstream produced no response.completed event","upstream_error"),null;nt(i,g);let S=ct(p,g),x;try{x=JSON.parse(S)}catch{return Y(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(x===null||typeof x!="object"||Array.isArray(x))return Y(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof x=="object"&&x!==null&&!Array.isArray(x)&&"timing"in x){let k=x.timing;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"question_fwd_ms"in k&&"head_ms"in k){let b=v=>typeof v=="number"&&Number.isFinite(v)&&v>=0?Math.round(v):null;a.question_fwd_ms=b(k.question_fwd_ms),a.head_ms=b(k.head_ms)}}return{answer:x,completed:g}}async function pc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){Y(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:xa,u=ue({model:i});o.model=u,o.stream=!1;let a;try{a=Ei(t,i)}catch(p){if(p instanceof U){Y(n,400,p.message);return}throw p}let l=await Ra(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=Ti(a.specs,l.answer)}catch(p){if(p instanceof _e){Y(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;ae(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function fc(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Zt=class extends Error{};function jn(t){return new Zt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function mc(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 gc(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 Zt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function hc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw jn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw jn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function yc(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 jn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let u=String(i.type??"");if(u==="text")o+=String(i.text??"");else if(u==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(u==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:hc(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw jn(u)}}return s(),r}function to(t){return lt(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 wc(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ee(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){Ee(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ee(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(R=>typeof R!="string"))){Ee(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=Us(o.id),l=[],d;try{t.system&&l.push({role:"system",content:fc(t.system)});for(let R of i)l.push(...yc(R));d=gc(t.tool_choice)}catch(R){if(R instanceof Zt){Ee(n,400,"invalid_request_error",R.message);return}throw R}let c=ue(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Gn(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:mc(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},he(o))}catch(R){if(R instanceof J){bt(n,"anthropic",R);return}if(R instanceof be||R instanceof ce){n.setHeader("retry-after","2"),Ee(n,503,"capacity_error",R.message);return}throw R}let g=(R,T)=>{n.destroyed||n.write(`event: ${R}
71
+ data: ${JSON.stringify({type:R,...T})}
72
72
 
73
- `)};if(t.stream===!0){let E=r.track(m,c,o);no(n),g("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let A=0,y="",x=0,T="none",C=()=>T,B=-1,V=-1,N=new Fe,$=[],D=()=>{T!=="none"&&(T="none",g("content_block_stop",{index:B}))},j=(Q,ne)=>{D(),T=Q,B=x++,g("content_block_start",{index:B,content_block:ne})};for await(let Q of E){if(n.destroyed)break;$.push(Q);let ne=dt(Q);if(Q.type==="response.reasoning_text.delta"&&typeof Q.delta=="string")C()!=="thinking"&&j("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:B,delta:{type:"thinking_delta",thinking:Q.delta}});else if(Q.type==="response.output_text.delta"&&typeof Q.delta=="string")C()!=="text"&&j("text",{type:"text",text:""}),A+=1,y+=Q.delta,g("content_block_delta",{index:B,delta:{type:"text_delta",text:Q.delta}});else if(ne){let{call:ve}=N.add(ne);(C()!=="tool"||ne.tool_index!==V)&&(V=ne.tool_index,j("tool",{type:"tool_use",id:ve.id??`call_${ne.tool_index}`,name:ve.name??"",input:{}})),ne.delta&&g("content_block_delta",{index:B,delta:{type:"input_json_delta",partial_json:ne.delta}})}else if(Q.type==="error"){o.streamError=!0;let ve=Q.error,He=Oe(ve);He===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Q)}`),g("error",{error:{type:"api_error",message:He??xe(o.id)}}),n.end();return}}if(n.destroyed)return;let X=Te($),M=lt(X),q=Qe(p,N.size+M.length,y);if(q){o.streamError=!0,g("error",{error:{type:"api_error",message:Xe(c,q)}}),n.end();return}D();let z=[];if(N.size===0)try{z=to(X)}catch(Q){o.streamError=!0;let ne=fe(Q,{inferenceId:o.id});ne.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Q instanceof Error?Q.message:Q)}`),g("error",{error:{type:"api_error",message:ne.message}}),n.end();return}x===0&&z.length===0&&(j("text",{type:"text",text:""}),D()),z.forEach(Q=>{let ne=x++;g("content_block_start",{index:ne,content_block:{...Q,input:{}}}),g("content_block_delta",{index:ne,delta:{type:"input_json_delta",partial_json:JSON.stringify(Q.input??{})}}),g("content_block_stop",{index:ne})});let je=N.size>0||z.length>0,rt=Bn(X);nt(o,X),g("message_delta",{delta:{stop_reason:je?"tool_use":"end_turn"},usage:rt?{input_tokens:rt.input_tokens,output_tokens:rt.output_tokens}:{output_tokens:A}}),g("message_stop",{}),n.end();return}let v="",k="",S=[],_=new Fe;for await(let E of r.track(m,c,o)){S.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(v+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(k+=E.delta);let A=dt(E);if(A&&_.add(A),E.type==="error"){let y=E.error,x=y?.type==="invalid_request_error",T=Oe(y);T===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(E)}`),Ee(n,x?400:502,x?"invalid_request_error":"api_error",T??xe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let f=Te(S);nt(o,f);let h;try{h=to(f),h.length===0&&_.size>0&&(h=to({output:_.items()}))}catch(E){let A=fe(E,{inferenceId:o.id});A.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(E instanceof Error?E.message:E)}`),Ee(n,502,"api_error",A.message);return}let w=Qe(p,h.length,v);if(w){Ee(n,502,"api_error",Xe(c,w));return}let b=[],R=k||ka(f);R&&b.push({type:"thinking",thinking:R}),(v||h.length===0)&&b.push({type:"text",text:v}),b.push(...h),ae(n,200,{id:a,type:"message",role:"assistant",content:b,model:u,stop_reason:h.length>0?"tool_use":"end_turn",usage:Bn(f)??{input_tokens:0,output_tokens:0}})}function _c(t){Re(process.stdout,t)}function vc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??_c,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new ze;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),g=(f,h,w,b,R)=>m?Ee(c,f,b,h):Y(c,f,h,w,R),v=br(p.pathname),k=p.pathname.startsWith("/partners/"),S=v||k?{id:Nt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;S&&(c.setHeader($s,S.id),c.once("close",()=>{let f=Ds({turn:S,method:d.method??"",path:p.pathname,res:c});i(Fs(f)),a?.(f),wa({record:f,ledger:t.ledger??null,req:d})}));let _=()=>Ls(p.pathname,S);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ae(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ae(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=p.pathname===ua?"canonical":p.pathname===Zr?"huggingface":null;if(f){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let R=t.usage;if(!R){g(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let E=R.authorize(d),A;try{A=await _a(d,la)}catch(T){if(T instanceof Qt){g(413,T.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let y=T=>R.lookup(E,T),x;try{if(f==="canonical"){let T=da(A),C=await y(T);Fn(C,T),x={requests:C}}else x=await ca(A,y)}catch(T){if(T instanceof qe){g(T.status,T.message,"invalid_request_error","invalid_request_error");return}throw T}ae(c,200,x);return}if(d.method==="GET"&&p.pathname===Tt){let R=await s(d);if(S&&(S.org=R.tenant??null),!R.openRouterModels){g(501,`GET ${Tt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ae(c,200,await R.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Zr} and GET ${Tt}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(S&&(S.org=h.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Tt}),c.end();return}ae(c,200,await h.listModels());return}if(d.method==="GET"&&p.pathname===Ci){if(!h.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ae(c,200,await h.listImageModels());return}if(Pi(p.pathname)){if(!h.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let R={clients:h,imageModels:h.supportsImages,stats:l,turn:_(),operatorLog:u};p.pathname===$n?await ji(d,c,R):await qi(d,c,R);return}if(d.method==="GET"&&p.pathname===ra){if(!h.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ae(c,200,await h.listSpeechToTextModels());return}if(na(p.pathname)){if(!h.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Dn}`,"not_implemented","not_implemented_error");return}let R={clients:h,transcriptionModels:h.supportsTranscription,stats:l,turn:_(),operatorLog:u};await ia(d,c,R);return}if(Xi(p.pathname)){if(!h.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Wt}`,"not_implemented","not_implemented_error");return}let R={clients:h,speechModels:h.supportsSpeech,stats:l,turn:_(),operatorLog:u};await ta(d,c,R);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let w;try{w=await _a(d)}catch(R){if(R instanceof Qt){g(413,R.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=Buffer.byteLength(JSON.stringify(w));if(p.pathname==="/v1/responses"){l.request("responses",b,b),await lc(w,h,Dt(h),c,l,_(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",b,b),await dc(w,h,c,l,_(),d.headers[Jr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",b,b),await cc(w,h,c,l,_(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",b,b),await pc(w,h,c,l,_(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",b,b),await wc(w,h,c,l,_(),u);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",b,b),Ee(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let h=String(f instanceof Error?f.message:f);if(!c.headersSent){let R=o?.(f)??null;if(R){R.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${R.operatorDetail}`),g(R.status,h,R.openaiType,R.anthropicType,R.code);return}if(f instanceof Hn.SessionAllocationError){let A=bn(f.code);if(A){let y=f.retryAfterSeconds??(A.status===429?30:void 0);y!==void 0&&c.setHeader("Retry-After",String(y)),g(A.status,Bt(A,f.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(f instanceof Hn.SessionFailedError){let A=Sn(f);if(A){let y=A.status===429?30:void 0;y!==void 0&&c.setHeader("Retry-After",String(y)),g(A.status,Bt(A,f.status.sessionId?`session ${f.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(f instanceof _t){g(502,h,"upstream_error","api_error");return}if(f instanceof Se){f.retryable&&c.setHeader("Retry-After","1");let A=fe(f,{inferenceId:S?.id??null});A.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),g(502,A.message,"upstream_error","api_error",f.code);return}if(f instanceof De){c.setHeader("Retry-After",String(f.retryAfterSeconds)),g(f.status,h,f.status===429?"capacity_error":"upstream_error",f.status===429?"rate_limit_error":"overloaded_error",f.code);return}let E=fe(f,{inferenceId:S?.id??null});E.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),g(500,E.message,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let w=f instanceof Se?f.code:null,b=fe(f,{inferenceId:S?.id??null});b.redacted&&u(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),c.destroyed||(m?c.write(`event: error
74
- data: ${JSON.stringify({type:"error",error:{type:"api_error",message:b.message}})}
73
+ `)};if(t.stream===!0){let R=r.track(m,c,o);no(n),g("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let T=0,w="",E=0,A="none",C=()=>A,q=-1,B=-1,N=new Fe,$=[],D=()=>{A!=="none"&&(A="none",g("content_block_stop",{index:q}))},H=(Q,ne)=>{D(),A=Q,q=E++,g("content_block_start",{index:q,content_block:ne})};for await(let Q of R){if(n.destroyed)break;$.push(Q);let ne=dt(Q);if(Q.type==="response.reasoning_text.delta"&&typeof Q.delta=="string")C()!=="thinking"&&H("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:q,delta:{type:"thinking_delta",thinking:Q.delta}});else if(Q.type==="response.output_text.delta"&&typeof Q.delta=="string")C()!=="text"&&H("text",{type:"text",text:""}),T+=1,w+=Q.delta,g("content_block_delta",{index:q,delta:{type:"text_delta",text:Q.delta}});else if(ne){let{call:ve}=N.add(ne);(C()!=="tool"||ne.tool_index!==B)&&(B=ne.tool_index,H("tool",{type:"tool_use",id:ve.id??`call_${ne.tool_index}`,name:ve.name??"",input:{}})),ne.delta&&g("content_block_delta",{index:q,delta:{type:"input_json_delta",partial_json:ne.delta}})}else if(Q.type==="error"){o.streamError=!0;let ve=Q.error,He=Oe(ve);He===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Q)}`),g("error",{error:{type:"api_error",message:He??xe(o.id)}}),n.end();return}}if(n.destroyed)return;let X=Te($),M=lt(X),j=Qe(p,N.size+M.length,w);if(j){o.streamError=!0,g("error",{error:{type:"api_error",message:Xe(c,j)}}),n.end();return}D();let z=[];if(N.size===0)try{z=to(X)}catch(Q){o.streamError=!0;let ne=fe(Q,{inferenceId:o.id});ne.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Q instanceof Error?Q.message:Q)}`),g("error",{error:{type:"api_error",message:ne.message}}),n.end();return}E===0&&z.length===0&&(H("text",{type:"text",text:""}),D()),z.forEach(Q=>{let ne=E++;g("content_block_start",{index:ne,content_block:{...Q,input:{}}}),g("content_block_delta",{index:ne,delta:{type:"input_json_delta",partial_json:JSON.stringify(Q.input??{})}}),g("content_block_stop",{index:ne})});let je=N.size>0||z.length>0,rt=Bn(X);nt(o,X),g("message_delta",{delta:{stop_reason:je?"tool_use":"end_turn"},usage:rt?{input_tokens:rt.input_tokens,output_tokens:rt.output_tokens}:{output_tokens:T}}),g("message_stop",{}),n.end();return}let S="",x="",k=[],b=new Fe;for await(let R of r.track(m,c,o)){k.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(S+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(x+=R.delta);let T=dt(R);if(T&&b.add(T),R.type==="error"){let w=R.error,E=w?.type==="invalid_request_error",A=Oe(w);A===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),Ee(n,E?400:502,E?"invalid_request_error":"api_error",A??xe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let v=Te(k);nt(o,v);let f;try{f=to(v),f.length===0&&b.size>0&&(f=to({output:b.items()}))}catch(R){let T=fe(R,{inferenceId:o.id});T.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),Ee(n,502,"api_error",T.message);return}let y=Qe(p,f.length,S);if(y){Ee(n,502,"api_error",Xe(c,y));return}let h=[],_=x||ka(v);_&&h.push({type:"thinking",thinking:_}),(S||f.length===0)&&h.push({type:"text",text:S}),h.push(...f),ae(n,200,{id:a,type:"message",role:"assistant",content:h,model:u,stop_reason:f.length>0?"tool_use":"end_turn",usage:Bn(v)??{input_tokens:0,output_tokens:0}})}function _c(t){Re(process.stdout,t)}function vc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??_c,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new ze;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),g=(v,f,y,h,_)=>m?Ee(c,v,h,f):Y(c,v,f,y,_),S=br(p.pathname),x=p.pathname.startsWith("/partners/"),k=S||x?{id:Nt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;k&&(c.setHeader($s,k.id),c.once("close",()=>{let v=Ds({turn:k,method:d.method??"",path:p.pathname,res:c});i(Fs(v)),a?.(v),wa({record:v,ledger:t.ledger??null,req:d})}));let b=()=>Ls(p.pathname,k);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ae(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ae(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let v=p.pathname===ua?"canonical":p.pathname===Zr?"huggingface":null;if(v){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let _=t.usage;if(!_){g(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let R=_.authorize(d),T;try{T=await _a(d,la)}catch(A){if(A instanceof Qt){g(413,A.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let w=A=>_.lookup(R,A),E;try{if(v==="canonical"){let A=da(T),C=await w(A);Fn(C,A),E={requests:C}}else E=await ca(T,w)}catch(A){if(A instanceof qe){g(A.status,A.message,"invalid_request_error","invalid_request_error");return}throw A}ae(c,200,E);return}if(d.method==="GET"&&p.pathname===Tt){let _=await s(d);if(k&&(k.org=_.tenant??null),!_.openRouterModels){g(501,`GET ${Tt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ae(c,200,await _.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Zr} and GET ${Tt}`,"invalid_request_error","not_found_error");return}let f=await s(d);if(k&&(k.org=f.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Tt}),c.end();return}ae(c,200,await f.listModels());return}if(d.method==="GET"&&p.pathname===Ci){if(!f.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ae(c,200,await f.listImageModels());return}if(Pi(p.pathname)){if(!f.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let _={clients:f,imageModels:f.supportsImages,stats:l,turn:b(),operatorLog:u};p.pathname===$n?await ji(d,c,_):await qi(d,c,_);return}if(d.method==="GET"&&p.pathname===ra){if(!f.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ae(c,200,await f.listSpeechToTextModels());return}if(na(p.pathname)){if(!f.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Dn}`,"not_implemented","not_implemented_error");return}let _={clients:f,transcriptionModels:f.supportsTranscription,stats:l,turn:b(),operatorLog:u};await ia(d,c,_);return}if(Xi(p.pathname)){if(!f.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Wt}`,"not_implemented","not_implemented_error");return}let _={clients:f,speechModels:f.supportsSpeech,stats:l,turn:b(),operatorLog:u};await ta(d,c,_);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await _a(d)}catch(_){if(_ instanceof Qt){g(413,_.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let h=Buffer.byteLength(JSON.stringify(y));if(p.pathname==="/v1/responses"){l.request("responses",h,h),await lc(y,f,Dt(f),c,l,b(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",h,h),await dc(y,f,c,l,b(),d.headers[Jr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",h,h),await cc(y,f,c,l,b(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",h,h),await pc(y,f,c,l,b(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",h,h),await wc(y,f,c,l,b(),u);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",h,h),Ee(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(v=>{let f=String(v instanceof Error?v.message:v);if(!c.headersSent){let _=o?.(v)??null;if(_){_.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${_.operatorDetail}`),g(_.status,f,_.openaiType,_.anthropicType,_.code);return}if(v instanceof Hn.SessionAllocationError){let T=bn(v.code);if(T){let w=v.retryAfterSeconds??(T.status===429?30:void 0);w!==void 0&&c.setHeader("Retry-After",String(w)),g(T.status,Bt(T,v.code??void 0),T.openaiType,T.anthropicType,T.code);return}}if(v instanceof Hn.SessionFailedError){let T=Sn(v);if(T){let w=T.status===429?30:void 0;w!==void 0&&c.setHeader("Retry-After",String(w)),g(T.status,Bt(T,v.status.sessionId?`session ${v.status.sessionId}`:void 0),T.openaiType,T.anthropicType,T.code);return}}if(v instanceof _t){g(502,f,"upstream_error","api_error");return}if(v instanceof Se){v.retryable&&c.setHeader("Retry-After","1");let T=fe(v,{inferenceId:k?.id??null});T.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${v instanceof Error?`${v.name}: ${v.message}`:we(v)}`),g(502,T.message,"upstream_error","api_error",v.code);return}if(v instanceof De){c.setHeader("Retry-After",String(v.retryAfterSeconds)),g(v.status,f,v.status===429?"capacity_error":"upstream_error",v.status===429?"rate_limit_error":"overloaded_error",v.code);return}let R=fe(v,{inferenceId:k?.id??null});R.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${v instanceof Error?`${v.name}: ${v.message}`:we(v)}`),g(500,R.message,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0);let y=v instanceof Se?v.code:null,h=fe(v,{inferenceId:k?.id??null});h.redacted&&u(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${v instanceof Error?`${v.name}: ${v.message}`:we(v)}`),c.destroyed||(m?c.write(`event: error
74
+ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h.message}})}
75
75
 
76
- `):c.write(`data: ${JSON.stringify({error:{message:b.message,type:"upstream_error",code:w}})}
76
+ `):c.write(`data: ${JSON.stringify({error:{message:h.message,type:"upstream_error",code:y}})}
77
77
 
78
78
  `)),c.end()})}}function Ea(t){let{clients:e,apiKey:n}=t,r=(0,ba.createServer)(vc(t)),o=Vs(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=Gr(r,{resolver:Ri(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(u=>(o.close(),s(),i(u))),Cs(r,{clients:e,apiKey:n}),r}var Vn=require("@urun-sh/core/internal");var bc={ensureWebRTC:Vn.ensureNodeWebRTC,webrtcUnavailableReason:Vn.nodeWebRTCUnavailableReason,audioBackend:rn};async function Aa(t=bc){try{await t.ensureWebRTC()}catch(n){return{ok:!1,reason:`the WebRTC bootstrap threw: ${String(n)}`}}let e=t.webrtcUnavailableReason();if(e)return{ok:!1,reason:`${e} \u2014 this artifact would join every session doc/KV-only and every token stream would error. Either "werift" is missing from the deployment directory (npm lane), or it was marked --external in a single-file build, where nothing can ever resolve it (bunfs: "Cannot find package 'werift' from '/$bunfs/root/\u2026'").`};try{(await t.audioBackend()).createSource()}catch(n){return{ok:!1,reason:`the werift/opus audio backend could not be constructed: ${String(n)}`}}return{ok:!0,reason:null}}function kc(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?kn(n,"URUN_CATALOG_URL"):"",o=(t.URUN_CATALOG_ANON_KEY??"").trim();return!r||!o?(e(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
79
- `),null):{catalogUrl:r,anonKey:o}}function xc(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:kc(H.default.env,r=>H.default.stderr.write(r)),decisionPool:ss(H.default.env,H.default.env.HOSTNAME)??void 0},n=ls(e);return{router:n,decision:e.decisionPool?ds(e,n):null}}async function Ia(t,e,n){let r=(0,oo.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{H.default.stderr.write(`failed to launch ${t}: ${String(s)}
80
- `),o(127)})})}function Ta(){return ri(H.default.env,L,Ae.existsSync)}function Pa(t){for(let[e,n]of Object.entries(Tr(t)))H.default.stdout.write(`export ${e}=${n}
81
- `)}async function Oa(t,e){let n=mt(H.default.env),r=e?Pr(n):void 0,{router:o,decision:s}=xc(n);s&&(s.boot().then(()=>s.reap()).catch(c=>H.default.stderr.write(`[decision-pool] boot FAILED: ${String(c instanceof Error?c.message:c)}
82
- `)),setInterval(()=>s.reap(),5e3).unref());let i=null,u=d=>{if(i===null){let c=a.address();if(c===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");i=Mr(c.port),(0,Ae.mkdirSync)(so.default.dirname(i),{recursive:!0})}(0,Ae.appendFileSync)(i,d)},a=Ea({clients:cs(o,void 0,void 0,s??void 0,is(H.default.env)),identity:r,...e?{requestLog:u}:{}});try{await new Promise((d,c)=>{a.once("error",c),a.listen(t,"127.0.0.1",d)})}catch(d){throw await o.closeAll().catch(()=>{}),s&&await s.close().catch(()=>{}),d.code==="EADDRINUSE"?new Error(fi(t,await Cr(t))):d}let l=a.address().port;return e&&(H.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${l}/v1
83
- `),Pa(l)),{port:l,close:async()=>{s&&await s.drain(5e3).catch(()=>{});let d=new Promise(c=>a.close(()=>c()));a.closeAllConnections(),await d,await o.closeAll(),s&&await s.close()}}}async function Rc(){let t=H.default.argv.slice(2),e=si(t),n=t.shift()??"proxy";if(n==="env")return Pa(ii(e??Or(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await Aa();return o?(H.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
84
- `),0):(H.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
85
- `),1)}if(n==="proxy"){let o=e??Or(t),s=await Oa(o,!0);return await new Promise(i=>{H.default.once("SIGINT",i),H.default.once("SIGTERM",i)}),await s.close(),0}let r=n==="run"?t.shift():n;{if(!r)throw new Error(`launch needs an agent (${Object.keys(xn).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let _=mt(H.default.env);return Ia("pi",["-e",Ta(),...ti(_.appId,t)],H.default.env)}if(r==="omp"){let _=mt(H.default.env);return Ia("omp",["-e",Ta(),...ni(_.appId,t)],H.default.env)}let o,s,i="openai";if(r==="--"){if(o=t.shift()??"",s=t,!o)throw new Error("`-- <cmd>` needs a command to launch")}else{let _=xn[r];if(!_)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(xn).join(" | ")} \u2014 or \`-- <cmd>\``);o=_.bin,s=[..._.args??[],...t],i=_.env}let u=await ui(e,Pr(mt(H.default.env))),a=null,l=u.port;u.mode==="reuse"?H.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${l} (app ${u.identity.app}, fn ${u.identity.fn}, v${u.identity.proxy_version})
86
- `):u.reason&&H.default.stderr.write(`urun compat: ${u.reason}
87
- `);let d=null,c=null,p=null,m=null;u.mode!=="reuse"&&(a=await Oa(u.port,!1),l=a.port,m=Mr(l),(0,Ae.mkdirSync)(so.default.dirname(m),{recursive:!0}),p=(0,Ae.createWriteStream)(m,{flags:"a"}),c=ci({streams:H.default,note:_=>(0,Ae.appendFileSync)(m,_)}).uninstall,p.on("error",_=>{d?.(),d=null,Re(H.default.stderr,`urun compat: proxy log ${m} failed: ${String(_)} \u2014 proxy output continues on the terminal
88
- `)}),H.default.stdout.write(`urun openai proxy on http://127.0.0.1:${l}/v1 \u2014 proxy logs: ${m}
89
- `),d=li(p)),r==="codex"&&(s=ei(l,mt(H.default.env).appId,s));let g=(0,oo.spawn)(o,s,{stdio:"inherit",env:Zs(H.default.env,l,i)}),v=m!==null?pi({logPath:m,appendSync:Ae.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:_=>H.default.stderr.write(_),killChild:()=>g.kill("SIGTERM"),exit:_=>H.default.exit(_),proc:H.default}):null,k=await new Promise(_=>{g.once("exit",f=>_(f??1)),g.once("error",f=>{d?.(),d=null,Re(H.default.stderr,`failed to launch ${o}: ${String(f)}
90
- `),_(127)})});v?.();let S=null;try{a&&await a.close()}catch(_){S=_}finally{d?.(),d=null,c?.(),c=null,p?.end()}return S!==null&&Re(H.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${k} preserved): ${String(S instanceof Error?S.message:S)}
91
- `),k}}Rc().then(t=>H.default.exit(t),t=>{H.default.stderr.write(`${String(t instanceof Error?t.message:t)}
92
- `),H.default.exit(1)});
79
+ `),null):{catalogUrl:r,anonKey:o}}function xc(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:kc(G.default.env,r=>G.default.stderr.write(r)),decisionPool:ss(G.default.env,G.default.env.HOSTNAME)??void 0},n=ls(e);return{router:n,decision:e.decisionPool?ds(e,n):null}}async function Ia(t,e,n){let r=(0,oo.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{G.default.stderr.write(`failed to launch ${t}: ${String(s)}
80
+ `),o(127)})})}function Ta(){return ri(G.default.env,L,Ae.existsSync)}function Pa(t){for(let[e,n]of Object.entries(Tr(t)))G.default.stdout.write(`export ${e}=${n}
81
+ `)}async function Oa(t,e){let n=mt(G.default.env),r=e?Pr(n):void 0,{router:o,decision:s}=xc(n);s&&(s.boot().then(()=>s.reap()).catch(c=>G.default.stderr.write(`[decision-pool] boot FAILED: ${String(c instanceof Error?c.message:c)}
82
+ `)),setInterval(()=>s.reap(),5e3).unref());let i=null,u=d=>{if(i===null){let c=a.address();if(c===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");i=Mr(c.port),(0,Ae.mkdirSync)(so.default.dirname(i),{recursive:!0})}(0,Ae.appendFileSync)(i,d)},a=Ea({clients:cs(o,void 0,void 0,s??void 0,is(G.default.env)),identity:r,...e?{requestLog:u}:{}});try{await new Promise((d,c)=>{a.once("error",c),a.listen(t,"127.0.0.1",d)})}catch(d){throw await o.closeAll().catch(()=>{}),s&&await s.close().catch(()=>{}),d.code==="EADDRINUSE"?new Error(fi(t,await Cr(t))):d}let l=a.address().port;return e&&(G.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${l}/v1
83
+ `),Pa(l)),{port:l,close:async()=>{s&&await s.drain(5e3).catch(()=>{});let d=new Promise(c=>a.close(()=>c()));a.closeAllConnections(),await d,await o.closeAll(),s&&await s.close()}}}async function Rc(){let t=G.default.argv.slice(2),e=si(t),n=t.shift()??"proxy";if(n==="env")return Pa(ii(e??Or(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await Aa();return o?(G.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
84
+ `),0):(G.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
85
+ `),1)}if(n==="proxy"){let o=e??Or(t),s=await Oa(o,!0);return await new Promise(i=>{G.default.once("SIGINT",i),G.default.once("SIGTERM",i)}),await s.close(),0}let r=n==="run"?t.shift():n;{if(!r)throw new Error(`launch needs an agent (${Object.keys(xn).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let b=mt(G.default.env);return Ia("pi",["-e",Ta(),...ti(b.appId,t)],G.default.env)}if(r==="omp"){let b=mt(G.default.env);return Ia("omp",["-e",Ta(),...ni(b.appId,t)],G.default.env)}let o,s,i="openai";if(r==="--"){if(o=t.shift()??"",s=t,!o)throw new Error("`-- <cmd>` needs a command to launch")}else{let b=xn[r];if(!b)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(xn).join(" | ")} \u2014 or \`-- <cmd>\``);o=b.bin,s=[...b.args??[],...t],i=b.env}let u=await ui(e,Pr(mt(G.default.env))),a=null,l=u.port;u.mode==="reuse"?G.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${l} (app ${u.identity.app}, fn ${u.identity.fn}, v${u.identity.proxy_version})
86
+ `):u.reason&&G.default.stderr.write(`urun compat: ${u.reason}
87
+ `);let d=null,c=null,p=null,m=null;u.mode!=="reuse"&&(a=await Oa(u.port,!1),l=a.port,m=Mr(l),(0,Ae.mkdirSync)(so.default.dirname(m),{recursive:!0}),p=(0,Ae.createWriteStream)(m,{flags:"a"}),c=ci({streams:G.default,note:b=>(0,Ae.appendFileSync)(m,b)}).uninstall,p.on("error",b=>{d?.(),d=null,Re(G.default.stderr,`urun compat: proxy log ${m} failed: ${String(b)} \u2014 proxy output continues on the terminal
88
+ `)}),G.default.stdout.write(`urun openai proxy on http://127.0.0.1:${l}/v1 \u2014 proxy logs: ${m}
89
+ `),d=li(p)),r==="codex"&&(s=ei(l,mt(G.default.env).appId,s));let g=(0,oo.spawn)(o,s,{stdio:"inherit",env:Zs(G.default.env,l,i)}),S=m!==null?pi({logPath:m,appendSync:Ae.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:b=>G.default.stderr.write(b),killChild:()=>g.kill("SIGTERM"),exit:b=>G.default.exit(b),proc:G.default}):null,x=await new Promise(b=>{g.once("exit",v=>b(v??1)),g.once("error",v=>{d?.(),d=null,Re(G.default.stderr,`failed to launch ${o}: ${String(v)}
90
+ `),b(127)})});S?.();let k=null;try{a&&await a.close()}catch(b){k=b}finally{d?.(),d=null,c?.(),c=null,p?.end()}return k!==null&&Re(G.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${x} preserved): ${String(k instanceof Error?k.message:k)}
91
+ `),x}}Rc().then(t=>G.default.exit(t),t=>{G.default.stderr.write(`${String(t instanceof Error?t.message:t)}
92
+ `),G.default.exit(1)});