@urun-sh/openai 0.6.52 → 0.6.54

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,41 +1,41 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ma=Object.create;var lo=Object.defineProperty;var $a=Object.getOwnPropertyDescriptor;var La=Object.getOwnPropertyNames;var Na=Object.getPrototypeOf,Ua=Object.prototype.hasOwnProperty;var Da=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of La(e))!Ua.call(t,o)&&o!==n&&lo(t,o,{get:()=>e[o],enumerable:!(r=$a(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Ma(Na(t)):{},Da(e||!t||!t.__esModule?lo(n,"default",{value:t,enumerable:!0}):n,t));var Fa=()=>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=Fa();var so=require("child_process"),Ae=require("fs"),io=ot(require("path"),1),H=ot(require("process"),1);var oe=require("@urun-sh/core");var Te=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 tn=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 co(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 ho=require("@urun-sh/core/internal");function po(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 fo(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 mo=require("@urun-sh/core/internal");var Ba="llm-resp";async function*go(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 fo(s);return}}}async function*Kn(t,e){let n=`${Ba}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*go(e,t.stream(n).messages())}finally{try{(0,mo.gcRequest)(t.doc("llm"),e)}catch{}}}var nn=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=po(e,n,r,this.consumerId);return this.write(o),Kn(this.session,r)})}cancelTurn(e){try{(0,ho.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await co(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 yo=0;function ja(){return yo+=1,`req_${Date.now().toString(36)}_${yo.toString(36)}`}var xt=class{transport;constructor(e,n){this.transport=new nn(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=ja(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var _o="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 vo(t,e,n=1e4){try{return await Ha(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Ha(t,e,n){let r=new zn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(_o);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Ga(t,n);return await r.startInbound(i),r}function Ga(t,e){let n=t.stream(_o);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 wo="rt-video-in",Et=256e3;function Xn(t){let e=t.stream(wo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${wo}') 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>Et)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Et}-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 Ja=24e3,Rt=480,Va=111,Wa=50,rn=null;async function Ka(){if(rn)return;let t=await import("opusscript");rn=t.default??t}function za(){if(!rn)throw new Error("[opus-guard] opusscript module not loaded");return new rn(Ja,1,2048)}var Yn=class{constructor(e=za){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>=Wa}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 on(){let t=await import("werift");await Ka();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>=Rt;){let d=a.subarray(l,l+Rt);l+=Rt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,Rt);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+Rt>>>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 bo(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 sn=require("@urun-sh/core"),Qn="rt-video-out";var Ya="h264";function Xa(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 Qa(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;Xa(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 So="urun.videoOut.v2-ws";function ko(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=Qa(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:Ya,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 xo={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 Ro(t){let e=t.t;if(typeof e!="string"||!(e in xo))throw new st(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(xo).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 Za(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 Ro(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 Ro(t)}function Eo(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function eu(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 Ao(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 Eo(e);let s=o.next();if(e!==void 0&&await eu(s,e)==="aborted")throw s.catch(()=>{}),Eo(e);let i=await s;if(i.done)return;yield Za(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Io=require("@urun-sh/core"),Zn=2;function tu(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function nu(t){let e=t?.type;return e==="response.completed"||e==="error"}function To(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(nu(m)&&(d=!0),tu(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Io.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",Po="model_id,variant,unit,price_usd,effective_at,expires_at",Oo={per_request:!0,per_minute:!0,per_output_unit:!0},ru=5e3;function ou(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 Co(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 su(t,e,n){return t===null?null:Co(t,e,n)}function iu(t,e){if(t===er)return"input";if(t===tr)return"output";if(typeof t=="string"&&Object.hasOwn(Oo,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(Oo).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 au(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 uu(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 Po.split(","))if(!Object.hasOwn(s,l))throw new ge(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=iu(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:ou(s.price_usd,o),effective_at:Co(s.effective_at,o,"effective_at"),expires_at:su(s.expires_at,o,"expires_at")})}return e}function Mo(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 R=au(S,m);return"reason"in R?R:R.rate.usd===0?m==="output"&&g!==null&&n?.has(nr(a,g))?R.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`}:R.rate};for(let[p,m]of o.get(a)){let g=l.get(p),S=c(g?.input,"input",m),R=c(g?.output,"output",m);if(S!==null&&"reason"in S){i.push({model_id:a,variant:m,reason:S.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:a,variant:m,reason:R.reason});continue}S===null||R===null||s.push({model_id:a,variant:m,pricing:{input:S.usd,output:R.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 At(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 It={prices:[],refusals:[]};async function $o(t){let e=t.fetchImpl??fetch,n=`${er},${tr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Po}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(ru)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return uu(await r.json())}var Ko=require("crypto");var Z=class extends Error{},lu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function du(t){if(typeof t!="string")return!1;let e=lu.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 cu(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new Z(`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 Z(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new Z(`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 Z(`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 Z(`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 Z(`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 Z(`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",du(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new Z(`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 Z(`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 Z(`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 Z(`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 Lo(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 Z(`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 Z(`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 No(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 Z(`catalog read failed: GET ${n} \u2192 ${r.status}`);return cu(await r.json())}function pe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Ot="/partners/openrouter/models",pu={chat:!0,code:!0,agent:!0,vl:!0},Uo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function fu(t){let e=t.toLowerCase();return Object.hasOwn(Uo,e)?Uo[e]:null}var Do={"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 mu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Do,o)?Do[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 Fo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Bo={2:"Llama2",3:"Llama3"};function gu(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(Fo,s))return Fo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Bo,i))return Bo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var hu=["context_length","max_model_len"];function yu(t){let e=hu.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 an(t){let e=t.map(yu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function wu(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(wu),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 _u(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Tt(n);let r=e.filter(s=>pe(s.model_id)===t);if(r.length>0)return Tt(r);let o=sr(t,e);return o.length>0?Tt(o):null}function Tt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:vu(t),matches:t}:null}function vu(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 Ne=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 Ne(`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 Ne(`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 Ne(`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 Ne(`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 un(t,e,n){let r=_u(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=an(s),u=at(s),a=At(o.model_id,o.variant,n),l=Ho(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 bu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Ho(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:[...bu],defect:o}:{published:[],defect:o}}function ir(t){let e=t.length>0?Tt(t):null;return e===null?{published:[],defect:null}:Ho(e.row,e.matches)}function qo(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 jo(t){return{input:[{type:"prompt",unit:"token",cost_usd:qo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:qo(t.output)}]}}function Su(t,e,n,r){if(e.length===0)return null;let o=Tt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||pu[s.task]!==!0)return null;let u=an(i),a=At(s.model_id,s.variant,n),l=gu(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:fu(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:jo(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:jo(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Go(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:mu(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=Su(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var zo="https://api.urun.sh/v1",J=class extends Error{},V=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 Mt(t,e){return ur+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Je(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 Yo(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 Jo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Eu(t);return e===null?[]:[e]}function ku(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 Na=Object.create;var po=Object.defineProperty;var Ua=Object.getOwnPropertyDescriptor;var Da=Object.getOwnPropertyNames;var Fa=Object.getPrototypeOf,Ba=Object.prototype.hasOwnProperty;var qa=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Da(e))!Ba.call(t,o)&&o!==n&&po(t,o,{get:()=>e[o],enumerable:!(r=Ua(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Na(Fa(t)):{},qa(e||!t||!t.__esModule?po(n,"default",{value:t,enumerable:!0}):n,t));var ja=()=>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=ja();var ao=require("child_process"),Ae=require("fs"),uo=ot(require("path"),1),H=ot(require("process"),1);var se=require("@urun-sh/core");var Te=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},pe=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var rn=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 fo(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 wo=require("@urun-sh/core/internal");function mo(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 Kn(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 go(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 ho=require("@urun-sh/core/internal");var Ha="llm-resp";async function*yo(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 go(s);return}}}async function*zn(t,e){let n=`${Ha}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*yo(e,t.stream(n).messages())}finally{try{(0,ho.gcRequest)(t.doc("llm"),e)}catch{}}}var on=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=Kn(e,n,this.consumerId);return this.write(r),zn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=mo(e,n,r,this.consumerId);return this.write(o),zn(this.session,r)})}cancelTurn(e){try{(0,wo.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await fo(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 _o=0;function Ja(){return _o+=1,`req_${Date.now().toString(36)}_${_o.toString(36)}`}var Rt=class{transport;constructor(e,n){this.transport=new on(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Ja(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var bo="audio",Yn=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 So(t,e,n=1e4){try{return await Va(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Va(t,e,n){let r=new Yn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(bo);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Wa(t,n);return await r.startInbound(i),r}function Wa(t,e){let n=t.stream(bo);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 vo="rt-video-in",At=256e3;function Qn(t){let e=t.stream(vo),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${vo}') 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>At)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${At}-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 Ka=24e3,Et=480,za=111,Ya=50,sn=null;async function Xa(){if(sn)return;let t=await import("opusscript");sn=t.default??t}function Qa(){if(!sn)throw new Error("[opus-guard] opusscript module not loaded");return new sn(Ka,1,2048)}var Xn=class{constructor(e=Qa){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>=Ya}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 an(){let t=await import("werift");await Xa();let e=new Xn;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>=Et;){let d=a.subarray(l,l+Et);l+=Et;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,Et);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+Et>>>0;let m=new t.RtpHeader({version:2,payloadType:za,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 ko(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 un=require("@urun-sh/core"),Zn="rt-video-out";var Za="h264";function eu(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 tu(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;eu(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 xo="urun.videoOut.v2-ws";function Ro(t){let e=t.stream(Zn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Zn}') 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: "${Zn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=tu(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 Eo={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 Ao(t){let e=t.t;if(typeof e!="string"||!(e in Eo))throw new st(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Eo).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 nu(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 Ao(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 Ao(t)}function Io(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function ru(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 To(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 Io(e);let s=o.next();if(e!==void 0&&await ru(s,e)==="aborted")throw s.catch(()=>{}),Io(e);let i=await s;if(i.done)return;yield nu(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Oo=require("@urun-sh/core"),er=2;function ou(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function su(t){let e=t?.type;return e==="response.completed"||e==="error"}function Po(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=er;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(su(m)&&(d=!0),ou(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Oo.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<er&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<er&&!c){await t.evict(u,a);continue}return}})()}}var wr=require("crypto");var he=class extends Error{name="ModelPriceError"},tr="per_million_input_tokens",nr="per_million_output_tokens",Mo="model_id,variant,unit,price_usd,effective_at,expires_at",Co={per_request:!0,per_minute:!0,per_output_unit:!0},iu=5e3;function au(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new he(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function $o(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new he(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function uu(t,e,n){return t===null?null:$o(t,e,n)}function lu(t,e){if(t===tr)return"input";if(t===nr)return"output";if(typeof t=="string"&&Object.hasOwn(Co,t))return null;throw new he(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${tr} | ${nr}) nor a known GPU-time unit (${Object.keys(Co).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 du(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 rr(t,e){return`${t}\0${e}`}function cu(t){if(!Array.isArray(t))throw new he(`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 he(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Mo.split(","))if(!Object.hasOwn(s,l))throw new he(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=lu(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new he(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new he(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:au(s.price_usd,o),effective_at:$o(s.effective_at,o,"effective_at"),expires_at:uu(s.expires_at,o,"expires_at")})}return e}function Lo(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 R=du(S,m);return"reason"in R?R:R.rate.usd===0?m==="output"&&g!==null&&n?.has(rr(a,g))?R.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`}:R.rate};for(let[p,m]of o.get(a)){let g=l.get(p),S=c(g?.input,"input",m),R=c(g?.output,"output",m);if(S!==null&&"reason"in S){i.push({model_id:a,variant:m,reason:S.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:a,variant:m,reason:R.reason});continue}S===null||R===null||s.push({model_id:a,variant:m,pricing:{input:S.usd,output:R.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 It(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 Tt={prices:[],refusals:[]};async function No(t){let e=t.fetchImpl??fetch,n=`${tr},${nr}`,r=await e(`${t.catalogUrl}/model_prices?select=${Mo}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(iu)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return cu(await r.json())}var Yo=require("crypto");var ee=class extends Error{},pu=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function fu(t){if(typeof t!="string")return!1;let e=pu.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 mu(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",fu(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 Uo(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 or(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 Do(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 mu(await r.json())}function fe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Pt="/partners/openrouter/models",gu={chat:!0,code:!0,agent:!0,vl:!0},Fo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function hu(t){let e=t.toLowerCase();return Object.hasOwn(Fo,e)?Fo[e]:null}var Bo={"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 yu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Bo,o)?Bo[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 qo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},jo={2:"Llama2",3:"Llama3"};function wu(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(qo,s))return qo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(jo,i))return jo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var _u=["context_length","max_model_len"];function vu(t){let e=_u.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 ln(t){let e=t.map(vu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function bu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function sr(t){if(t.length===0)return null;let e=t.map(bu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ir(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 Su(t,e){let n=e.filter(s=>fe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Ot(n);let r=e.filter(s=>fe(s.model_id)===t);if(r.length>0)return Ot(r);let o=ir(t,e);return o.length>0?Ot(o):null}function Ot(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ku(t),matches:t}:null}function ku(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 Ne=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 Ne(`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 Ne(`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 Ne(`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 Ne(`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 dn(t,e,n){let r=Su(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=ln(s),u=at(s),a=It(o.model_id,o.variant,n),l=Jo(o,s),d=sr(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 xu=["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:[...xu],defect:o}:{published:[],defect:o}}function ar(t){let e=t.length>0?Ot(t):null;return e===null?{published:[],defect:null}:Jo(e.row,e.matches)}function Ho(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 Go(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ho(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ho(t.output)}]}}function Ru(t,e,n,r){if(e.length===0)return null;let o=Ot(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||gu[s.task]!==!0)return null;let u=ln(i),a=It(s.model_id,s.variant,n),l=wu(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:hu(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:Go(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:Go(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Vo(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:yu(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=Ru(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Xo="https://api.urun.sh/v1",J=class extends Error{},V=class extends Error{bindingLost;reason;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1,this.reason=n?.reason??null}},cr="credits_exhausted",pr="insufficient_credits",lr="urs1.";function $t(t,e){return lr+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Je(t){if(!t.startsWith(lr))return null;try{let e=JSON.parse(Buffer.from(t.slice(lr.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 Qo(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 Wo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Tu(t);return e===null?[]:[e]}function Eu(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
- `),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function xu(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?ku(n.engine_args?.pool):null}function ar(t,e,n,r,o){if(!o)throw new Z(`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 Z(`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 Z(`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 Z(`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 Xo="shared:",Wo="speech:",$t="realtime:";function De(t){return t.sharedApp?Xo+t.appSlug:t.appSlug}function Ct(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 Ru(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Eu(t){let e=t.map(Ru),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Au={stt:"stt",tts:"tts"};function Ue(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:Au[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Qo(t,e){let n=lr(t,e);return n.length>0?n:sr(t,e)}function Pt(t,e){return Qo(t.appSlug,e)}function Iu(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 Z(`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 ln=6e4,dn=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??ln):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??ln):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??ln):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??ln;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
- `),It}let r=Mo(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
- `);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(Xo)||o.startsWith(Wo)||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=Ct(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return xu(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return De(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,De(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return Ct(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Wo+De(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,$t+(0,Ko.randomUUID)())}async evictHandle(e){let n=Je(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:Ct(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:Mt(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Mt(n,this.keyOf(r))}}async sessionForHandle(e){let n=Je(e);if(!n)throw new V(`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 V(`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 V(`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:It;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(k=>k.model_id===l.model_id&&k.variant===l.variant),c=an(d),p=at(d),m=or(d),g=At(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=>un(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Go(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 Jo(lr(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ue(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ue(Pt(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ue(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ue(Pt(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ue(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ue(Pt(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):Pt(n,r);return Iu(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):Pt(n,r);return ir(o)}async imageModelList(){let e=await this.catalogRows(),n=It,r=[];for(let s of await this.availableIds()){let i=Jo(lr(s,e));i.length!==0&&r.push(Ge({...un(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=It,r=[];for(let s of await this.availableIds())Ue(Qo(s,e))==="stt"&&r.push(un(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(Ue(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 Fe=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)}},Lt=class extends Fe{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},pr=class extends Fe{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}},cn=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 Lt;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 Lt;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 Lt}}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)}},fn=33e4;function Zo(t,e=fn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new pn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof V||l instanceof fr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof pn?(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 pn=class extends Error{constructor(){super("stream idle timeout")}};function es(t){return t instanceof Se?!1:t instanceof V?!0:t instanceof fr.SessionFailedError?t.kind==="transport-failed":!1}var Tu=require("http");var mn=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"),Ou="audio";function ts(t){let e=t.streamEndpoint(Ou);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 ns=require("@urun-sh/core"),Pu="rt-video-in";function rs(t){let e=t.streamEndpoint(Pu);return{sendInputFrame:async n=>{e.send((0,ns.encodeStreamEnvelope)(n))}}}var Cu=3,Mu="llm",$u=new Set(["paused","error"]);function os(t,e,n){let r=t.doc(Mu),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<Cu||d(new V(`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&&$u.has(c.name)&&d(new V(`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 Nu=0,Uu=4,Du=4;function is(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):Nu;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,Uu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Du),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function as(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return fn;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 us(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 xt(S),gone:os(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:R}=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:R,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 ls(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 Fu=new Set(["error","paused"]);function ds(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=us(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 dn({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"?()=>Yo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>bo(n):null),listPrices:n?()=>$o(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return Lo(i)}:e.lane==="api-key"?()=>No({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:ls});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},De({appSlug:t.defaultApp}))),s}function cs(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 cn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,onLease:g=>g.session.activity?.(),openSlot:async g=>{let S=us(t,d,c,{concurrencyKey:g.concurrencyKey});return S.gone.onGone(R=>R.bindingLost?m.evict(S):m.markSessionDead(S)),await hn(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,De(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=De(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:Ct(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,De(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 Bu(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 hn(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:Bu(t.phase),signal:e})}async function qu(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 ss(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 gn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ps(t,e=on,n,r,o=fn,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=Je(f);if(!s||!y||y.app!==m)return null;let h=s.entryFor(y.key);if(!h)throw new V(`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,R=f=>{let y=i.get(f);if(!y){let h={waiting:0,gone:new AbortController};c.set(f,h),y=(async()=>{if(await hn(f.session,h.gone.signal),h.gone.signal.aborted)throw gn(h.gone.signal);c.get(f)===h&&c.delete(f);let v=await vo(f.session,await e());return Object.assign(v,{sessionId:f.session.id})})(),i.set(f,y),y.then(v=>{i.get(f)===y&&(f.audioDispose=()=>v.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 R(f);return{appendInputAudio:(v,E)=>h.appendInputAudio(v,E),onOutputAudio:v=>h.onOutputAudio(v),sessionId:p(f)}})(),l.set(f,y),y.catch(()=>{l.get(f)===y&&l.delete(f)})),y},b=async(f,y,h,v=!1)=>{let E=()=>v?ss(f.session):qu(f.session);if(h?.aborted){let x=c.get(f);throw(i.get(f)===void 0||x!==void 0&&x.waiting===0)&&await E().catch(()=>{}),gn(h)}let A=y(f),w=c.get(f);return w!==void 0&&w.waiting++,h===void 0?A:new Promise((x,I)=>{let $=()=>{w!==void 0&&--w.waiting===0&&c.get(f)===w&&(w.gone.abort(),c.delete(f),i.delete(f),l.delete(f),E().catch(()=>{})),I(gn(h))};h.addEventListener("abort",$,{once:!0});let F=()=>h.removeEventListener("abort",$);A.then(j=>{F(),x(j)},j=>{F(),I(j)})})},_=async(f,y,h)=>{try{return await h}catch(v){throw(v instanceof V||v instanceof oe.SessionFailedError&&wr(v))&&(t.evict(f,y),v instanceof oe.SessionFailedError&&n?.(f,v.kind==="never-live"?"never-live":"create-failed")),v}};return{createResponse:To({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 tn)return r?r.sessionFor(f):t.sessionFor(f);if(h instanceof mn)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 hn(f.session);let h=Zo(gr(await f.responses.responses.create(y),f.gone),o);if(!r&&!s)return h;let v=f;return(async function*(){try{yield*h}catch(A){throw es(A)&&(s&&s.owns(v)?s.evict(v):r&&(A instanceof V&&!A.bindingLost?r.markSessionDead(v):r.evict(v))),A}finally{s&&s.owns(v)?s.release(v):r?.end(v)}})()}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:v}=await t.sessionFor(f);return await _(h,v,b(v,R,y))},openAudioOn:async(f,y,h,v)=>{let E=g(f);if(E){let I=E.entry.session;return ts(I)}let{app:A,entry:w}=await t.sessionForHandle(f);if(v&&w.session.phase?.name!=="live"){let I=w.session.phase?.name;v({status:I==="queued"||I==="waiting_for_capacity"?I:"pending",reason:`the dial's session is ${I??"not yet admitted"} \u2014 the connection waits for admission`})}let x=Je(f)?.app.startsWith($t)??!1;return await _(A,w,b(w,k,y,x))},openTurnsOn:async function*(f,y){if(y?.aborted)throw gn(y);let h=await S(f);yield*Ao(h.session,y)},openVideoOn:async f=>{let y=g(f);if(y)return rs(y.entry.session);let{entry:h}=await t.sessionForHandle(f),v=u.get(h);return v||(v=Xn(h.session),u.set(h,v)),v},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=ko(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),v=p(h.entry);if(v===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Mt(m,v)}}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:v}=await t.dedicatedSessionFor(f);return Mt(h,ls(v))},touchSessionPresence:(f,y)=>{(async()=>{let h=d.get(f);h||(h=new Map,d.set(f,h)),h.set(y,Date.now());let v=null;try{v=await S(f)}catch{return}v.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 v=null;try{v=await S(f)}catch{return}v.session.presenceDetach?.()})()},releaseSessionHandle:f=>{let y=Je(f);if(!y)return;if(y.app.startsWith($t)){(async()=>{let v=null;try{v=(await t.sessionForHandle(f)).entry}catch{return}await ss(v.session).catch(()=>{}),await t.evict(y.app,v)})();return}if(!s||y.app!==m)return;let h=s.entryFor(y.key);h&&s.release(h)},endDedicatedSession:async f=>{let y=Je(f);if(!y||!y.app.startsWith($t))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 v=await h.session.end();return await t.evict(y.app,h),v},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 v=await S(f);await hn(v.session);let E=h!==void 0&&g(f)?new xt({...v.session,consumerId:h},{sessionTag:h}):v.responses;return gr(await E.responses.create(y),v.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:v}=await t.sessionForHandle(f),E=v.session;if(typeof E.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let A=!1;return E.onPhase(w=>{if(A||!Fu.has(w.name))return;A=!0;let x=E.endsAt??null;y({timeLeftMs:x?Math.max(0,x.getTime()-Date.now()):null,reason:w.reason??`session ${w.name}`})})}}}var Sa=require("http");var Ps=require("crypto"),Cs=require("ws");var ms="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",ju=1007,gs=1008,Me=1011,vn=1008,T=class extends Error{constructor(n,r=ju){super(n);this.closeCode=r}closeCode},re=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,yn=["setup","clientContent","realtimeInput","toolResponse"];function hs(t){let e;try{e=JSON.parse(t)}catch{throw new T("client message is not valid JSON")}let n=re(e);if(!n)throw new T("client message must be a JSON object");let r=yn.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!yn.includes(u));if(o.length>0)throw new T(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${yn.join(", ")}`);if(r.length!==1)throw new T(`client message must contain exactly one of ${yn.join(", ")} (got ${r.length})`);let s=r[0],i=re(n[s]);if(!i)throw new T(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ys(t,e){if(typeof t=="string")return t;let n=re(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new T(`${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 T(`${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 T(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new T(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
9
- `)}var Hu={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},We="urun.videoOut";function ws(t){return{framing:So,codec:t}}function _s(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 Gu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ju=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",We],fs=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Vu(t){let e=re(t);if(!e)throw new T("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new T(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 T("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new T(`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 T("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(!fs.includes(e.activityHandling))throw new T(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${fs.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Wu=["temperature","maxOutputTokens","responseModalities"];function vs(t){for(let[c,p]of Object.entries(Gu))if(t[c]!==void 0)throw new T(p);for(let c of Object.keys(t))if(!Ju.includes(c))throw new T(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new T('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 T("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Wu.includes(c))throw new T(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new T("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new T("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 T(`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:ys(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new T("setup.tools must be an array");u=[];for(let c of t.tools){let p=re(c);if(!p)throw new T("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new T(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new T("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let g=re(m);if(!g||typeof g.name!="string")throw new T("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 T("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new T(`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 T("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?Hu:Vu(t.realtimeInputConfig),d=!1;if(t[We]!==void 0){if(!re(t[We]))throw new T(`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 bs(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ss(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ks(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new T(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new T("clientContent.turns must be an array");let n=[];for(let r of e){let o=re(r);if(!o)throw new T("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 T(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:ys(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var wn=16e3,xs=24e3,Ku=`audio/pcm;rate=${xs}`,Rs=Buffer.alloc(960).toString("base64");function zu(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 Yu(t){let e=re(t);if(!e)throw new T("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new T(`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 T("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 T("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Xu(t){let e=re(t);if(!e)throw new T("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new T(`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])!==wn)throw new T(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${wn} Hz (audio/pcm;rate=${wn})`);if(typeof e.data!="string"||e.data.length===0)throw new T("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 T(`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=zu(o,wn,xs);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Es(t){if(t.mediaChunks!==void 0)throw new T('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 T("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 T(`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 T(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new T(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Xu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Yu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new T("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new T("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function As(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new T(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new T("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 T("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 Is(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ts(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Ku,data:t}}]}}}}function Os(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 T(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Me);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new T(`upstream function_call arguments are not valid JSON: ${c}`,Me)}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 Qu=256,_r=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Qu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Zu="local",Nt=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(gs,Nt(e.message));return}if(e instanceof V){this.ws.close(vn,Nt(e.message));return}if(e instanceof T){this.ws.close(e.closeCode,Nt(e.message));return}this.ws.close(Me,Nt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=hs(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 T(`"${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}=ks(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Es(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:Rs);return}this.transcript.push(...As(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new T("setup may only be sent once, as the first client message");let n=vs(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new T("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",vn);if(s.model!==n.model)throw new T(`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 T("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 T(`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`,vn);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(_s(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[We]=ws(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 T("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new T("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Me);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ts(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 T("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new T("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Me);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 T(`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 T("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 T("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,Ps.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(bs(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(Ss(e.timeLeftMs)),this.ws.close(Me,Nt(`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 T(`upstream error: ${JSON.stringify(l)}`,Me);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=Is(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new T("upstream produced no response.completed event",Me);let{messages:i,assistantItems:u}=Os(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 el(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 Ms(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 Cs.WebSocketServer({noServer:!0}),o=new _r;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===ms&&(u.on("error",()=>{}),(async()=>{let d=el(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:Zu}}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
4
+ `),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function Au(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||fe(`${r.model_id}-${r.variant}`)===e.appSlug||fe(r.model_id)===e.appSlug)),n?Eu(n.engine_args?.pool):null}function ur(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 Ko(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 Zo="shared:",zo="speech:",Lt="realtime:";function De(t){return t.sharedApp?Zo+t.appSlug:t.appSlug}function Mt(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 dr(t,e){let n=e.filter(s=>fe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>fe(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Iu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Tu(t){let e=t.map(Iu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Ou={stt:"stt",tts:"tts"};function Ue(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:Ou[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function es(t,e){let n=dr(t,e);return n.length>0?n:ir(t,e)}function Ct(t,e){return es(t.appSlug,e)}function Pu(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 cn=6e4,pn=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??cn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??cn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??cn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??cn;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 he)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
+ `),Tt}let r=Lo(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
+ `);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(rr(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(Zo)||o.startsWith(zo)||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=or(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=fe(s),a=n.endpoints.filter(c=>fe(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:or(n,d,i)}async resolveTarget(e){let n=await this.dialTargetFor(e);return this.opts.callerOrgId&&(n.callerOrgId=this.opts.callerOrgId),n}async dialTargetFor(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=fe(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===fe(a.model_id)||o===fe(`${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=Mt(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return Au(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return De(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,De(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return Mt(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,zo+De(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Lt+(0,Yo.randomUUID)())}async evictHandle(e){let n=Je(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:Mt(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:$t(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:$t(n,this.keyOf(r))}}async sessionForHandle(e){let n=Je(e);if(!n)throw new V(`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 V(`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 V(`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:Tt;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(k=>k.model_id===l.model_id&&k.variant===l.variant),c=ln(d),p=at(d),m=sr(d),g=It(l.model_id,l.variant,i),S=ar(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=>dn(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Vo(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=ur(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ko(`${r.modelId}:${r.variant}`,s).includes(n)}return Wo(dr(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ue(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ue(Ct(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ue(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ue(Ct(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ue(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ue(Ct(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):Ct(n,r);return Pu(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):Ct(n,r);return ar(o)}async imageModelList(){let e=await this.catalogRows(),n=Tt,r=[];for(let s of await this.availableIds()){let i=Wo(dr(s,e));i.length!==0&&r.push(Ge({...dn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ur(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Ko(`${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=Tt,r=[];for(let s of await this.availableIds())Ue(es(s,e))==="stt"&&r.push(dn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of it(o)){let i=ur(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Ue(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 Fe=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)}},Nt=class extends Fe{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},fr=class extends Fe{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}},fn=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 Nt;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 Nt;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 fr(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 Nt}}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 mr=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)}},gn=33e4;function ts(t,e=gn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new mn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof V||l instanceof mr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof mn?(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 mn=class extends Error{constructor(){super("stream idle timeout")}};function ns(t){return t instanceof Se?!1:t instanceof V?!0:t instanceof mr.SessionFailedError?t.kind==="transport-failed":!1}var Cu=require("http");var hn=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 gr=require("@urun-sh/core"),Mu="audio";function rs(t){let e=t.streamEndpoint(Mu);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,gr.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,gr.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var os=require("@urun-sh/core"),$u="rt-video-in";function ss(t){let e=t.streamEndpoint($u);return{sendInputFrame:async n=>{e.send((0,os.encodeStreamEnvelope)(n))}}}var Lu=3,Nu="llm",Uu=new Set(["paused","error"]);function is(t,e,n){let r=t.doc(Nu),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<Lu||d(new V(`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&&Uu.has(c.name)&&d(new V(`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*hr(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 Fu=0,Bu=4,qu=4;function us(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):Fu;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,Bu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",qu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function ls(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return gn;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 yr(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 ds(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 Rt(S),gone:is(S,n)});if(i.lane==="jwt"){let S=(0,se.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(yr(S,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let S=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:R}=i,k=(typeof t.subject=="function"?t.subject():t.subject)??(0,wr.randomUUID)(),b=(0,se.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,se.createClientToken)(S,{baseUrl:R,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:k,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(yr(b,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,wr.randomUUID)(),g=(0,se.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,se.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(yr(g,e.appSlug,u,l))}function cs(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 _r(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 ju=new Set(["error","paused"]);function ps(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=ds(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 pn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,callerOrgId:t.orgId,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"?()=>Qo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>ko(n):null),listPrices:n?()=>No(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return Uo(i)}:e.lane==="api-key"?()=>Do({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:cs});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},De({appSlug:t.defaultApp}))),s}function fs(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 fn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,onLease:g=>g.session.activity?.(),openSlot:async g=>{let S=ds(t,d,c,{concurrencyKey:g.concurrencyKey});return S.gone.onGone(R=>R.bindingLost?m.evict(S):m.markSessionDead(S)),await wn(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 se.SessionFailedError&&_r(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,De(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=De(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:Mt(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,De(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 Hu(t){return(0,se.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?se.DEFAULT_WHEN_LIVE_TIMEOUT_MS:se.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:se.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function wn(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:Hu(t.phase),signal:e})}async function Gu(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 as(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 yn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ms(t,e=an,n,r,o=gn,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=Je(f);if(!s||!y||y.app!==m)return null;let h=s.entryFor(y.key);if(!h)throw new V(`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,R=f=>{let y=i.get(f);if(!y){let h={waiting:0,gone:new AbortController};c.set(f,h),y=(async()=>{if(await wn(f.session,h.gone.signal),h.gone.signal.aborted)throw yn(h.gone.signal);c.get(f)===h&&c.delete(f);let v=await So(f.session,await e());return Object.assign(v,{sessionId:f.session.id})})(),i.set(f,y),y.then(v=>{i.get(f)===y&&(f.audioDispose=()=>v.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 R(f);return{appendInputAudio:(v,E)=>h.appendInputAudio(v,E),onOutputAudio:v=>h.onOutputAudio(v),sessionId:p(f)}})(),l.set(f,y),y.catch(()=>{l.get(f)===y&&l.delete(f)})),y},b=async(f,y,h,v=!1)=>{let E=()=>v?as(f.session):Gu(f.session);if(h?.aborted){let x=c.get(f);throw(i.get(f)===void 0||x!==void 0&&x.waiting===0)&&await E().catch(()=>{}),yn(h)}let A=y(f),w=c.get(f);return w!==void 0&&w.waiting++,h===void 0?A:new Promise((x,I)=>{let $=()=>{w!==void 0&&--w.waiting===0&&c.get(f)===w&&(w.gone.abort(),c.delete(f),i.delete(f),l.delete(f),E().catch(()=>{})),I(yn(h))};h.addEventListener("abort",$,{once:!0});let F=()=>h.removeEventListener("abort",$);A.then(j=>{F(),x(j)},j=>{F(),I(j)})})},_=async(f,y,h)=>{try{return await h}catch(v){throw(v instanceof V||v instanceof se.SessionFailedError&&_r(v))&&(t.evict(f,y),v instanceof se.SessionFailedError&&n?.(f,v.kind==="never-live"?"never-live":"create-failed")),v}};return{createResponse:Po({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 rn)return r?r.sessionFor(f):t.sessionFor(f);if(h instanceof hn)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)=>{_r(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 wn(f.session);let h=ts(hr(await f.responses.responses.create(y),f.gone),o);if(!r&&!s)return h;let v=f;return(async function*(){try{yield*h}catch(A){throw ns(A)&&(s&&s.owns(v)?s.evict(v):r&&(A instanceof V&&!A.bindingLost?r.markSessionDead(v):r.evict(v))),A}finally{s&&s.owns(v)?s.release(v):r?.end(v)}})()}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:v}=await t.sessionFor(f);return await _(h,v,b(v,R,y))},openAudioOn:async(f,y,h,v)=>{let E=g(f);if(E){let I=E.entry.session;return rs(I)}let{app:A,entry:w}=await t.sessionForHandle(f);if(v&&w.session.phase?.name!=="live"){let I=w.session.phase?.name;v({status:I==="queued"||I==="waiting_for_capacity"?I:"pending",reason:`the dial's session is ${I??"not yet admitted"} \u2014 the connection waits for admission`})}let x=Je(f)?.app.startsWith(Lt)??!1;return await _(A,w,b(w,k,y,x))},openTurnsOn:async function*(f,y){if(y?.aborted)throw yn(y);let h=await S(f);yield*To(h.session,y)},openVideoOn:async f=>{let y=g(f);if(y)return ss(y.entry.session);let{entry:h}=await t.sessionForHandle(f),v=u.get(h);return v||(v=Qn(h.session),u.set(h,v)),v},openVideo:async f=>{let{entry:y}=await t.sessionFor(f),h=u.get(y);return h||(h=Qn(y.session),u.set(y,h)),h},openVideoOut:async f=>{let{entry:y}=await t.sessionFor(f),h=a.get(y);return h||(h=Ro(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),v=p(h.entry);if(v===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return $t(m,v)}}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:v}=await t.dedicatedSessionFor(f);return $t(h,cs(v))},touchSessionPresence:(f,y)=>{(async()=>{let h=d.get(f);h||(h=new Map,d.set(f,h)),h.set(y,Date.now());let v=null;try{v=await S(f)}catch{return}v.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 v=null;try{v=await S(f)}catch{return}v.session.presenceDetach?.()})()},releaseSessionHandle:f=>{let y=Je(f);if(!y)return;if(y.app.startsWith(Lt)){(async()=>{let v=null;try{v=(await t.sessionForHandle(f)).entry}catch{return}await as(v.session).catch(()=>{}),await t.evict(y.app,v)})();return}if(!s||y.app!==m)return;let h=s.entryFor(y.key);h&&s.release(h)},endDedicatedSession:async f=>{let y=Je(f);if(!y||!y.app.startsWith(Lt))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 v=await h.session.end();return await t.evict(y.app,h),v},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 v=await S(f);await wn(v.session);let E=h!==void 0&&g(f)?new Rt({...v.session,consumerId:h},{sessionTag:h}):v.responses;return hr(await E.responses.create(y),v.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:v}=await t.sessionForHandle(f),E=v.session;if(typeof E.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let A=!1;return E.onPhase(w=>{if(A||!ju.has(w.name))return;A=!0;let x=E.endsAt??null;y({timeLeftMs:x?Math.max(0,x.getTime()-Date.now()):null,reason:w.reason??`session ${w.name}`})})}}}var Ra=require("http");var Ms=require("crypto"),$s=require("ws");var hs="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Ju=1007,ys=1008,Me=1011,Sn=1008,T=class extends Error{constructor(n,r=Ju){super(n);this.closeCode=r}closeCode},re=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,_n=["setup","clientContent","realtimeInput","toolResponse"];function ws(t){let e;try{e=JSON.parse(t)}catch{throw new T("client message is not valid JSON")}let n=re(e);if(!n)throw new T("client message must be a JSON object");let r=_n.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!_n.includes(u));if(o.length>0)throw new T(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${_n.join(", ")}`);if(r.length!==1)throw new T(`client message must contain exactly one of ${_n.join(", ")} (got ${r.length})`);let s=r[0],i=re(n[s]);if(!i)throw new T(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function _s(t,e){if(typeof t=="string")return t;let n=re(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new T(`${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 T(`${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 T(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new T(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
9
+ `)}var Vu={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},We="urun.videoOut";function vs(t){return{framing:xo,codec:t}}function bs(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 Wu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ku=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",We],gs=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function zu(t){let e=re(t);if(!e)throw new T("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new T(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 T("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new T(`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 T("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(!gs.includes(e.activityHandling))throw new T(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${gs.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Yu=["temperature","maxOutputTokens","responseModalities"];function Ss(t){for(let[c,p]of Object.entries(Wu))if(t[c]!==void 0)throw new T(p);for(let c of Object.keys(t))if(!Ku.includes(c))throw new T(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new T('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 T("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Yu.includes(c))throw new T(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new T("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new T("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 T(`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:_s(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new T("setup.tools must be an array");u=[];for(let c of t.tools){let p=re(c);if(!p)throw new T("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new T(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new T("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let g=re(m);if(!g||typeof g.name!="string")throw new T("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 T("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new T(`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 T("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?Vu:zu(t.realtimeInputConfig),d=!1;if(t[We]!==void 0){if(!re(t[We]))throw new T(`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 ks(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function xs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Rs(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new T(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new T("clientContent.turns must be an array");let n=[];for(let r of e){let o=re(r);if(!o)throw new T("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 T(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:_s(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var vn=16e3,Es=24e3,Xu=`audio/pcm;rate=${Es}`,As=Buffer.alloc(960).toString("base64");function Qu(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 T("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new T(`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 T("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 T("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function el(t){let e=re(t);if(!e)throw new T("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new T(`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])!==vn)throw new T(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${vn} Hz (audio/pcm;rate=${vn})`);if(typeof e.data!="string"||e.data.length===0)throw new T("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 T(`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=Qu(o,vn,Es);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Is(t){if(t.mediaChunks!==void 0)throw new T('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 T("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 T(`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 T(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new T(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:el(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 T("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new T("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Ts(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new T(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new T("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 T("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 Os(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Ps(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Xu,data:t}}]}}}}function Cs(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 T(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Me);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new T(`upstream function_call arguments are not valid JSON: ${c}`,Me)}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 tl=256,vr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>tl;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},nl="local",Ut=t=>t.slice(0,120),br=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(ys,Ut(e.message));return}if(e instanceof V){this.ws.close(Sn,Ut(e.message));return}if(e instanceof T){this.ws.close(e.closeCode,Ut(e.message));return}this.ws.close(Me,Ut(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=ws(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 T(`"${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}=Rs(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Is(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:As);return}this.transcript.push(...Ts(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new T("setup may only be sent once, as the first client message");let n=Ss(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new T("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",Sn);if(s.model!==n.model)throw new T(`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 T("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 T(`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`,Sn);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(bs(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[We]=vs(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 T("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new T("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Me);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Ps(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 T("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new T("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Me);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 T(`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 T("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 T("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,Ms.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ks(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(xs(e.timeLeftMs)),this.ws.close(Me,Ut(`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 T(`upstream error: ${JSON.stringify(l)}`,Me);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=Os(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new T("upstream produced no response.completed event",Me);let{messages:i,assistantItems:u}=Cs(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 rl(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 Ls(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 $s.WebSocketServer({noServer:!0}),o=new vr;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===hs&&(u.on("error",()=>{}),(async()=>{let d=rl(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:nl}}r.handleUpgrade(i,u,a,p=>{new br(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
- `),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 qe=require("ws");var $s=require("crypto"),Ls="Inference-Id";function Ut(){return(0,$s.randomUUID)()}function br(t){return t==="/v1"||t.startsWith("/v1/")}function Ns(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 Dt(t){return`resp_${t}`}function Us(t){return`chatcmpl-${t}`}function Ds(t){return`msg_${t}`}function he(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Fs(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 Bs(t){return`${JSON.stringify(t)}
14
- `}var tl=256,nl=128;function ue(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,nl)}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>=tl?"(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}}}},rl=256;function ol(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=ol(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<=rl)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},qs=new WeakMap;function Ft(t){let e=qs.get(t);return e||(e=new ut,qs.set(t,e)),e}function lt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Oe(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 Be=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}))}},sl=["<tool_call>","<function="];function il(t){return sl.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 il(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 $e(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function al(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=al(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 js(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}:{},...js(e)!==void 0?{response_format:js(e)}:{}},o)}async function Bt(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:cl({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function ul(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?dl(o[i++],a):a),...ll(r,n)]}function ll(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 dl(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*cl(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*R(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let k=[],b=(M,U)=>{k.push({output_index:M,item:U})},_=!1,f=0,y="",h=0,v="";function*E(){if(!_)return;_=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:f,content_index:0,text:v};let M={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:f,item:M},b(f,M),v=""}let A=!1,w=0,x="",I=0,$="",F="";function*j(M){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:x,output_index:w,content_index:0,text:$},yield{type:"response.content_part.done",item_id:x,output_index:w,content_index:0,part:{type:"output_text",text:$}};let U={id:x,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:$}]};yield{type:"response.output_item.done",output_index:w,item:U},b(w,U),$=""}let N=new Be,B=null,W=-1;function*C(M){if(!B)return;let U=B;B=null,yield{type:"response.function_call_arguments.done",item_id:U.fcId,output_index:U.outputIndex,arguments:U.args};let z={id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:U.args,status:M};yield{type:"response.output_item.done",output_index:U.outputIndex,item:z},b(U.outputIndex,z)}let X=!1;for await(let M of l.track(e,o,t.turn)){d.push(M);let U=String(M.type??"");if(U==="response.created"||U==="response.in_progress"){m=!0,yield c(M);continue}if(U==="response.output_item.added"){g=!0,yield c(M);continue}if(U==="response.reasoning_text.delta"&&!g){yield*R(),_||(_=!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"}}),v+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:f,content_index:0,delta:M.delta};continue}if(U==="response.output_text.delta"&&!g){yield*R(),yield*E(),A||(A=!0,w=S++,I+=1,x=I===1?p:`${p}_${I}`,yield{type:"response.output_item.added",output_index:w,item:{id:x,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:x,output_index:w,content_index:0,part:{type:"output_text",text:""}}),$+=String(M.delta??""),F+=String(M.delta??""),yield{type:U,item_id:x,output_index:w,content_index:0,delta:M.delta};continue}let z=g?null:dt(M);if(z){if(yield*R(),yield*E(),yield*j("completed"),N.add(z),z.tool_index!==W){yield*C("completed"),W=z.tool_index;let Ie=S++;B={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:Ie,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:Ie,item:{id:B.fcId,type:"function_call",call_id:B.callId??B.fcId,name:B.name??"",arguments:"",status:"in_progress"}}}B&&(z.call_id&&(B.callId=z.call_id),z.name&&(B.name=z.name),B.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:B.fcId,output_index:B.outputIndex,delta:z.delta});continue}if(U==="response.completed"&&!g){let Ie=lt(M.response),rt=Qe(s,N.size+Ie.length,F);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*j("completed"),yield*C("completed"),N.size===0)for(let ne of Ie){let ve=S++,He=ne.id??ne.call_id??`fc_${ve}`,Vn=ne.arguments??"",ao={id:He,type:"function_call",call_id:ne.call_id??He,name:ne.name??""};yield{type:"response.output_item.added",output_index:ve,item:{...ao,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:He,output_index:ve,delta:Vn},yield{type:"response.function_call_arguments.done",item_id:He,output_index:ve,arguments:Vn};let uo={...ao,arguments:Vn,status:"completed"};yield{type:"response.output_item.done",output_index:ve,item:uo},b(ve,uo)}let Q=ul(k,M.response);yield Q.length>0?c({...M,response:{...M.response,output:Q}}):c(M);continue}yield c(M)}if(yield*E(),yield*j("incomplete"),yield*C("incomplete"),i&&!X){let M=Oe(d);a.remember(r,n,Sr(M,ct(d,M)),u)}}var pl=[/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!pl.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 V)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=Hs(t);return n||{message:xe(e?.inferenceId??null),redacted:!0}}function Hs(t){return t instanceof Ne?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Z?{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 Te?{message:t.message,redacted:!1}:t instanceof Fe?{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=Hs(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 Pe(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 fl="/v1/responses",ml=64*1024*1024,gl=8*1024*1024,hl=16,Gs=32,Js=3600*1e3,yl=/^[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 wl=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 _l(t){for(;t.bufferedAmount>gl&&t.readyState===qe.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(Ft(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 (${Js/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Js).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"||!yl.test(o.stream_id)){this.sendFrame(wl);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Gs){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 (${Gs}). 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=Ut();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Bt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Dt(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!==qe.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await _l(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=Ut(),o=Dt(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 V){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=Pe(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>=hl;){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!==qe.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!==qe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function bn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
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 qe=require("ws");var Ns=require("crypto"),Us="Inference-Id";function Dt(){return(0,Ns.randomUUID)()}function Sr(t){return t==="/v1"||t.startsWith("/v1/")}function Ds(t,e){if(!Sr(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 Ft(t){return`resp_${t}`}function Fs(t){return`chatcmpl-${t}`}function Bs(t){return`msg_${t}`}function ye(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function qs(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 js(t){return`${JSON.stringify(t)}
14
+ `}var ol=256,sl=128;function le(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,sl)}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>=ol?"(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}}}},il=256;function al(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=al(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<=il)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Hs=new WeakMap;function Bt(t){let e=Hs.get(t);return e||(e=new ut,Hs.set(t,e)),e}function lt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Oe(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 Be=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}))}},ul=["<tool_call>","<function="];function ll(t){return ul.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 ll(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 $e(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function dl(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 kr(t,e){let n=dl(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var we=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 we(n.message,"previous_response_not_found",400,"previous_response_id"):new we(String(n instanceof Error?n.message:n),"invalid_input")}}function Gs(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function xr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new we("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}:{},...Gs(e)!==void 0?{response_format:Gs(e)}:{}},o)}async function qt(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=le(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await xr(n,e,s,!0,c?ye(c):void 0);return{responseId:i,events:ml({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function cl(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?fl(o[i++],a):a),...pl(r,n)]}function pl(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 fl(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*ml(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*R(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let k=[],b=(M,U)=>{k.push({output_index:M,item:U})},_=!1,f=0,y="",h=0,v="";function*E(){if(!_)return;_=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:f,content_index:0,text:v};let M={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:f,item:M},b(f,M),v=""}let A=!1,w=0,x="",I=0,$="",F="";function*j(M){if(!A)return;A=!1,yield{type:"response.output_text.done",item_id:x,output_index:w,content_index:0,text:$},yield{type:"response.content_part.done",item_id:x,output_index:w,content_index:0,part:{type:"output_text",text:$}};let U={id:x,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:$}]};yield{type:"response.output_item.done",output_index:w,item:U},b(w,U),$=""}let N=new Be,B=null,W=-1;function*C(M){if(!B)return;let U=B;B=null,yield{type:"response.function_call_arguments.done",item_id:U.fcId,output_index:U.outputIndex,arguments:U.args};let z={id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:U.args,status:M};yield{type:"response.output_item.done",output_index:U.outputIndex,item:z},b(U.outputIndex,z)}let X=!1;for await(let M of l.track(e,o,t.turn)){d.push(M);let U=String(M.type??"");if(U==="response.created"||U==="response.in_progress"){m=!0,yield c(M);continue}if(U==="response.output_item.added"){g=!0,yield c(M);continue}if(U==="response.reasoning_text.delta"&&!g){yield*R(),_||(_=!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"}}),v+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:f,content_index:0,delta:M.delta};continue}if(U==="response.output_text.delta"&&!g){yield*R(),yield*E(),A||(A=!0,w=S++,I+=1,x=I===1?p:`${p}_${I}`,yield{type:"response.output_item.added",output_index:w,item:{id:x,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:x,output_index:w,content_index:0,part:{type:"output_text",text:""}}),$+=String(M.delta??""),F+=String(M.delta??""),yield{type:U,item_id:x,output_index:w,content_index:0,delta:M.delta};continue}let z=g?null:dt(M);if(z){if(yield*R(),yield*E(),yield*j("completed"),N.add(z),z.tool_index!==W){yield*C("completed"),W=z.tool_index;let Ie=S++;B={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:Ie,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:Ie,item:{id:B.fcId,type:"function_call",call_id:B.callId??B.fcId,name:B.name??"",arguments:"",status:"in_progress"}}}B&&(z.call_id&&(B.callId=z.call_id),z.name&&(B.name=z.name),B.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:B.fcId,output_index:B.outputIndex,delta:z.delta});continue}if(U==="response.completed"&&!g){let Ie=lt(M.response),rt=Qe(s,N.size+Ie.length,F);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*j("completed"),yield*C("completed"),N.size===0)for(let ne of Ie){let ve=S++,He=ne.id??ne.call_id??`fc_${ve}`,Wn=ne.arguments??"",lo={id:He,type:"function_call",call_id:ne.call_id??He,name:ne.name??""};yield{type:"response.output_item.added",output_index:ve,item:{...lo,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:He,output_index:ve,delta:Wn},yield{type:"response.function_call_arguments.done",item_id:He,output_index:ve,arguments:Wn};let co={...lo,arguments:Wn,status:"completed"};yield{type:"response.output_item.done",output_index:ve,item:co},b(ve,co)}let Q=cl(k,M.response);yield Q.length>0?c({...M,response:{...M.response,output:Q}}):c(M);continue}yield c(M)}if(yield*E(),yield*j("incomplete"),yield*C("incomplete"),i&&!X){let M=Oe(d);a.remember(r,n,kr(M,ct(d,M)),u)}}var gl=[/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!gl.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 me(t,e){if(t instanceof V)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 Ne?{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 Te?{message:t.message,redacted:!1}:t instanceof Fe?{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 pe?{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: ${_e(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: ${_e(e)}`),`the ${t} upstream failed while serving this request`)}function Pe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ke(e)?e:null}function _e(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var hl="/v1/responses",yl=64*1024*1024,wl=8*1024*1024,_l=16,Vs=32,Ws=3600*1e3,vl=/^[A-Za-z0-9._-]{1,256}$/;function de(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var bl=de(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 Ar(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Sl(t){for(;t.bufferedAmount>wl&&t.readyState===qe.WebSocket.OPEN;){let{promise:e,resolve:n}=Ar();setTimeout(n,5),await e}}var Rr=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)}},Er=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 Rr(Bt(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(de(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ws/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ws).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(de(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(de(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(de(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(de(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(de(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(de(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"||!vl.test(o.stream_id)){this.sendFrame(bl);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Vs){this.sendFrame(de(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Vs}). 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=Dt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await qt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ft(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!==qe.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await Sl(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=Dt(),o=Ft(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:_e(e);if(e instanceof we)return de(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 de(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof V){let u=me(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}`),de(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}`),de(s.status,{type:s.openaiType,message:o},n);let i=me(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}`),de(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Pe(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)}`),de(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=_l;){let{promise:e,resolve:n}=Ar();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!==qe.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!==qe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function kn(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 qe.WebSocketServer({noServer:!0,maxPayload:ml}),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{bn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==fl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){bn(c,401,"invalid local proxy api key");return}let S;try{S=await u(d)}catch(R){let k=e.statusOf?.(R)??null;bn(c,k?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,R=>{s.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new Rr(R,S,r,e.statusOf,e.operatorLog??(k=>console.error(k)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&bn(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!==qe.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Hr=require("@urun-sh/core");var Ws=require("@urun-sh/core"),vl={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},bl={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 qt(t,e){let n=bl[t.code];return e?`${n} (${e})`:n}function Sn(t){if(t==null)return null;let e=vl[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 kn(t){if(t.kind==="create-failed")return Sn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ws.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Sn(e?"cold_start_exceeded":"queue_timeout")}var zs=ot(require("os"),1),Ys=ot(require("path"),1),Xs=require("url"),Qs=require("util");var Ks="0.6.52";var Zs=4141,kl=Ks,Rn={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 ei(t,e,n){let r={...t,...Tr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function ti(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 ni(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ri(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function oi(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,Xs.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 si(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 ii(t){if(t[0]!=="--port")return null;let e=si(t[1]);return t.splice(0,2),e}function Or(t){let e=t.indexOf("--port");if(e===-1)return Zs;let n=si(t[e+1]);return t.splice(e,2),n}function ai(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=xl(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?xn(s,"URUN_API_URL"):zo,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?xn(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 xl(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 xn(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:kl}}function Rl(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 El=250;async function Cr(t,e=El){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 ui=2e3;async function Al(t,e=ui){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 li(t,e,n=Zs,r=ui){if(t!=null)return{mode:"spawn",port:t};let o=await Cr(n);if(o!==null&&Rl(o,e)){let s=await Al(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=zs.default.homedir()){return Ys.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Ir=["log","info","warn","error","debug","trace"];function di(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,Qs.format)(...a)}
21
- `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Ir)n[u]=i[u]}}var Il=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ci(t){let e=t?.code;return typeof e=="string"&&Il.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(ci(n))return!1;throw n}}function pi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{ci(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
- `)}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 fi(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}
20
+ ${o}`)}function Ks(t,e){let n=new qe.WebSocketServer({noServer:!0,maxPayload:yl}),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{kn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==hl){i.add(c);return}s.add(c);let g=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){kn(c,401,"invalid local proxy api key");return}let S;try{S=await u(d)}catch(R){let k=e.statusOf?.(R)??null;kn(c,k?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(g=!0,n.handleUpgrade(d,c,p,R=>{s.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new Er(R,S,r,e.statusOf,e.operatorLog??(k=>console.error(k)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!g&&!c.destroyed&&kn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=Ar();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!==qe.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Jr=require("@urun-sh/core");var zs=require("@urun-sh/core"),kl={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},xl={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 jt(t,e){let n=xl[t.code];return e?`${n} (${e})`:n}function xn(t){if(t==null)return null;let e=kl[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 Rn(t){if(t.kind==="create-failed")return xn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=zs.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return xn(e?"cold_start_exceeded":"queue_timeout")}var Xs=ot(require("os"),1),Qs=ot(require("path"),1),Zs=require("url"),ei=require("util");var Ys="0.6.54";var ti=4141,El=Ys,An={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 Or(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 ni(t,e,n){let r={...t,...Or(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function ri(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 oi(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function si(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function ii(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,Zs.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 ai(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 ui(t){if(t[0]!=="--port")return null;let e=ai(t[1]);return t.splice(0,2),e}function Pr(t){let e=t.indexOf("--port");if(e===-1)return ti;let n=ai(t[e+1]);return t.splice(e,2),n}function li(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 Ir(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=Al(Ir(t,"URUN_BASE_URL")),n=Ir(t,"URUN_ORG_ID"),r=Ir(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?En(s,"URUN_API_URL"):Xo,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?En(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 Al(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 En(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 Cr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:El}}function Il(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 Tl=250;async function Mr(t,e=Tl){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 di=2e3;async function Ol(t,e=di){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 ci(t,e,n=ti,r=di){if(t!=null)return{mode:"spawn",port:t};let o=await Mr(n);if(o!==null&&Il(o,e)){let s=await Ol(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 $r(t,e=Xs.default.homedir()){return Qs.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Tr=["log","info","warn","error","debug","trace"];function pi(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(Tr.map(u=>[u,n[u]]));for(let u of Tr)n[u]=(...a)=>{t.write(`${(0,ei.format)(...a)}
21
+ `)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Tr)n[u]=i[u]}}var Pl=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function fi(t){let e=t?.code;return typeof e=="string"&&Pl.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(fi(n))return!1;throw n}}function mi(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{fi(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
+ `)}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 gi(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 mi(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 Gt=require("ws");var wi=require("@urun-sh/core");var hi=require("crypto");function O(t){return`${t}_${(0,hi.randomUUID)().replace(/-/g,"").slice(0,24)}`}var En=4*1024*1024,$r=8*1024*1024,Lr=512,ht=20*1024*1024;function ee(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Ce(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},Tl={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},Ol={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Pl={format:!0,voice:!0,speed:!0};function Cl(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 gi(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 Ml=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:Ml})}function jt(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 Tl));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(!Cl(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 Ol))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&gi(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=jt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=jt({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 Pl))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&gi(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 $l=1001,Ll=1011,Nl=6e4,Ul=3e5,Fr=3;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"}},Br=t=>t.slice(0,120),Dl=/^[A-Za-z0-9+/=]*$/,Fl=2;function Bl(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Fl)return!1;return!0}var Ht=class{id=O("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Nr();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!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??Nl,this.responseDeadlineMs=e.responseDeadlineMs??Ul,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 V&&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(Ce("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(ee("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>En){this.fail(ee("frame_too_large",`frame exceeds the ${En}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ee("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ee("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(Ce(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(Ce(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=jt(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(ee("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(ee("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(ee("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(ee("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(ee("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Dl.test(e.audio)){this.send(K(ee("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}this.pendingAudioTotalBytes+r>ht&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${ht}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${ht} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>ht&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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(ee("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(ee("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(ee("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}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);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(ee("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,Br("session ended by client"))}catch{}});return}case"ping":return;default:this.send(K(ee("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(K(ee("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,n=!1){if(this.inFlight){this.send(K(ee("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?gt(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?gt(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.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((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.input!==void 0){this.send(K(ee("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,this.seamEndedTurn=null,this.clientCancel=!1;let u=()=>{},a=new Promise((E,A)=>{u=()=>A(new Ze)});this.turnCancelled=a,this.wakeTurnCancelled=()=>u(),a.catch(()=>{});let l=()=>{},d=new Promise((E,A)=>{l=()=>A(new Ze)});this.turnDialGate=d,this.wakeTurnDialGate=()=>l(),d.catch(()=>{});let c=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 p=O("req"),m=`resp_${p}`;this.activeResponseId=m,this.activeRequestId=p;let g=this.binding.composite===!0,S=g?0:this.items.length,R=g?null:In(this.items),k=Ur(typeof r.instructions=="string"?r.instructions:this.config.instructions),b=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,f=_==="inf"||_===void 0?void 0:_,y=r.tools!==void 0?r.tools:this.config.tools,h=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,v={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},...b!==void 0?{temperature:b}:{},...f!==void 0?{max_output_tokens:f}:{},...y!==void 0?{tools:y}:{},...h!==void 0?{tool_choice:h}:{}};if(!(g&&!this.ensureVoice())){for(let{audio:E,captureWallMs:A}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(E,A);this.inFlight=(async()=>{let E=[],A=F=>{this.responseFlushed?this.send(F):E.push(F)},w=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:O("event"),response:this.responseObject(m,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(m,"in_progress")});for(let F of E)this.send(F);E.length=0,this.responseFlushed=!0}},x={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},I=null,$=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(m,x,S),w(),this.send({type:"response.done",event_id:O("event"),response:this.responseObject(m,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(g){if(this.pendingTranscriptItemId!==null&&(await new Promise(W=>{this.pendingTranscriptSettled=W}),this.cancelled||this.closed))throw new Ze;S=this.items.length,R=In(this.items)}let{input:F,sawAudioOnlyItem:j}=R??{input:[],sawAudioOnlyItem:!1},N={...v,input:F,...g?this.compositeTurnAsk(r):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let B;try{let W=this.upstreamStream(N,p);Promise.resolve(W).catch(C=>{C instanceof V&&this.failSessionGone(C)}),B=await Promise.race([W,d])}catch(W){if(W instanceof Ze){this.deadlineFired&&!this.closed&&$();return}this.upstreamTurnFault(W,m);return}w();try{for await(let W of this.stallBoundedTurn(B)){if(this.cancelled)break;let C=W;if(C.type==="error"){let X=this.upstreamErrorBody(C);x.contentFlowed?this.send(K(X)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(m,X)});return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){w(),x.contentFlowed=!0,x.messageOpen||(this.beginMessageItem(m,x.nextOutputIndex++),x.messageOpen=!0),this.config.outputModalities.includes("text")&&A({type:"response.output_text.delta",event_id:O("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:C.delta}),this.turnOutputIsAudio()&&(x.transcriptDelta=!0,A({type:"response.output_audio_transcript.delta",event_id:O("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:C.delta})),x.messageText+=C.delta;continue}if(C.type==="response.function_call_arguments.delta"){w(),x.contentFlowed=!0;let X=typeof C.delta=="string"?C.delta:"",M=typeof C.call_id=="string"&&C.call_id.length>0?C.call_id:`${m}_fc_${x.nextOutputIndex}`,U=x.tools.get(M);if(!U){let z=typeof C.name=="string"&&C.name.length>0?C.name:void 0;U={outputIndex:x.nextOutputIndex++,name:z,args:""},x.tools.set(M,U);let Ie={id:M,object:"realtime.item",type:"function_call",call_id:M,name:z??"",arguments:"",status:"in_progress"};A({type:"response.output_item.added",event_id:O("event"),response_id:m,output_index:U.outputIndex,item:Ie}),this.emitAssistantItemAdded(Ie)}typeof C.name=="string"&&C.name.length>0&&(U.name=C.name),U.args+=X,A({type:"response.function_call_arguments.delta",event_id:O("event"),item_id:M,response_id:m,output_index:U.outputIndex,call_id:M,name:U.name??"",delta:X});continue}if(C.type==="response.completed"){I=C.response??null;continue}}}catch(W){if(this.closed)return;if(W instanceof Ze){this.deadlineFired&&$();return}if(this.cancelled)return;if(W instanceof On)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${m} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(W,m);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&$();return}this.closeOpenItems(m,x,S),w(),this.send({type:"response.done",event_id:O("event"),response:this.doneResponse(m,S,I)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(x.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=Fr){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${Fr} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(K(Ce("member_unresponsive",`the member served no content for ${Fr} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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(Bl(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.turnOutputFlowed=!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=Pe(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(Ce(cr,"the organization is out of credits \u2014 top up to continue"),cr))}failSessionGone(e){if(e instanceof V&&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(Ce("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof V){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof wi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Ce(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(ee("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.clientCancel=!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(ee("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>Et){this.send(K(ee("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${Et}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(K(ee("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(Ce(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($l,Br("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(Ll,Br(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=>yi(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),yi(this.id,e)}},qr=[];function yi(t,e){qr.push({id:t,reason:e}),qr.length>256&&qr.shift()}var Gr="/v1/realtime",_i="urun.admission",vi=t=>t.slice(0,120);function ql(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 hi(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 Jt=require("ws");var vi=require("@urun-sh/core");var wi=require("crypto");function O(t){return`${t}_${(0,wi.randomUUID)().replace(/-/g,"").slice(0,24)}`}var In=4*1024*1024,Lr=8*1024*1024,Nr=512,ht=20*1024*1024;function Z(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Ce(t,e){return{type:"server_error",code:t,message:e}}function K(t){return{type:"error",event_id:O("event"),error:t}}function Ur(){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},Cl={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},Ml={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},$l={format:!0,voice:!0,speed:!0};function Ll(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 yi(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 Nl=10;function Dr(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:Nl})}function Ht(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 Cl));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(!Ll(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=Dr(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 Ml))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&yi(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Ht({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Ht({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 $l))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&yi(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 Tn(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 Fr(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 On(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 Ul=1001,Dl=1011,Fl=6e4,Bl=3e5,Br=3;var Pn=class extends Error{},Cn=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"}},qr=t=>t.slice(0,120),ql=/^[A-Za-z0-9+/=]*$/,jl=2,Hl=600;function jr(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>jl)return!1;return!0}var Gt=class{id=O("conn");ws;binding;onClosed;operatorLog;turnStallMs;responseDeadlineMs;config=Ur();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;heldShedWarned=!1;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;turnDialGate=null;wakeTurnDialGate=null;deadlineFired=!1;seamEndedTurn=null;clientCancel=!1;seamEmptyStreak=0;turnOutputFlowed=!1;continuationTurnInFlight=!1;lastTurnParams={};collidingCreateWarned=!1;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;duplexSilenceMs=0;duplexInputCount=0;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??Fl,this.responseDeadlineMs=e.responseDeadlineMs??Bl,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===cr&&this.failInsufficientCredits()}).catch(()=>{}),this.send({type:"session.created",event_id:O("event"),session:Tn(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(),this.binding.duplex&&this.ensureVoice();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 V&&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(Ce("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.binding.duplex&&this.activeResponseId!==null&&this.closeDuplexResponse("cancelled"),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.binding.duplex&&!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")>In){this.fail(Z("frame_too_large",`frame exceeds the ${In}-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 Pn){this.fail(Ce(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??_e(o)}`),this.send(K(Ce(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.presence":return;case"session.update":{let n=Ht(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:Tn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Fr(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(!ql.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.binding.duplex){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}this.pendingAudioTotalBytes+r>ht&&!this.heldShedWarned&&(this.heldShedWarned=!0,this.operatorLog(`[${this.sessionId}] uncommitted input audio past the ${ht}-byte bound \u2014 shedding oldest chunks (latest-wins); a commit prefill now carries only the newest ${ht} bytes`));let o=this.pendingAudioTotalBytes+r;for(;o>ht&&this.pendingAudioBytes.length>0;){let s=this.pendingAudioBytes.shift();o-=Buffer.byteLength(s.audio,"base64")}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes=o;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}if(this.binding.duplex){this.send(K(Z("duplex_engine_owns_turns","this model is a full-duplex speech engine that decides its own turns \u2014 its replies arrive as server-initiated responses; response.create is not accepted","response.create")));return}if(this.continuationTurnInFlight){!this.collidingCreateWarned&&!this.closed&&(this.collidingCreateWarned=!0,this.operatorLog("[realtime] standing-cadence session: client response.create arrived while the continuation turn is live \u2014 ignored (the SDK re-open collides with the adapter's own continuation; response.cancel to force a fresh turn)"));return}this.lastTurnParams=e.response??{},this.startResponse(this.lastTurnParams);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,qr("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 Pn("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 Cn),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,n=!1){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}this.continuationTurnInFlight=n,this.turnOutputFlowed=!1;let r=e??{},o=r.modalities!==void 0?gt(r.modalities,"response.modalities"):void 0,s=r.output_modalities!==void 0?gt(r.output_modalities,"response.output_modalities"):void 0;if(o!==void 0&&s!==void 0&&o.slice().sort().join(",")!==s.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((s??o)?.includes("audio")&&!this.ensureVoice())return;if(r.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,this.seamEndedTurn=null,this.clientCancel=!1;let u=()=>{},a=new Promise((E,A)=>{u=()=>A(new Ze)});this.turnCancelled=a,this.wakeTurnCancelled=()=>u(),a.catch(()=>{});let l=()=>{},d=new Promise((E,A)=>{l=()=>A(new Ze)});this.turnDialGate=d,this.wakeTurnDialGate=()=>l(),d.catch(()=>{});let c=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 p=O("req"),m=`resp_${p}`;this.activeResponseId=m,this.activeRequestId=p;let g=this.binding.composite===!0,S=g?0:this.items.length,R=g?null:On(this.items),k=Dr(typeof r.instructions=="string"?r.instructions:this.config.instructions),b=typeof r.temperature=="number"?r.temperature:this.config.temperature,_=r.max_output_tokens??this.config.maxOutputTokens,f=_==="inf"||_===void 0?void 0:_,y=r.tools!==void 0?r.tools:this.config.tools,h=r.tool_choice!==void 0?r.tool_choice:this.config.toolChoice,v={stream:!0,...this.config.model?{model:this.config.model}:{},...k!==void 0?{instructions:k}:{},...b!==void 0?{temperature:b}:{},...f!==void 0?{max_output_tokens:f}:{},...y!==void 0?{tools:y}:{},...h!==void 0?{tool_choice:h}:{}};if(!(g&&!this.ensureVoice())){for(let{audio:E,captureWallMs:A}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(E,A);this.inFlight=(async()=>{let E=[],A=F=>{this.responseFlushed?this.send(F):E.push(F)},w=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:O("event"),response:this.responseObject(m,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(m,"in_progress")});for(let F of E)this.send(F);E.length=0,this.responseFlushed=!0}},x={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},I=null,$=()=>{this.seamEndedTurn="deadline",this.closeOpenItems(m,x,S),w(),this.send({type:"response.done",event_id:O("event"),response:this.responseObject(m,"incomplete",{status_details:{reason:"response_deadline"}})})};try{if(g){if(this.pendingTranscriptItemId!==null&&(await new Promise(W=>{this.pendingTranscriptSettled=W}),this.cancelled||this.closed))throw new Ze;S=this.items.length,R=On(this.items)}let{input:F,sawAudioOnlyItem:j}=R??{input:[],sawAudioOnlyItem:!1},N={...v,input:F,...g?this.compositeTurnAsk(r):{}};j&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let B;try{let W=this.upstreamStream(N,p);Promise.resolve(W).catch(C=>{C instanceof V&&this.failSessionGone(C)}),B=await Promise.race([W,d])}catch(W){if(W instanceof Ze){this.deadlineFired&&!this.closed&&$();return}this.upstreamTurnFault(W,m);return}w();try{for await(let W of this.stallBoundedTurn(B)){if(this.cancelled)break;let C=W;if(C.type==="error"){let X=this.upstreamErrorBody(C);x.contentFlowed?this.send(K(X)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(m,X)});return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){w(),x.contentFlowed=!0,x.messageOpen||(this.beginMessageItem(m,x.nextOutputIndex++),x.messageOpen=!0),this.config.outputModalities.includes("text")&&A({type:"response.output_text.delta",event_id:O("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:C.delta}),this.turnOutputIsAudio()&&(x.transcriptDelta=!0,A({type:"response.output_audio_transcript.delta",event_id:O("event"),item_id:`${m}_msg_0`,response_id:m,output_index:0,content_index:0,delta:C.delta})),x.messageText+=C.delta;continue}if(C.type==="response.function_call_arguments.delta"){w(),x.contentFlowed=!0;let X=typeof C.delta=="string"?C.delta:"",M=typeof C.call_id=="string"&&C.call_id.length>0?C.call_id:`${m}_fc_${x.nextOutputIndex}`,U=x.tools.get(M);if(!U){let z=typeof C.name=="string"&&C.name.length>0?C.name:void 0;U={outputIndex:x.nextOutputIndex++,name:z,args:""},x.tools.set(M,U);let Ie={id:M,object:"realtime.item",type:"function_call",call_id:M,name:z??"",arguments:"",status:"in_progress"};A({type:"response.output_item.added",event_id:O("event"),response_id:m,output_index:U.outputIndex,item:Ie}),this.emitAssistantItemAdded(Ie)}typeof C.name=="string"&&C.name.length>0&&(U.name=C.name),U.args+=X,A({type:"response.function_call_arguments.delta",event_id:O("event"),item_id:M,response_id:m,output_index:U.outputIndex,call_id:M,name:U.name??"",delta:X});continue}if(C.type==="response.completed"){I=C.response??null;continue}}}catch(W){if(this.closed)return;if(W instanceof Ze){this.deadlineFired&&$();return}if(this.cancelled)return;if(W instanceof Cn)this.seamEndedTurn="stall",this.operatorLog(`[realtime] turn ${m} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(W,m);return}}if(this.cancelled){this.deadlineFired&&!this.closed&&$();return}this.closeOpenItems(m,x,S),w(),this.send({type:"response.done",event_id:O("event"),response:this.doneResponse(m,S,I)})}finally{clearTimeout(c),this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null,this.turnDialGate=null,this.wakeTurnDialGate=null,this.continuationTurnInFlight=!1,this.maybeAutoContinue(x.contentFlowed||this.turnOutputFlowed)}})()}}maybeAutoContinue(e){let n=this.seamEndedTurn;if(this.seamEndedTurn=null,e&&(this.seamEmptyStreak=0),n===null||this.closed||this.clientCancel||!this.isStandingCadenceSession())return;if(!e&&++this.seamEmptyStreak>=Br){this.seamEmptyStreak=0,this.failMemberUnresponsive(n);return}let r=n;queueMicrotask(()=>{this.closed||this.inFlight!==null||this.clientCancel||(this.operatorLog(`[realtime] standing-cadence session: auto-continuing the decision stream after the ${r} turn end`),this.startResponse(this.lastTurnParams??{},!0))})}failMemberUnresponsive(e){this.operatorLog(`[realtime] standing-cadence session: ${Br} consecutive ${e}-ended turns delivered no content \u2014 failing the session (member_unresponsive)`),this.send(K(Ce("member_unresponsive",`the member served no content for ${Br} consecutive turn attempts \u2014 session failed`)));try{this.ws.close(1011,"member unresponsive")}catch{}}isStandingCadenceSession(){let e=this.config.instructions;if(typeof e!="string"||e.length===0)return!1;try{let n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)||n.hz===void 0&&n.cadence_ms===void 0?!1:"questions"in n||"question"in n}catch{return!1}}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.binding.duplex){if(this.activeResponseId===null){if(jr(n))return;this.openDuplexResponse()}else if(jr(n)){if(this.duplexSilenceMs+=Buffer.byteLength(n,"base64")/2/24,this.duplexSilenceMs>=Hl){this.closeDuplexResponse("completed");return}}else this.duplexSilenceMs=0;e=this.activeResponseId}if(this.activeResponseId!==e){if(jr(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.turnOutputFlowed=!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})}openDuplexResponse(){this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null,this.duplexInputCount=this.items.length,this.duplexSilenceMs=0,this.activeResponseId=`resp_${O("req")}`}closeDuplexResponse(e){let n=this.activeResponseId;this.closeOpenItems(n,{messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},this.duplexInputCount);let r=this.doneResponse(n,this.duplexInputCount,null);this.send({type:"response.done",event_id:O("event"),response:e==="cancelled"?{...r,status:e,status_details:{type:"cancelled",reason:"turn_detected"}}:r}),this.activeResponseId=null}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=Pe(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(Ce(pr,"the organization is out of credits \u2014 top up to continue"),pr))}failSessionGone(e){if(e instanceof V&&e.reason===cr){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: ${_e(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(Ce("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof V){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof vi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Ce(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.clientCancel=!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>Nr&&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>At){this.send(K(Z("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${At}-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(Ce(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>Lr){this.ws.close(Ul,qr("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=me(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${_e(e)}`),r.message}fail(e,n){this.send(K(e)),this.ws.close(Dl,qr(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=>_i(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),_i(this.id,e)}},Hr=[];function _i(t,e){Hr.push({id:t,reason:e}),Hr.length>256&&Hr.shift()}var Vr="/v1/realtime",bi="urun.admission",Si=t=>t.slice(0,120);function Gl(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
- ${vi(n)}\r
31
- `),t.destroy()}function jl(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
32
- `}function Hl(t){Re(process.stdout,t)}function Gl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function jr(t){return t.audioSession?.audio.sessionId??void 0}function Jr(t,e){let n=new Gt.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Gr)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=O("rtup"),l=Gl(o),d=w=>{(e.log??Hl)(jl(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)"),R=w=>m(`client socket error: ${w.message}`);s.once("close",g),s.once("end",S),s.once("error",R);let k=()=>{s.removeListener("close",g),s.removeListener("end",S),s.removeListener("error",R)},b=w=>{d({stage:"close",conn:a,model:l,...w})},_=null,f=!1,y=null,h=w=>JSON.stringify({type:_i,event_id:O("event"),...w}),v=w=>{if(_!==null){_.readyState===Gt.WebSocket.OPEN&&_.send(h(w));return}f||(f=!0,n.handleUpgrade(o,s,i,x=>{_=x,y=[],x.on("message",I=>{y?.push(String(I))}),d({stage:"waiting",conn:a,model:l,status:w.status}),x.send(h(w))}))},E=w=>{let x=w,I=x.session!=null&&typeof x.session.sendResponseCreate=="function",$=x.clients!=null&&typeof x.clients.createResponse=="function";if(!I&&!$)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((F,j)=>{let N=(B,W)=>{try{let C=Date.now();new Ht({ws:B,binding:w,operatorLog:e.operatorLog,...W.length>0?{replayFrames:W}:{},onClosed:(X,M)=>{b({while:"live",reason:M.reason});try{e.onSessionEnded?.({req:o,binding:w,connected_ms:Math.max(0,Date.now()-C),reason:M.reason})}catch(U){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${U instanceof Error?U.message:String(U)}
33
- `)}}}),d({stage:"admit",conn:a,model:l,...jr(w)===void 0?{}:{session:jr(w)}}),F()}catch(C){j(C)}};if(_!==null){let B=y??[];y=null,N(_,B);return}n.handleUpgrade(o,s,i,B=>N(B,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,v).then(async w=>{if(c.signal.aborted){k();let x=jr(w);try{await w.release?.()}catch(I){b({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",release_failed:I instanceof Error?I.message:String(I)});return}b({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",released:!0}),s.destroy();return}k(),await E(w)}).catch(w=>{let x=w instanceof Hr.SessionFailedError?kn(w):null,I=null;if(w!==null&&typeof w=="object"&&"status"in w){let N=w.status;typeof N=="number"&&(I=N)}let $=I??x?.status??502,F=w instanceof Error?w.message:String(w),j=I!==null?F:x!==null?qt(x,w instanceof Hr.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:F,status:$}}),_!==null&&!c.signal.aborted){let N=JSON.stringify({type:_i,event_id:O("event"),status:$<500?"rejected":"failed",reason:j});_.readyState===Gt.WebSocket.OPEN&&_.send(N),_.close(1011,vi(j));return}s.destroyed||ql(s,$,j)}).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 Ri=require("crypto");var Wr="x-urun-profile",Jt="voice";var de=class extends Error{status=400},Jl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Vl=/\s/;function Wl(t){return Jl.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 bi(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 Si(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 ${Wr} header is empty \u2014 the only profile this lane accepts is "${Jt}" (omit the header for the ordinary lane)`);if(l!==Jt)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Jt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Jt)throw new de(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Jt}"`);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:bi(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:bi(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 yt=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&&Wl(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 Le=(t,e)=>Object.assign(new Error(e),{status:t}),Yl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',zr=(t,e,n)=>new V(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Kr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof J?Le(404,n.message):n}};async function ki(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Le(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Yl}`);if(o==="transcription")throw Le(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 Le(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 Le(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?Le(404,m.message):m}if(!p)throw Le(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?Le(404,m.message):m}if(p!=="stt")throw Le(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 Kr(t,n.stt),i=await Kr(t,e),u=await Kr(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,Xl({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 V?zr("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function xi(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Vt=class extends Error{};async function*Xl(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,R=[],k=null,b=new Promise((x,I)=>{n&&n.addEventListener("abort",()=>I(new Vt),{once:!0})}),_=()=>m||n?.aborted===!0,f=async x=>{if(_())return;let I;try{I=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(F){throw F instanceof V?zr("tts",a.tts,F):F}let $=I[Symbol.asyncIterator]();S=$;try{for(;;){let F=$.next(),j;try{j=await Promise.race([F,b])}catch(B){if(F.catch(()=>{}),B instanceof Vt)return;throw B}if(j.done)return;let N=j.value;if(N.type==="error"){let B=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: ${B}`)}if(N.type==="response.completed")return}}finally{S===$&&(S=null)}},y=async()=>{for(;R.length>0&&!_();){let x=R.shift();await f(x)}},h=x=>{if(x===""||_()||(R.push(x),k!==null))return;let I=y();k=I,I.then(()=>{k===I&&(k=null)},$=>{k===I&&(k=null),g??=$})},v=()=>{m=!0,R.length=0;let x=S;if(S=null,x){let I=x.return?.();I&&I.catch(()=>{})}},E=async()=>{for(;R.length>0||k!==null;){let x=k;if(x===null){await f(R.shift());continue}await x}},A=p?new yt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},x=>h(x)):null,w=null;try{let x;try{x=await o.createResponseOn(s,d)}catch($){throw $ instanceof V?zr("chat",u,$):$}let I=x[Symbol.asyncIterator]();try{for(;;){let $=I.next(),F;try{F=await Promise.race([$,b])}catch(B){if($.catch(()=>{}),B instanceof Vt)break;throw B}if(F.done)break;let j=F.value;if(_())return;let N=j;if(N.type==="error"){yield j;return}if(N.type==="response.output_text.delta"&&typeof N.delta=="string"){yield j,A?.push(N.delta);continue}if(N.type==="response.function_call_arguments.delta"){A?.flush(),yield j;continue}if(N.type==="response.completed"){w=j.response;continue}}}finally{Promise.resolve(I.return?.()).catch(()=>{})}A?.flush(),A?.dispose(),p&&await E(),w!==null&&(yield{type:"response.completed",response:w})}finally{A?.dispose(),v();try{if(g instanceof V)throw g}finally{r?.()}}}var me=(t,e)=>Object.assign(new Error(e),{status:t});function Ql(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Zl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var ed='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function td(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 ki(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: ${ed}`);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,Ri.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 Ei(t,e,n){let r=xi(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 td(r,Ql(o),s,Zl(o),i)}}}var D=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 wt(t,e){if(t!=null)throw new D(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Yr(t){let e=Pn(t);return e!==null&&e<=1?e:null}function Ai(t,e){if(!se(t))throw new D("decisions requires a JSON object body");wt(t.prompt_cache_key,"prompt_cache_key"),wt(t.prompt_cache_options,"prompt_cache_options"),wt(t.safety_identifier,"safety_identifier");let n=[],r=nd(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new D("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}=id(o[l],l,o.length,n);if(u.has(c.key))throw new D(`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 nd(t,e){if(typeof t=="string")return t;if(!se(t)&&!Array.isArray(t))throw new D("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)od(o,r,e);return rd(r)}function rd(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
30
+ ${Si(n)}\r
31
+ `),t.destroy()}function Jl(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
32
+ `}function Vl(t){Re(process.stdout,t)}function Wl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Gr(t){return t.audioSession?.audio.sessionId??void 0}function Wr(t,e){let n=new Jt.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Vr)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=O("rtup"),l=Wl(o),d=w=>{(e.log??Vl)(Jl(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)"),R=w=>m(`client socket error: ${w.message}`);s.once("close",g),s.once("end",S),s.once("error",R);let k=()=>{s.removeListener("close",g),s.removeListener("end",S),s.removeListener("error",R)},b=w=>{d({stage:"close",conn:a,model:l,...w})},_=null,f=!1,y=null,h=w=>JSON.stringify({type:bi,event_id:O("event"),...w}),v=w=>{if(_!==null){_.readyState===Jt.WebSocket.OPEN&&_.send(h(w));return}f||(f=!0,n.handleUpgrade(o,s,i,x=>{_=x,y=[],x.on("message",I=>{y?.push(String(I))}),d({stage:"waiting",conn:a,model:l,status:w.status}),x.send(h(w))}))},E=w=>{let x=w,I=x.session!=null&&typeof x.session.sendResponseCreate=="function",$=x.clients!=null&&typeof x.clients.createResponse=="function";if(!I&&!$)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((F,j)=>{let N=(B,W)=>{try{let C=Date.now();new Gt({ws:B,binding:w,operatorLog:e.operatorLog,...W.length>0?{replayFrames:W}:{},onClosed:(X,M)=>{b({while:"live",reason:M.reason});try{e.onSessionEnded?.({req:o,binding:w,connected_ms:Math.max(0,Date.now()-C),reason:M.reason})}catch(U){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${U instanceof Error?U.message:String(U)}
33
+ `)}}}),d({stage:"admit",conn:a,model:l,...Gr(w)===void 0?{}:{session:Gr(w)}}),F()}catch(C){j(C)}};if(_!==null){let B=y??[];y=null,N(_,B);return}n.handleUpgrade(o,s,i,B=>N(B,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,v).then(async w=>{if(c.signal.aborted){k();let x=Gr(w);try{await w.release?.()}catch(I){b({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",release_failed:I instanceof Error?I.message:String(I)});return}b({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",released:!0}),s.destroy();return}k(),await E(w)}).catch(w=>{let x=w instanceof Jr.SessionFailedError?Rn(w):null,I=null;if(w!==null&&typeof w=="object"&&"status"in w){let N=w.status;typeof N=="number"&&(I=N)}let $=I??x?.status??502,F=w instanceof Error?w.message:String(w),j=I!==null?F:x!==null?jt(x,w instanceof Jr.SessionFailedError&&w.status.sessionId?`session ${w.status.sessionId}`:void 0):me(w).message;if(b({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:F,status:$}}),_!==null&&!c.signal.aborted){let N=JSON.stringify({type:bi,event_id:O("event"),status:$<500?"rejected":"failed",reason:j});_.readyState===Jt.WebSocket.OPEN&&_.send(N),_.close(1011,Si(j));return}s.destroyed||Gl(s,$,j)}).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 Ai=require("crypto");var zr="x-urun-profile",Vt="voice";var ce=class extends Error{status=400},Kl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,zl=/\s/;function Yl(t){return Kl.test(t)}function Kr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ce(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function ki(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 ce(`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 ce(`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 ce(`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 xi(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 ce(`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 ce(`the ${zr} header is empty \u2014 the only profile this lane accepts is "${Vt}" (omit the header for the ordinary lane)`);if(l!==Vt)throw new ce(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Vt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Vt)throw new ce(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Vt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ce("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 ce("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:ki(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:ki(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Kr(a,"sentence_flush",!0),includeReasoning:Kr(a,"include_reasoning",!1),metadata:Kr(a,"metadata",!1)}}var yt=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&&Yl(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(zl.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 Le=(t,e)=>Object.assign(new Error(e),{status:t}),Zl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Xr=(t,e,n)=>new V(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Yr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof J?Le(404,n.message):n}};async function Ri(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Le(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Zl}`);if(o==="transcription")throw Le(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 Le(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 Le(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?Le(404,m.message):m}if(!p)throw Le(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?Le(404,m.message):m}if(p!=="stt")throw Le(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 Yr(t,n.stt),i=await Yr(t,e),u=await Yr(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,ed({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 V?Xr("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function Ei(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Wt=class extends Error{};async function*ed(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,R=[],k=null,b=new Promise((x,I)=>{n&&n.addEventListener("abort",()=>I(new Wt),{once:!0})}),_=()=>m||n?.aborted===!0,f=async x=>{if(_())return;let I;try{I=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(F){throw F instanceof V?Xr("tts",a.tts,F):F}let $=I[Symbol.asyncIterator]();S=$;try{for(;;){let F=$.next(),j;try{j=await Promise.race([F,b])}catch(B){if(F.catch(()=>{}),B instanceof Wt)return;throw B}if(j.done)return;let N=j.value;if(N.type==="error"){let B=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: ${B}`)}if(N.type==="response.completed")return}}finally{S===$&&(S=null)}},y=async()=>{for(;R.length>0&&!_();){let x=R.shift();await f(x)}},h=x=>{if(x===""||_()||(R.push(x),k!==null))return;let I=y();k=I,I.then(()=>{k===I&&(k=null)},$=>{k===I&&(k=null),g??=$})},v=()=>{m=!0,R.length=0;let x=S;if(S=null,x){let I=x.return?.();I&&I.catch(()=>{})}},E=async()=>{for(;R.length>0||k!==null;){let x=k;if(x===null){await f(R.shift());continue}await x}},A=p?new yt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},x=>h(x)):null,w=null;try{let x;try{x=await o.createResponseOn(s,d)}catch($){throw $ instanceof V?Xr("chat",u,$):$}let I=x[Symbol.asyncIterator]();try{for(;;){let $=I.next(),F;try{F=await Promise.race([$,b])}catch(B){if($.catch(()=>{}),B instanceof Wt)break;throw B}if(F.done)break;let j=F.value;if(_())return;let N=j;if(N.type==="error"){yield j;return}if(N.type==="response.output_text.delta"&&typeof N.delta=="string"){yield j,A?.push(N.delta);continue}if(N.type==="response.function_call_arguments.delta"){A?.flush(),yield j;continue}if(N.type==="response.completed"){w=j.response;continue}}}finally{Promise.resolve(I.return?.()).catch(()=>{})}A?.flush(),A?.dispose(),p&&await E(),w!==null&&(yield{type:"response.completed",response:w})}finally{A?.dispose(),v();try{if(g instanceof V)throw g}finally{r?.()}}}var ge=(t,e)=>Object.assign(new Error(e),{status:t});function td(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function nd(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var rd='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function od(t,e,n,r,o){if(!t.supportsAudio)throw ge(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?ge(404,m.message):m}if(!s){let m=null;if(t.realtimeCompanionsFor)try{m=await t.realtimeCompanionsFor(e)}catch(g){throw g instanceof J?ge(404,g.message):g}if(m!==null)return await Ri(t,e,m,n,r);throw ge(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 ge(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?ge(404,m.message):m}if(i&&!t.openTurnsOn)throw ge(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?ge(404,g.message):g}if(m!=="stt")throw ge(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 ge(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${rd}`);if(r==="transcription"&&!i)throw ge(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 pe?ge(503,m.message):m}let a=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,Ai.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 Ii(t,e,n){let r=Ei(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 ge(401,"invalid local proxy api key")}return od(r,td(o),s,nd(o),i)}}}var D=class extends Error{},ue=class extends Error{};function oe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Kt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function _t(t,e){if(t!=null)throw new D(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Qr(t){let e=Kt(t);return e!==null&&e<=1?e:null}function Ti(t,e){if(!oe(t))throw new D("decisions requires a JSON object body");_t(t.prompt_cache_key,"prompt_cache_key"),_t(t.prompt_cache_options,"prompt_cache_options"),_t(t.safety_identifier,"safety_identifier");let n=[],r=sd(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new D("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}=ld(o[l],l,o.length,n);if(u.has(c.key))throw new D(`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 sd(t,e){if(typeof t=="string")return t;if(!oe(t)&&!Array.isArray(t))throw new D("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)ad(o,r,e);return id(r)}function id(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 od(t,e,n){if(!se(t))throw new D("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){sd(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)){Ii(s,e,n,void 0,!1);return}throw new D(`${o} output must be a string or an array of parts`)}default:throw new D(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function sd(t,e,n,r){e==="assistant"&&wt(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 D(`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 D("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 D(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}Ii(o,n,r,e)}function Ii(t,e,n,r,o=!0){for(let s of t){if(!se(s))throw new D("decisions content parts must be JSON objects");switch(wt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new D("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new D("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 D("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Ti(s));break}default:throw new D(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Ti(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new D("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new D("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 D("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 D("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 D("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 id(t,e,n,r){if(!se(t))throw new D(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new D(`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 D(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=ad(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 D(`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 D(`questions[${e}] choices must be JSON objects`);let R=S.value;if(typeof R!="string"&&typeof R!="boolean")throw new D(`questions[${e}] choice value must be a string or boolean`);let k=String(R);if(c.has(k))throw new D(`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 D(`questions[${e}] choice description must be a string`);d.push(R),p.push(b)}let m=l.map((S,R)=>({name:String(d[R]),description:p[R]??String(d[R])}));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 D(`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 D(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new D(`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 D(`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 D(`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 ad(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new D(`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 D(`questions[${e}] instruction parts must be JSON objects`);switch(wt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new D(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new D(`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(Ti(s));break}case"input_json":{let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new D(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new D(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
35
+ `)}function ad(t,e,n){if(!oe(t))throw new D("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){ud(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)){Oi(s,e,n,void 0,!1);return}throw new D(`${o} output must be a string or an array of parts`)}default:throw new D(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function ud(t,e,n,r){e==="assistant"&&_t(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 D(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!oe(s))throw new D("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 D(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}Oi(o,n,r,e)}function Oi(t,e,n,r,o=!0){for(let s of t){if(!oe(s))throw new D("decisions content parts must be JSON objects");switch(_t(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new D("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new D("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(!oe(i)&&!(Array.isArray(i)&&i.every(oe)))throw new D("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Pi(s));break}default:throw new D(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Pi(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new D("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new D("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 D("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 D("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 D("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 ld(t,e,n,r){if(!oe(t))throw new D(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new D(`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 D(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=dd(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 D(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let S of l){if(!oe(S))throw new D(`questions[${e}] choices must be JSON objects`);let R=S.value;if(typeof R!="string"&&typeof R!="boolean")throw new D(`questions[${e}] choice value must be a string or boolean`);let k=String(R);if(c.has(k))throw new D(`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 D(`questions[${e}] choice description must be a string`);d.push(R),p.push(b)}let m=l.map((S,R)=>({name:String(d[R]),description:p[R]??String(d[R])}));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 D(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!oe(m)||typeof m.label!="string")throw new D(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new D(`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 D(`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 D(`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 dd(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new D(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!oe(s))throw new D(`questions[${e}] instruction parts must be JSON objects`);switch(_t(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new D(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new D(`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(Pi(s));break}case"input_json":{let i=s.data;if(!oe(i)&&!(Array.isArray(i)&&i.every(oe)))throw new D(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new D(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
36
36
 
37
- `)}function Oi(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=Yr(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=Yr(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=Yr(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 Pi="/v1/images/generations",$n="/v1/images/edits";function Ci(t){return t===Pi||t===$n}var Mi="/v1/images/models";async function $i(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}},ud=16*1024*1024,Li=64*1024*1024;function Ni(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 Wt(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 Ui(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??{},R=typeof S.message=="string"&&S.message.length>0&&ke(S.message)?S.message:null;throw R===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: ${R}`)}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=$e(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(Ni(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 Di(t,e){if(t instanceof G)return t;if(t instanceof Te)throw t;return t instanceof J?new G(404,t.message):new G(502,ft("image",t,e))}async function Fi(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 Wt(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 Bi(t,e){t&&(t.outputUnits=e.images.length)}function qi(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 ld={model:!0,prompt:!0,response_format:!0,n:!0};async function ji(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Li;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${Pi}`);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(!ld[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 $i(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 Fi(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await Ui(n.clients,a,c,n.turn?he(n.turn):void 0,n.turn,r);Bi(n.turn,p),qi(e,p)}catch(p){throw Di(p,r)}}catch(s){if(s instanceof ie){Wt(e,new G(413,s.message));return}if(s instanceof G){Wt(e,s);return}throw s}}var dd={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Hi(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Li,s=n.maxImagePartBytes??ud;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 $i(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(!dd[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 S of u.getAll(g)){if(!(S 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(S.size>s)throw new G(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let R=new Uint8Array(await S.arrayBuffer()),k=Ni(R);if(k===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:R,mime:k})}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 Fi(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 Ui(n.clients,d,m,n.turn?he(n.turn):void 0,n.turn,r);Bi(n.turn,g),qi(e,g)}catch(g){throw Di(g,r)}}catch(i){if(i instanceof ie){Wt(e,new G(413,i.message));return}if(i instanceof G){Wt(e,i);return}throw i}}var Kt="/v1/audio/speech";function Qi(t){return t===Kt}var Gi=4096,Ji=18e4,Vi=5e3,cd=64*1024*1024,Wi=8,Ki=5,zi=1024*1024,_t="voice_applied",Nn="X-Urun-Voice-Applied",q=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Xr(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 q{constructor(e){super(502,e)}};function Zi(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 ea(t){return new q(502,`the runtime's ${_t} 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 pd(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 ta(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var fd=2;function md(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>fd)return!1;return!0}function gd(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 Yi=new WeakMap,Ln=new WeakMap;function hd(t,e){let n=Ln.get(t)??0;if(n>=Wi)throw new q(503,`this model's speech queue is full \u2014 ${Wi} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Ki}s`,void 0,Ki);Ln.set(t,n+1);let r=Yi.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Yi.set(t,s),(async()=>{await r;try{return await e()}finally{Ln.set(t,(Ln.get(t)??1)-1),o()}})()}async function yd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new q(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 V))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 q)return t;if(t instanceof Te)throw t;return t instanceof J?new q(404,t.message):new q(502,ft("speech",t,e))}async function Xi(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return hd(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,g=!1,S,R=new Promise(x=>{S=x}),k=[],b,_=!1,f=null,y=()=>{f!==null&&(clearTimeout(b),b=setTimeout(()=>{_=!0,f?.()},o.capMs))},h=()=>{m&&!g&&k.length>=o.quietRunFrames&&(g=!0,S())},v=e.onOutputAudio(x=>{let I=Buffer.from(x,"base64");if(I.byteLength===0)return;y();let $=md(I);if(!p){if($)return;p=!0}if($){k.push(I),h();return}for(let F of k)c(F);k.length=0,c(I),h()}),E=null,A,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 I=()=>(clearTimeout(A),new Promise(N=>{A=setTimeout(N,s.capMs)})),$=I(),F=!1;for(;;){let N=w.next(),B=await Promise.race([N,$]);if(B===void 0){F=!0,N.catch(()=>{});break}if(B.done)break;let W=B.value;if($=I(),W.type==="error"){let C=W.error??{};await w.return?.();let X=typeof C.message=="string"&&C.message.length>0&&ke(C.message)?C.message:null;throw X===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(W)}`),new q(502,"the speech upstream failed while serving this request")):new q(502,`speech upstream error: ${X}`)}if(W.type==="response.completed"){E=W.response??null,m=!0,a?.(E),h(),await w.return?.();break}}if(clearTimeout(A),F)throw new q(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 q(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=new Promise(N=>{f=N});if(y(),await Promise.race([R,j]),clearTimeout(b),b=void 0,f=null,r.voice!==void 0){let N=E[_t];if(typeof N!="string"||N!==r.voice){let B=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof N=="string"?`${_t} ${JSON.stringify(N)}`:`no ${_t} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new Un(B):new q(502,B)}}if(!p)throw new q(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(_&&!g&&k.length<1)throw new q(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 yd(t,n,w,s.returnBoundMs),x}finally{clearTimeout(b),clearTimeout(A),v()}})}function wd(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,ta(e,s))}),t.writableLength>zi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${zi} 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[_t];if(typeof a=="string"){if(!Zi(a))throw ea(a);t.addTrailers({[Nn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function _d(t,e,n,r){let o;try{o=await t(e)}catch(s){throw et(s,r)}return o?!0:(Xr(n,new q(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 vd={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},bd="wav, pcm";async function na(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??cd,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${Kt}`);let u;try{u=JSON.parse((await Cn(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof ie?new q(413,f.message):new q(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new q(400,"request body must be a JSON object");let a=u;for(let f of Object.keys(a))if(!vd[f])throw new q(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 q(400,"input is required and must be a non-empty string","input");if(l.length>Gi)throw new q(400,`input is ${l.length} chars \u2014 over the ${Gi}-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 q(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new q(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new q(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 ${Kt} 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 q(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 q(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 q(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 ${bd} \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 q(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 q(400,"speed, when present, must be a number","speed");if(S!==1)throw new q(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 R=a.instructions;if(R!==void 0){if(typeof R!="string")throw new q(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new q(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 pd(n.turn,n.clients,d);let k=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",k,k),!await _d(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new q(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 q(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 q(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 _;try{_=await n.clients.openAudioOn(b)}catch(f){throw et(f,r)}n.turn&&(n.turn.sessionId=_.sessionId);try{if(g==="wav"){let f=[],y=await Xi(n.clients,_,b,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ji,returnBoundMs:n.turnReturnBoundMs??Vi},i,v=>f.push(v),v=>{n.turn&&(n.turn.outputSeconds=$e(v))},r);if(y===null||i())return;let h=Buffer.concat(f);if(m===void 0){let v=y[_t];if(typeof v=="string"){if(!Zi(v))throw ea(v);e.setHeader(Nn,v)}}ta(n.turn,h.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([gd(h.byteLength),h]))}else{let f=wd(e,n.turn,i,m===void 0),y;try{y=await Xi(n.clients,_,b,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ji,returnBoundMs:n.turnReturnBoundMs??Vi},i,f.sink,h=>{n.turn&&(n.turn.outputSeconds=$e(h))},r)}catch(h){let v=et(h,r);if(!f.started())throw v;n.turn&&(n.turn.streamError=!0),f.fail(v);return}if(y===null)return;try{await f.finish(y)}catch(h){let v=et(h,r);n.turn&&(n.turn.streamError=!0),f.fail(v);return}}}catch(f){throw et(f,r)}}catch(u){if(u instanceof ie){Xr(e,new q(413,u.message));return}if(u instanceof q){Xr(e,u);return}throw u}}var Dn="/v1/audio/transcriptions";function ra(t){return t===Dn}var oa="/v1/audio/models",Sd=16*1024*1024,kd=64*1024*1024,te=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Qr(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 sa(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 xd(t){if(!sa(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 Rd(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 Ed(t,e){t&&(t.outputUnits=e.seconds)}async function Ad(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=$e(d)),ct(l,d)}function ia(t,e){if(t instanceof te)return t;if(t instanceof Te)throw t;return t instanceof J?new te(404,t.message):new te(502,ft("transcription",t,e))}async function Id(t,e,n,r){let o;try{o=await t(e)}catch(s){throw ia(s,r)}return o?!0:(Qr(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 Td=new Set(["file","model","language","response_format"]);async function aa(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??kd,s=n.maxAudioPartBytes??Sd;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(!Td.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,_]of a)if(_>1)throw new te(400,`form field "${b}" appears ${_} 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(!sa(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 R=xd(S);if(R===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 Rd(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",S.length,S.length),!await Id(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 Ad(n.clients,d,k,p,n.turn?he(n.turn):void 0,n.turn,r);Ed(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw ia(b,r)}}catch(i){if(i instanceof ie){Qr(e,new te(413,i.message));return}if(i instanceof te){Qr(e,i);return}throw i}}var la="/v1/usage/requests",ua=1e4,Od=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,je=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},vt=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var da=1024*1024;function Zr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new je(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new je(`"${e}" must be an array of uuid strings`);if(n.length>ua)throw new je(`"${e}" carries ${n.length} ids; at most ${ua} 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"||!Od.test(s))throw new je(`"${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 ca(t){return Zr(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 vt(`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 vt(`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 eo="/partners/huggingface/v1/billing/requests";function Pd(t){return Zr(t,"requestIds")}function Cd(t){return t>=200&&t<=399}function Md(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Cd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function pa(t,e){let n=Pd(t),r=await e(n);return Fn(r,n),Md(r)}var $d={"/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 Ld(t){return $d[t]??null}var ha=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Nd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Ud(t){return t==="surface"}function Dd(t){let e=t?.ledgerFailureReason;return ha.includes(e)?e:"unknown"}var Fd=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],fa=["priced","unpriced"],Bd={written:fa,already_written:fa,skipped:Fd,failed:ha},sg=Object.entries(Bd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function qd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function jd(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 Hd=256,ma=4096,Yt=12e4,Gd=250,Jd=8e3,Xt=[],ga=new Set,Qt=0,zt=!1;var Vd=new Set;function Wd(){return Qt===0&&Xt.length===0}function Kd(){if(Wd()){zt=!1;for(let t of[...Vd])t()}}function ya(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
38
- `}function zd(t){Re(process.stdout,t)}function wa(t,e){try{t(e)}catch{}}function _a(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??zd,o=Ld(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),wa(r,ya("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:jd(e),completed_at:e.ts,billable_outcome:qd(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(Xt.length>=ma){i("queue_full",`${Xt.length} ledger writes are already waiting (capacity ${ma}, ${Qt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Xt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Qt<Hd&&(Qt+=1,Yd())}async function Yd(){try{for(;;){let t=Xd();if(t===void 0)return;ga.add(t);try{await Qd(t)}finally{ga.delete(t)}}}finally{Qt-=1,Kd()}}function Xd(){let t=Date.now();for(;;){let e=Xt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Yt)return e;bt(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 ${Yt}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 Qd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);bt(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=Nd(o);if(s!==null){bt(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=Dd(o),u=Date.now()-t.queuedAt;if(zt){bt(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(Ud(i)&&u<Yt){if(await ec(Zd(t.attempts)),zt||Date.now()-t.queuedAt>=Yt){let a=Date.now()-t.queuedAt;bt(t,{outcome:"failed",reason:zt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:zt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${Yt}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}bt(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 Zd(t){return Math.min(Jd,Gd*2**Math.max(0,t-1))}function ec(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function bt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;wa(t.report,ya(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function ro(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function tc(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 oo(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Pe(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 St(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 nc=64*1024*1024,Zt=class extends Error{};async function va(t,e=nc){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Zt(`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 ka(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=ka(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ba(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:rc(t)},completion_tokens_details:{reasoning_tokens:0}}}function rc(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 oc(t,e){let n=ka(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function sc(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 ic(t,e){let n=sc(e);n&&(t.timing=n),t.outputSeconds=$e(e)}function nt(t,e){oc(t,e),ic(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 xa(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 ac(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 uc(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 lc(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:uc(n.role,n.content)})}return e}function to(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 dc(t,e,n,r,o,s,i){let u=Dt(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 Bt({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(_){if(_ instanceof J){St(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 _}ro(r);for await(let _ of b.events){if(_.type==="error"){s.streamError=!0;let f=_.error,y=Pe(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(_)}`),r.write(`event: error
37
+ `)}function Ci(t,e){if(!oe(e))throw new ue("decision answer was not a JSON object");let n=e.answers;if(!oe(n))throw new ue("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!oe(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=oe(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=Qr(s.noul);if(u===null)throw new ue(`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 ue(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new ue(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=Kt(s.confidence);if(d===null)throw new ue(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let m=Qr(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=Kt(s.score);if(a===null)throw new ue(`the score answer for "${o.key}" carries no numeric score to translate`);let l=Kt(s.confidence);if(l===null)throw new ue(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<u.length;c++){let p=Qr(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}function wt(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function cd(t){let e=oe(t.input_tokens_details)?t.input_tokens_details.cached_tokens:void 0,n=e!==void 0?e:t.cached_tokens;return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:0}function Mi(t){if(t==null)return null;if(!oe(t))throw new ue("decision reply carried a usage receipt that is not a JSON object");let e=wt(t.prompt_tokens)??wt(t.input_tokens),n=wt(t.completion_tokens)??wt(t.output_tokens);if(e===null||n===null)throw new ue("decision reply carried a usage receipt with no usable token counts");let r=Kt(t.ttft_ms),o=wt(t.total_tokens)??wt(e+n);if(o===null)throw new ue("decision reply carried a usage receipt with an unusable token total");return{input_tokens:e,input_tokens_details:{cache_write_tokens:0,cached_tokens:cd(t)},output_tokens:n,output_tokens_details:{reasoning_tokens:0},total_tokens:o,...r!==null?{ttft_ms:r}:{}}}var ie=class extends Error{};async function Mn(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 $n(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 $i="/v1/images/generations",Ln="/v1/images/edits";function Li(t){return t===$i||t===Ln}var Ni="/v1/images/models";async function Ui(t,e,n){if(t){if(t.model=le({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}},pd=16*1024*1024,Di=64*1024*1024;function Fi(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 zt(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 Bi(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??{},R=typeof S.message=="string"&&S.message.length>0&&ke(S.message)?S.message:null;throw R===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: ${R}`)}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=$e(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(Fi(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 qi(t,e){if(t instanceof G)return t;if(t instanceof Te)throw t;return t instanceof J?new G(404,t.message):new G(502,ft("image",t,e))}async function ji(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 zt(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 Hi(t,e){t&&(t.outputUnits=e.images.length)}function Gi(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 fd={model:!0,prompt:!0,response_format:!0,n:!0};async function Ji(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Di;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${$i}`);let s;try{s=JSON.parse((await Mn(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(!fd[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 Ui(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 ji(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await Bi(n.clients,a,c,n.turn?ye(n.turn):void 0,n.turn,r);Hi(n.turn,p),Gi(e,p)}catch(p){throw qi(p,r)}}catch(s){if(s instanceof ie){zt(e,new G(413,s.message));return}if(s instanceof G){zt(e,s);return}throw s}}var md={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Vi(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Di,s=n.maxImagePartBytes??pd;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${Ln}`);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 $n(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 Ui(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(!md[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 S of u.getAll(g)){if(!(S 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(S.size>s)throw new G(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let R=new Uint8Array(await S.arrayBuffer()),k=Fi(R);if(k===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:R,mime:k})}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 ji(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 Bi(n.clients,d,m,n.turn?ye(n.turn):void 0,n.turn,r);Hi(n.turn,g),Gi(e,g)}catch(g){throw qi(g,r)}}catch(i){if(i instanceof ie){zt(e,new G(413,i.message));return}if(i instanceof G){zt(e,i);return}throw i}}var Yt="/v1/audio/speech";function ta(t){return t===Yt}var Wi=4096,Ki=18e4,zi=5e3,gd=64*1024*1024,Yi=8,Xi=5,Qi=1024*1024,vt="voice_applied",Un="X-Urun-Voice-Applied",q=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Zr(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 Dn=class extends q{constructor(e){super(502,e)}};function na(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 ra(t){return new q(502,`the runtime's ${vt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Un} 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 hd(t,e,n){if(t){if(t.model=le({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 oa(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var yd=2;function wd(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>yd)return!1;return!0}function _d(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,Nn=new WeakMap;function vd(t,e){let n=Nn.get(t)??0;if(n>=Yi)throw new q(503,`this model's speech queue is full \u2014 ${Yi} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Xi}s`,void 0,Xi);Nn.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{Nn.set(t,(Nn.get(t)??1)-1),o()}})()}async function bd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new q(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 V))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 q)return t;if(t instanceof Te)throw t;return t instanceof J?new q(404,t.message):new q(502,ft("speech",t,e))}async function ea(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return vd(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,g=!1,S,R=new Promise(x=>{S=x}),k=[],b,_=!1,f=null,y=()=>{f!==null&&(clearTimeout(b),b=setTimeout(()=>{_=!0,f?.()},o.capMs))},h=()=>{m&&!g&&k.length>=o.quietRunFrames&&(g=!0,S())},v=e.onOutputAudio(x=>{let I=Buffer.from(x,"base64");if(I.byteLength===0)return;y();let $=wd(I);if(!p){if($)return;p=!0}if($){k.push(I),h();return}for(let F of k)c(F);k.length=0,c(I),h()}),E=null,A,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 I=()=>(clearTimeout(A),new Promise(N=>{A=setTimeout(N,s.capMs)})),$=I(),F=!1;for(;;){let N=w.next(),B=await Promise.race([N,$]);if(B===void 0){F=!0,N.catch(()=>{});break}if(B.done)break;let W=B.value;if($=I(),W.type==="error"){let C=W.error??{};await w.return?.();let X=typeof C.message=="string"&&C.message.length>0&&ke(C.message)?C.message:null;throw X===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(W)}`),new q(502,"the speech upstream failed while serving this request")):new q(502,`speech upstream error: ${X}`)}if(W.type==="response.completed"){E=W.response??null,m=!0,a?.(E),h(),await w.return?.();break}}if(clearTimeout(A),F)throw new q(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 q(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=new Promise(N=>{f=N});if(y(),await Promise.race([R,j]),clearTimeout(b),b=void 0,f=null,r.voice!==void 0){let N=E[vt];if(typeof N!="string"||N!==r.voice){let B=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof N=="string"?`${vt} ${JSON.stringify(N)}`:`no ${vt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new Dn(B):new q(502,B)}}if(!p)throw new q(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(_&&!g&&k.length<1)throw new q(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 Dn||await bd(t,n,w,s.returnBoundMs),x}finally{clearTimeout(b),clearTimeout(A),v()}})}function Sd(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",Un)),t.write(u,a=>{a||(s+=u.byteLength,oa(e,s))}),t.writableLength>Qi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Qi} 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[vt];if(typeof a=="string"){if(!na(a))throw ra(a);t.addTrailers({[Un]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function kd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw et(s,r)}return o?!0:(Zr(n,new q(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 xd={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Rd="wav, pcm";async function sa(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??gd,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${Yt}`);let u;try{u=JSON.parse((await Mn(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof ie?new q(413,f.message):new q(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new q(400,"request body must be a JSON object");let a=u;for(let f of Object.keys(a))if(!xd[f])throw new q(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 q(400,"input is required and must be a non-empty string","input");if(l.length>Wi)throw new q(400,`input is ${l.length} chars \u2014 over the ${Wi}-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 q(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new q(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new q(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 ${Yt} 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 q(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 q(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 q(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 ${Rd} \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 q(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 q(400,"speed, when present, must be a number","speed");if(S!==1)throw new q(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 R=a.instructions;if(R!==void 0){if(typeof R!="string")throw new q(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new q(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 hd(n.turn,n.clients,d);let k=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",k,k),!await kd(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new q(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 q(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 q(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 _;try{_=await n.clients.openAudioOn(b)}catch(f){throw et(f,r)}n.turn&&(n.turn.sessionId=_.sessionId);try{if(g==="wav"){let f=[],y=await ea(n.clients,_,b,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ki,returnBoundMs:n.turnReturnBoundMs??zi},i,v=>f.push(v),v=>{n.turn&&(n.turn.outputSeconds=$e(v))},r);if(y===null||i())return;let h=Buffer.concat(f);if(m===void 0){let v=y[vt];if(typeof v=="string"){if(!na(v))throw ra(v);e.setHeader(Un,v)}}oa(n.turn,h.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([_d(h.byteLength),h]))}else{let f=Sd(e,n.turn,i,m===void 0),y;try{y=await ea(n.clients,_,b,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ki,returnBoundMs:n.turnReturnBoundMs??zi},i,f.sink,h=>{n.turn&&(n.turn.outputSeconds=$e(h))},r)}catch(h){let v=et(h,r);if(!f.started())throw v;n.turn&&(n.turn.streamError=!0),f.fail(v);return}if(y===null)return;try{await f.finish(y)}catch(h){let v=et(h,r);n.turn&&(n.turn.streamError=!0),f.fail(v);return}}}catch(f){throw et(f,r)}}catch(u){if(u instanceof ie){Zr(e,new q(413,u.message));return}if(u instanceof q){Zr(e,u);return}throw u}}var Fn="/v1/audio/transcriptions";function ia(t){return t===Fn}var aa="/v1/audio/models",Ed=16*1024*1024,Ad=64*1024*1024,te=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function eo(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 ua(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 Id(t){if(!ua(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 Td(t,e,n){if(t){if(t.model=le({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 Od(t,e){t&&(t.outputUnits=e.seconds)}async function Pd(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=$e(d)),ct(l,d)}function la(t,e){if(t instanceof te)return t;if(t instanceof Te)throw t;return t instanceof J?new te(404,t.message):new te(502,ft("transcription",t,e))}async function Cd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw la(s,r)}return o?!0:(eo(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 Md=new Set(["file","model","language","response_format"]);async function da(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ad,s=n.maxAudioPartBytes??Ed;try{if(t.method!=="POST")throw new te(405,`${String(t.method)} is not supported on ${Fn}`);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 $n(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(!Md.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,_]of a)if(_>1)throw new te(400,`form field "${b}" appears ${_} 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(!ua(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 R=Id(S);if(R===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 Td(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",S.length,S.length),!await Cd(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 Pd(n.clients,d,k,p,n.turn?ye(n.turn):void 0,n.turn,r);Od(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw la(b,r)}}catch(i){if(i instanceof ie){eo(e,new te(413,i.message));return}if(i instanceof te){eo(e,i);return}throw i}}var pa="/v1/usage/requests",ca=1e4,$d=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,je=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},bt=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var fa=1024*1024;function to(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new je(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new je(`"${e}" must be an array of uuid strings`);if(n.length>ca)throw new je(`"${e}" carries ${n.length} ids; at most ${ca} 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"||!$d.test(s))throw new je(`"${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 ma(t){return to(t,"inference_ids")}function Bn(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 bt(`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 bt(`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 Gn=require("@urun-sh/core");var no="/partners/huggingface/v1/billing/requests";function Ld(t){return to(t,"requestIds")}function Nd(t){return t>=200&&t<=399}function Ud(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Nd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ga(t,e){let n=Ld(t),r=await e(n);return Bn(r,n),Ud(r)}var Dd={"/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 Fd(t){return Dd[t]??null}var _a=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Bd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function qd(t){return t==="surface"}function jd(t){let e=t?.ledgerFailureReason;return _a.includes(e)?e:"unknown"}var Hd=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ha=["priced","unpriced"],Gd={written:ha,already_written:ha,skipped:Hd,failed:_a},lg=Object.entries(Gd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Jd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Vd(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 Wd=256,ya=4096,Qt=12e4,Kd=250,zd=8e3,Zt=[],wa=new Set,en=0,Xt=!1;var Yd=new Set;function Xd(){return en===0&&Zt.length===0}function Qd(){if(Xd()){Xt=!1;for(let t of[...Yd])t()}}function va(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
38
+ `}function Zd(t){Re(process.stdout,t)}function ba(t,e){try{t(e)}catch{}}function Sa(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Zd,o=Fd(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ba(r,va("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:Vd(e),completed_at:e.ts,billable_outcome:Jd(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(Zt.length>=ya){i("queue_full",`${Zt.length} ledger writes are already waiting (capacity ${ya}, ${en} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Zt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),en<Wd&&(en+=1,ec())}async function ec(){try{for(;;){let t=tc();if(t===void 0)return;wa.add(t);try{await nc(t)}finally{wa.delete(t)}}}finally{en-=1,Qd()}}function tc(){let t=Date.now();for(;;){let e=Zt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Qt)return e;St(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 ${Qt}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 nc(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);St(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=Bd(o);if(s!==null){St(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=jd(o),u=Date.now()-t.queuedAt;if(Xt){St(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(qd(i)&&u<Qt){if(await oc(rc(t.attempts)),Xt||Date.now()-t.queuedAt>=Qt){let a=Date.now()-t.queuedAt;St(t,{outcome:"failed",reason:Xt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Xt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${Qt}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}St(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 rc(t){return Math.min(zd,Kd*2**Math.max(0,t-1))}function oc(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function St(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ba(t.report,va(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function so(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function sc(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 io(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Pe(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 kt(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 ic=64*1024*1024,tn=class extends Error{};async function ka(t,e=ic){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new tn(`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 Ea(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 qn(t){let e=Ea(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function xa(t){let e=qn(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:ac(t)},completion_tokens_details:{reasoning_tokens:0}}}function ac(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 uc(t,e){let n=Ea(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function lc(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 dc(t,e){let n=lc(e);n&&(t.timing=n),t.outputSeconds=$e(e)}function nt(t,e){uc(t,e),dc(t,e)}async function Jn(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 Aa(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 cc(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 jn=class extends Error{};function pc(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 jn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function fc(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:pc(n.role,n.content)})}return e}function ro(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 mc(t,e,n,r,o,s,i){let u=Ft(s.id),a=t.stream===!0;if(s.model=le(t),s.stream=a,await Jn(s,e,typeof t.model=="string"?t.model:void 0),a){let b;try{b=await qt({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(_){if(_ instanceof J){kt(r,"openai",_);return}if(_ instanceof we){Y(r,_.status,_.message);return}if(_ instanceof be||_ instanceof pe){r.setHeader("retry-after","2"),Y(r,503,_.message,"capacity_error");return}throw _}so(r);for await(let _ of b.events){if(_.type==="error"){s.streamError=!0;let f=_.error,y=Pe(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(_)}`),r.write(`event: error
39
39
  data: ${JSON.stringify({error:{message:h,type:f?.type??"upstream_error",code:f?.code??null}})}
40
40
 
41
41
  `),r.end();return}_.type==="response.completed"&&nt(s,_.response),r.write(`event: ${String(_.type??"message")}
@@ -43,7 +43,7 @@ data: ${JSON.stringify(_)}
43
43
 
44
44
  `)}r.write(`data: [DONE]
45
45
 
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){St(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"){oo(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 R=ct(g,S),k=Qe(p,lt(S).length,R);if(k){Y(r,502,Xe(c,k),"upstream_error");return}d&&n.remember(u,l,Sr(S,R),d),ae(r,200,{...S,id:u})}async function cc(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=Si(s,t)}catch(w){if(w instanceof de){Y(n,w.status,w.message);return}throw w}let l=String(t.model??"urun"),d=Us(o.id),c;try{c=lc(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:ac(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){St(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?tc(n):ro(n);let w=[],x=new Be,I="",$=a?new yt(a,j=>{n.write(`data: ${JSON.stringify(tt(d,l,{content:j},null))}
46
+ `),r.end();return}let l;try{l=pt(n,t)}catch(b){if(b instanceof we){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=le(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await xr(e,t,l,!1,ye(s))}catch(b){if(b instanceof J){kt(r,"openai",b);return}if(b instanceof we){Y(r,b.status,b.message);return}if(b instanceof be||b instanceof pe){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"){io(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 R=ct(g,S),k=Qe(p,lt(S).length,R);if(k){Y(r,502,Xe(c,k),"upstream_error");return}d&&n.remember(u,l,kr(S,R),d),ae(r,200,{...S,id:u})}async function gc(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=xi(s,t)}catch(w){if(w instanceof ce){Y(n,w.status,w.message);return}throw w}let l=String(t.model??"urun"),d=Fs(o.id),c;try{c=fc(u)}catch(w){if(w instanceof jn){Y(n,400,w.message);return}throw w}let p=le(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Jn(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:cc(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}:{}},ye(o))}catch(w){if(w instanceof J){kt(n,"openai",w);return}if(w instanceof be||w instanceof pe){n.setHeader("retry-after","2"),Y(n,503,w.message,"capacity_error");return}throw w}if(t.stream===!0){a?sc(n):so(n);let w=[],x=new Be,I="",$=a?new yt(a,j=>{n.write(`data: ${JSON.stringify(tt(d,l,{content:j},null))}
47
47
 
48
48
  `)}):null,F=j=>{$?.flush(),n.write(j),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
 
@@ -57,36 +57,36 @@ data: ${JSON.stringify(_)}
57
57
 
58
58
  `)}else if(C.type==="error"){o.streamError=!0;let M=C.error??{},U=Pe(M),z=U??xe(o.id);U===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(C)}`),F(`data: ${JSON.stringify({error:{message:z,type:M.type??"upstream_error",code:M.code??null}})}
59
59
 
60
- `);return}}let j=to(Oe(w)),N=Qe(m,x.size+j.length,I);if(N){o.streamError=!0,F(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(p,N)}})}
60
+ `);return}}let j=ro(Oe(w)),N=Qe(m,x.size+j.length,I);if(N){o.streamError=!0,F(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(p,N)}})}
61
61
 
62
62
  `);return}$?.flush(),x.size===0&&j.length>0&&n.write(`data: ${JSON.stringify(tt(d,l,{tool_calls:j},null))}
63
63
 
64
64
  `);let B=x.size>0||j.length>0;n.write(`data: ${JSON.stringify(tt(d,l,{},B?"tool_calls":"stop"))}
65
65
 
66
- `);let W=Bn(Oe(w));nt(o,Oe(w)),W&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:ba(Oe(w))})}
66
+ `);let W=qn(Oe(w));nt(o,Oe(w)),W&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:xa(Oe(w))})}
67
67
 
68
68
  `),n.write(`data: [DONE]
69
69
 
70
- `),n.end();return}finally{$?.flush(),$?.dispose()}}let S="",R="",k=[],b=new Be;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"&&(R+=w.delta);let x=dt(w);if(x&&b.add(x),w.type==="error"){oo(n,w,{inferenceId:o.id,operatorError:i});return}}let _=Oe(k);nt(o,_);let f=to(_),y=f.length>0?f:to({output:b.items()}),h=Qe(m,y.length,S);if(h){Y(n,502,Xe(p,h),"upstream_error");return}let v=y.map(({index:w,...x})=>x),E={role:"assistant",content:S||null},A=R||xa(_);A&&(E.reasoning_content=A),v.length>0&&(E.tool_calls=v),ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:E,finish_reason:v.length>0?"tool_calls":"stop"}],usage:ba(_)})}var Ra="sense-latest";async function pc(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:Ra,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 Ea(t,i,u,e,n,r,o,s);l!==null&&ae(n,200,l.answer)}async function Ea(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 St(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 oo(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)),St(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=Oe(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),R;try{R=JSON.parse(S)}catch{return Y(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(R===null||typeof R!="object"||Array.isArray(R))return Y(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof R=="object"&&R!==null&&!Array.isArray(R)&&"timing"in R){let k=R.timing;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"question_fwd_ms"in k&&"head_ms"in k){let b=_=>typeof _=="number"&&Number.isFinite(_)&&_>=0?Math.round(_):null;a.question_fwd_ms=b(k.question_fwd_ms),a.head_ms=b(k.head_ms)}}return{answer:R,completed:g}}async function fc(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:Ra,u=ue({model:i});o.model=u,o.stream=!1;let a;try{a=Ai(t,i)}catch(p){if(p instanceof D){Y(n,400,p.message);return}throw p}let l=await Ea(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=Oi(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 mc(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var en=class extends Error{};function jn(t){return new en(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function gc(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 hc(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 en(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function yc(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 wc(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:yc(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw jn(u)}}return s(),r}function no(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 _c(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=Ds(o.id),l=[],d;try{t.system&&l.push({role:"system",content:mc(t.system)});for(let E of i)l.push(...wc(E));d=hc(t.tool_choice)}catch(E){if(E instanceof en){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:gc(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){St(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}
70
+ `),n.end();return}finally{$?.flush(),$?.dispose()}}let S="",R="",k=[],b=new Be;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"&&(R+=w.delta);let x=dt(w);if(x&&b.add(x),w.type==="error"){io(n,w,{inferenceId:o.id,operatorError:i});return}}let _=Oe(k);nt(o,_);let f=ro(_),y=f.length>0?f:ro({output:b.items()}),h=Qe(m,y.length,S);if(h){Y(n,502,Xe(p,h),"upstream_error");return}let v=y.map(({index:w,...x})=>x),E={role:"assistant",content:S||null},A=R||Aa(_);A&&(E.reasoning_content=A),v.length>0&&(E.tool_calls=v),ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:E,finish_reason:v.length>0?"tool_calls":"stop"}],usage:xa(_)})}var Ia="sense-latest";async function hc(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:Ia,u=le({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 Ta(t,i,u,e,n,r,o,s);l!==null&&ae(n,200,l.answer)}async function Ta(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 Jn(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},ye(i))}catch(k){if(k instanceof J)return kt(o,"openai",k),null;if(k instanceof be||k instanceof pe)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 io(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)),kt(o,"openai",k),null;if(k instanceof be||k instanceof pe)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=Oe(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),R;try{R=JSON.parse(S)}catch{return Y(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(R===null||typeof R!="object"||Array.isArray(R))return Y(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof R=="object"&&R!==null&&!Array.isArray(R)&&"timing"in R){let k=R.timing;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"question_fwd_ms"in k&&"head_ms"in k){let b=_=>typeof _=="number"&&Number.isFinite(_)&&_>=0?Math.round(_):null;a.question_fwd_ms=b(k.question_fwd_ms),a.head_ms=b(k.head_ms)}}return{answer:R,completed:g}}async function yc(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:Ia,u=le({model:i});o.model=u,o.stream=!1;let a;try{a=Ti(t,i)}catch(p){if(p instanceof D){Y(n,400,p.message);return}throw p}let l=await Ta(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=Ci(a.specs,l.answer)}catch(p){if(p instanceof ue){Y(n,502,p.message,"upstream_error");return}throw p}let c;try{c=Mi(l.completed.usage)}catch(p){if(p instanceof ue){Y(n,502,p.message,"upstream_error");return}throw p}ae(n,200,{model:i,answers:d,...c===null?{}:{usage:c}})}function wc(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var nn=class extends Error{};function Hn(t){return new nn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function _c(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 vc(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 nn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function bc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Hn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Hn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Sc(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 Hn(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:bc(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw Hn(u)}}return s(),r}function oo(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 kc(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=Bs(o.id),l=[],d;try{t.system&&l.push({role:"system",content:wc(t.system)});for(let E of i)l.push(...Sc(E));d=vc(t.tool_choice)}catch(E){if(E instanceof nn){Ee(n,400,"invalid_request_error",E.message);return}throw E}let c=le(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Jn(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:_c(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ye(o))}catch(E){if(E instanceof J){kt(n,"anthropic",E);return}if(E instanceof be||E instanceof pe){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
71
  data: ${JSON.stringify({type:E,...A})}
72
72
 
73
- `)};if(t.stream===!0){let E=r.track(m,c,o);ro(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,w="",x=0,I="none",$=()=>I,F=-1,j=-1,N=new Be,B=[],W=()=>{I!=="none"&&(I="none",g("content_block_stop",{index:F}))},C=(Q,ne)=>{W(),I=Q,F=x++,g("content_block_start",{index:F,content_block:ne})};for await(let Q of E){if(n.destroyed)break;B.push(Q);let ne=dt(Q);if(Q.type==="response.reasoning_text.delta"&&typeof Q.delta=="string")$()!=="thinking"&&C("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:F,delta:{type:"thinking_delta",thinking:Q.delta}});else if(Q.type==="response.output_text.delta"&&typeof Q.delta=="string")$()!=="text"&&C("text",{type:"text",text:""}),A+=1,w+=Q.delta,g("content_block_delta",{index:F,delta:{type:"text_delta",text:Q.delta}});else if(ne){let{call:ve}=N.add(ne);($()!=="tool"||ne.tool_index!==j)&&(j=ne.tool_index,C("tool",{type:"tool_use",id:ve.id??`call_${ne.tool_index}`,name:ve.name??"",input:{}})),ne.delta&&g("content_block_delta",{index:F,delta:{type:"input_json_delta",partial_json:ne.delta}})}else if(Q.type==="error"){o.streamError=!0;let ve=Q.error,He=Pe(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=Oe(B),M=lt(X),U=Qe(p,N.size+M.length,w);if(U){o.streamError=!0,g("error",{error:{type:"api_error",message:Xe(c,U)}}),n.end();return}W();let z=[];if(N.size===0)try{z=no(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&&(C("text",{type:"text",text:""}),W()),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 Ie=N.size>0||z.length>0,rt=Bn(X);nt(o,X),g("message_delta",{delta:{stop_reason:Ie?"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 S="",R="",k=[],b=new Be;for await(let E of r.track(m,c,o)){k.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(S+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(R+=E.delta);let A=dt(E);if(A&&b.add(A),E.type==="error"){let w=E.error,x=w?.type==="invalid_request_error",I=Pe(w);I===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",I??xe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let _=Oe(k);nt(o,_);let f;try{f=no(_),f.length===0&&b.size>0&&(f=no({output:b.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 y=Qe(p,f.length,S);if(y){Ee(n,502,"api_error",Xe(c,y));return}let h=[],v=R||xa(_);v&&h.push({type:"thinking",thinking:v}),(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(_)??{input_tokens:0,output_tokens:0}})}function vc(t){Re(process.stdout,t)}function bc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??vc,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,y,h,v)=>m?Ee(c,_,h,f):Y(c,_,f,y,v),S=br(p.pathname),R=p.pathname.startsWith("/partners/"),k=S||R?{id:Ut(),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(Ls,k.id),c.once("close",()=>{let _=Fs({turn:k,method:d.method??"",path:p.pathname,res:c});i(Bs(_)),a?.(_),_a({record:_,ledger:t.ledger??null,req:d})}));let b=()=>Ns(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 _=p.pathname===la?"canonical":p.pathname===eo?"huggingface":null;if(_){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){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=v.authorize(d),A;try{A=await va(d,da)}catch(I){if(I instanceof Zt){g(413,I.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=I=>v.lookup(E,I),x;try{if(_==="canonical"){let I=ca(A),$=await w(I);Fn($,I),x={requests:$}}else x=await pa(A,w)}catch(I){if(I instanceof je){g(I.status,I.message,"invalid_request_error","invalid_request_error");return}throw I}ae(c,200,x);return}if(d.method==="GET"&&p.pathname===Ot){let v=await s(d);if(k&&(k.org=v.tenant??null),!v.openRouterModels){g(501,`GET ${Ot} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ae(c,200,await v.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${eo} and GET ${Ot}`,"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:Ot}),c.end();return}ae(c,200,await f.listModels());return}if(d.method==="GET"&&p.pathname===Mi){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(Ci(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 v={clients:f,imageModels:f.supportsImages,stats:l,turn:b(),operatorLog:u};p.pathname===$n?await Hi(d,c,v):await ji(d,c,v);return}if(d.method==="GET"&&p.pathname===oa){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(ra(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 v={clients:f,transcriptionModels:f.supportsTranscription,stats:l,turn:b(),operatorLog:u};await aa(d,c,v);return}if(Qi(p.pathname)){if(!f.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Kt}`,"not_implemented","not_implemented_error");return}let v={clients:f,speechModels:f.supportsSpeech,stats:l,turn:b(),operatorLog:u};await na(d,c,v);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 va(d)}catch(v){if(v instanceof Zt){g(413,v.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 dc(y,f,Ft(f),c,l,b(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",h,h),await cc(y,f,c,l,b(),d.headers[Wr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",h,h),await pc(y,f,c,l,b(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",h,h),await fc(y,f,c,l,b(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",h,h),await _c(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(_=>{let f=String(_ instanceof Error?_.message:_);if(!c.headersSent){let v=o?.(_)??null;if(v){v.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),g(v.status,f,v.openaiType,v.anthropicType,v.code);return}if(_ instanceof Hn.SessionAllocationError){let A=Sn(_.code);if(A){let w=_.retryAfterSeconds??(A.status===429?30:void 0);w!==void 0&&c.setHeader("Retry-After",String(w)),g(A.status,qt(A,_.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(_ instanceof Hn.SessionFailedError){let A=kn(_);if(A){let w=A.status===429?30:void 0;w!==void 0&&c.setHeader("Retry-After",String(w)),g(A.status,qt(A,_.status.sessionId?`session ${_.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(_ instanceof vt){g(502,f,"upstream_error","api_error");return}if(_ instanceof Se){_.retryable&&c.setHeader("Retry-After","1");let A=fe(_,{inferenceId:k?.id??null});A.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${_ instanceof Error?`${_.name}: ${_.message}`:we(_)}`),g(502,A.message,"upstream_error","api_error",_.code);return}if(_ instanceof Fe){c.setHeader("Retry-After",String(_.retryAfterSeconds)),g(_.status,f,_.status===429?"capacity_error":"upstream_error",_.status===429?"rate_limit_error":"overloaded_error",_.code);return}let E=fe(_,{inferenceId:k?.id??null});E.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${_ instanceof Error?`${_.name}: ${_.message}`:we(_)}`),g(500,E.message,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0);let y=_ instanceof Se?_.code:null,h=fe(_,{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: ${_ instanceof Error?`${_.name}: ${_.message}`:we(_)}`),c.destroyed||(m?c.write(`event: error
73
+ `)};if(t.stream===!0){let E=r.track(m,c,o);so(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,w="",x=0,I="none",$=()=>I,F=-1,j=-1,N=new Be,B=[],W=()=>{I!=="none"&&(I="none",g("content_block_stop",{index:F}))},C=(Q,ne)=>{W(),I=Q,F=x++,g("content_block_start",{index:F,content_block:ne})};for await(let Q of E){if(n.destroyed)break;B.push(Q);let ne=dt(Q);if(Q.type==="response.reasoning_text.delta"&&typeof Q.delta=="string")$()!=="thinking"&&C("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:F,delta:{type:"thinking_delta",thinking:Q.delta}});else if(Q.type==="response.output_text.delta"&&typeof Q.delta=="string")$()!=="text"&&C("text",{type:"text",text:""}),A+=1,w+=Q.delta,g("content_block_delta",{index:F,delta:{type:"text_delta",text:Q.delta}});else if(ne){let{call:ve}=N.add(ne);($()!=="tool"||ne.tool_index!==j)&&(j=ne.tool_index,C("tool",{type:"tool_use",id:ve.id??`call_${ne.tool_index}`,name:ve.name??"",input:{}})),ne.delta&&g("content_block_delta",{index:F,delta:{type:"input_json_delta",partial_json:ne.delta}})}else if(Q.type==="error"){o.streamError=!0;let ve=Q.error,He=Pe(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=Oe(B),M=lt(X),U=Qe(p,N.size+M.length,w);if(U){o.streamError=!0,g("error",{error:{type:"api_error",message:Xe(c,U)}}),n.end();return}W();let z=[];if(N.size===0)try{z=oo(X)}catch(Q){o.streamError=!0;let ne=me(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&&(C("text",{type:"text",text:""}),W()),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 Ie=N.size>0||z.length>0,rt=qn(X);nt(o,X),g("message_delta",{delta:{stop_reason:Ie?"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 S="",R="",k=[],b=new Be;for await(let E of r.track(m,c,o)){k.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(S+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(R+=E.delta);let A=dt(E);if(A&&b.add(A),E.type==="error"){let w=E.error,x=w?.type==="invalid_request_error",I=Pe(w);I===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",I??xe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let _=Oe(k);nt(o,_);let f;try{f=oo(_),f.length===0&&b.size>0&&(f=oo({output:b.items()}))}catch(E){let A=me(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 y=Qe(p,f.length,S);if(y){Ee(n,502,"api_error",Xe(c,y));return}let h=[],v=R||Aa(_);v&&h.push({type:"thinking",thinking:v}),(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:qn(_)??{input_tokens:0,output_tokens:0}})}function xc(t){Re(process.stdout,t)}function Rc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??xc,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,y,h,v)=>m?Ee(c,_,h,f):Y(c,_,f,y,v),S=Sr(p.pathname),R=p.pathname.startsWith("/partners/"),k=S||R?{id:Dt(),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(Us,k.id),c.once("close",()=>{let _=qs({turn:k,method:d.method??"",path:p.pathname,res:c});i(js(_)),a?.(_),Sa({record:_,ledger:t.ledger??null,req:d})}));let b=()=>Ds(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 _=p.pathname===pa?"canonical":p.pathname===no?"huggingface":null;if(_){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){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=v.authorize(d),A;try{A=await ka(d,fa)}catch(I){if(I instanceof tn){g(413,I.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=I=>v.lookup(E,I),x;try{if(_==="canonical"){let I=ma(A),$=await w(I);Bn($,I),x={requests:$}}else x=await ga(A,w)}catch(I){if(I instanceof je){g(I.status,I.message,"invalid_request_error","invalid_request_error");return}throw I}ae(c,200,x);return}if(d.method==="GET"&&p.pathname===Pt){let v=await s(d);if(k&&(k.org=v.tenant??null),!v.openRouterModels){g(501,`GET ${Pt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ae(c,200,await v.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${no} and GET ${Pt}`,"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:Pt}),c.end();return}ae(c,200,await f.listModels());return}if(d.method==="GET"&&p.pathname===Ni){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(Li(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 v={clients:f,imageModels:f.supportsImages,stats:l,turn:b(),operatorLog:u};p.pathname===Ln?await Vi(d,c,v):await Ji(d,c,v);return}if(d.method==="GET"&&p.pathname===aa){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(ia(p.pathname)){if(!f.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Fn}`,"not_implemented","not_implemented_error");return}let v={clients:f,transcriptionModels:f.supportsTranscription,stats:l,turn:b(),operatorLog:u};await da(d,c,v);return}if(ta(p.pathname)){if(!f.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Yt}`,"not_implemented","not_implemented_error");return}let v={clients:f,speechModels:f.supportsSpeech,stats:l,turn:b(),operatorLog:u};await sa(d,c,v);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 ka(d)}catch(v){if(v instanceof tn){g(413,v.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 mc(y,f,Bt(f),c,l,b(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",h,h),await gc(y,f,c,l,b(),d.headers[zr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",h,h),await hc(y,f,c,l,b(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",h,h),await yc(y,f,c,l,b(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",h,h),await kc(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(_=>{let f=String(_ instanceof Error?_.message:_);if(!c.headersSent){let v=o?.(_)??null;if(v){v.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),g(v.status,f,v.openaiType,v.anthropicType,v.code);return}if(_ instanceof Gn.SessionAllocationError){let A=xn(_.code);if(A){let w=_.retryAfterSeconds??(A.status===429?30:void 0);w!==void 0&&c.setHeader("Retry-After",String(w)),g(A.status,jt(A,_.code??void 0),A.openaiType,A.anthropicType,A.code);return}}if(_ instanceof Gn.SessionFailedError){let A=Rn(_);if(A){let w=A.status===429?30:void 0;w!==void 0&&c.setHeader("Retry-After",String(w)),g(A.status,jt(A,_.status.sessionId?`session ${_.status.sessionId}`:void 0),A.openaiType,A.anthropicType,A.code);return}}if(_ instanceof bt){g(502,f,"upstream_error","api_error");return}if(_ instanceof Se){_.retryable&&c.setHeader("Retry-After","1");let A=me(_,{inferenceId:k?.id??null});A.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${_ instanceof Error?`${_.name}: ${_.message}`:_e(_)}`),g(502,A.message,"upstream_error","api_error",_.code);return}if(_ instanceof Fe){c.setHeader("Retry-After",String(_.retryAfterSeconds)),g(_.status,f,_.status===429?"capacity_error":"upstream_error",_.status===429?"rate_limit_error":"overloaded_error",_.code);return}let E=me(_,{inferenceId:k?.id??null});E.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${_ instanceof Error?`${_.name}: ${_.message}`:_e(_)}`),g(500,E.message,"proxy_error","api_error","proxy_error");return}k&&(k.streamError=!0);let y=_ instanceof Se?_.code:null,h=me(_,{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: ${_ instanceof Error?`${_.name}: ${_.message}`:_e(_)}`),c.destroyed||(m?c.write(`event: error
74
74
  data: ${JSON.stringify({type:"error",error:{type:"api_error",message:h.message}})}
75
75
 
76
76
  `):c.write(`data: ${JSON.stringify({error:{message:h.message,type:"upstream_error",code:y}})}
77
77
 
78
- `)),c.end()})}}function Aa(t){let{clients:e,apiKey:n}=t,r=(0,Sa.createServer)(bc(t)),o=Vs(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=Jr(r,{resolver:Ei(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(u=>(o.close(),s(),i(u))),Ms(r,{clients:e,apiKey:n}),r}var Jn=require("@urun-sh/core/internal");var Sc={ensureWebRTC:Jn.ensureNodeWebRTC,webrtcUnavailableReason:Jn.nodeWebRTCUnavailableReason,audioBackend:on};async function Ia(t=Sc){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 xc(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?xn(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 Rc(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:xc(H.default.env,r=>H.default.stderr.write(r)),decisionPool:is(H.default.env,H.default.env.HOSTNAME)??void 0},n=ds(e);return{router:n,decision:e.decisionPool?cs(e,n):null}}async function Ta(t,e,n){let r=(0,so.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 Oa(){return oi(H.default.env,L,Ae.existsSync)}function Ca(t){for(let[e,n]of Object.entries(Tr(t)))H.default.stdout.write(`export ${e}=${n}
81
- `)}async function Pa(t,e){let n=mt(H.default.env),r=e?Pr(n):void 0,{router:o,decision:s}=Rc(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)(io.default.dirname(i),{recursive:!0})}(0,Ae.appendFileSync)(i,d)},a=Aa({clients:ps(o,void 0,void 0,s??void 0,as(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(mi(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
- `),Ca(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 Ec(){let t=H.default.argv.slice(2),e=ii(t),n=t.shift()??"proxy";if(n==="env")return Ca(ai(e??Or(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await Ia();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
78
+ `)),c.end()})}}function Oa(t){let{clients:e,apiKey:n}=t,r=(0,Ra.createServer)(Rc(t)),o=Ks(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=Wr(r,{resolver:Ii(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(u=>(o.close(),s(),i(u))),Ls(r,{clients:e,apiKey:n}),r}var Vn=require("@urun-sh/core/internal");var Ec={ensureWebRTC:Vn.ensureNodeWebRTC,webrtcUnavailableReason:Vn.nodeWebRTCUnavailableReason,audioBackend:an};async function Pa(t=Ec){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 Ic(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?En(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 Tc(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:Ic(H.default.env,r=>H.default.stderr.write(r)),decisionPool:us(H.default.env,H.default.env.HOSTNAME)??void 0},n=ps(e);return{router:n,decision:e.decisionPool?fs(e,n):null}}async function Ca(t,e,n){let r=(0,ao.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 Ma(){return ii(H.default.env,L,Ae.existsSync)}function La(t){for(let[e,n]of Object.entries(Or(t)))H.default.stdout.write(`export ${e}=${n}
81
+ `)}async function $a(t,e){let n=mt(H.default.env),r=e?Cr(n):void 0,{router:o,decision:s}=Tc(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=$r(c.port),(0,Ae.mkdirSync)(uo.default.dirname(i),{recursive:!0})}(0,Ae.appendFileSync)(i,d)},a=Oa({clients:ms(o,void 0,void 0,s??void 0,ls(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(hi(t,await Mr(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
+ `),La(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 Oc(){let t=H.default.argv.slice(2),e=ui(t),n=t.shift()??"proxy";if(n==="env")return La(li(e??Pr(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await Pa();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
84
  `),0):(H.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
85
- `),1)}if(n==="proxy"){let o=e??Or(t),s=await Pa(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(Rn).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let b=mt(H.default.env);return Ta("pi",["-e",Oa(),...ni(b.appId,t)],H.default.env)}if(r==="omp"){let b=mt(H.default.env);return Ta("omp",["-e",Oa(),...ri(b.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 b=Rn[r];if(!b)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(Rn).join(" | ")} \u2014 or \`-- <cmd>\``);o=b.bin,s=[...b.args??[],...t],i=b.env}let u=await li(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})
85
+ `),1)}if(n==="proxy"){let o=e??Pr(t),s=await $a(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(An).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let b=mt(H.default.env);return Ca("pi",["-e",Ma(),...oi(b.appId,t)],H.default.env)}if(r==="omp"){let b=mt(H.default.env);return Ca("omp",["-e",Ma(),...si(b.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 b=An[r];if(!b)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(An).join(" | ")} \u2014 or \`-- <cmd>\``);o=b.bin,s=[...b.args??[],...t],i=b.env}let u=await ci(e,Cr(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
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 Pa(u.port,!1),l=a.port,m=Mr(l),(0,Ae.mkdirSync)(io.default.dirname(m),{recursive:!0}),p=(0,Ae.createWriteStream)(m,{flags:"a"}),c=pi({streams:H.default,note:b=>(0,Ae.appendFileSync)(m,b)}).uninstall,p.on("error",b=>{d?.(),d=null,Re(H.default.stderr,`urun compat: proxy log ${m} failed: ${String(b)} \u2014 proxy output continues on the terminal
87
+ `);let d=null,c=null,p=null,m=null;u.mode!=="reuse"&&(a=await $a(u.port,!1),l=a.port,m=$r(l),(0,Ae.mkdirSync)(uo.default.dirname(m),{recursive:!0}),p=(0,Ae.createWriteStream)(m,{flags:"a"}),c=mi({streams:H.default,note:b=>(0,Ae.appendFileSync)(m,b)}).uninstall,p.on("error",b=>{d?.(),d=null,Re(H.default.stderr,`urun compat: proxy log ${m} failed: ${String(b)} \u2014 proxy output continues on the terminal
88
88
  `)}),H.default.stdout.write(`urun openai proxy on http://127.0.0.1:${l}/v1 \u2014 proxy logs: ${m}
89
- `),d=di(p)),r==="codex"&&(s=ti(l,mt(H.default.env).appId,s));let g=(0,so.spawn)(o,s,{stdio:"inherit",env:ei(H.default.env,l,i)}),S=m!==null?fi({logPath:m,appendSync:Ae.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:b=>H.default.stderr.write(b),killChild:()=>g.kill("SIGTERM"),exit:b=>H.default.exit(b),proc:H.default}):null,R=await new Promise(b=>{g.once("exit",_=>b(_??1)),g.once("error",_=>{d?.(),d=null,Re(H.default.stderr,`failed to launch ${o}: ${String(_)}
89
+ `),d=pi(p)),r==="codex"&&(s=ri(l,mt(H.default.env).appId,s));let g=(0,ao.spawn)(o,s,{stdio:"inherit",env:ni(H.default.env,l,i)}),S=m!==null?gi({logPath:m,appendSync:Ae.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:b=>H.default.stderr.write(b),killChild:()=>g.kill("SIGTERM"),exit:b=>H.default.exit(b),proc:H.default}):null,R=await new Promise(b=>{g.once("exit",_=>b(_??1)),g.once("error",_=>{d?.(),d=null,Re(H.default.stderr,`failed to launch ${o}: ${String(_)}
90
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(H.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${R} preserved): ${String(k instanceof Error?k.message:k)}
91
- `),R}}Ec().then(t=>H.default.exit(t),t=>{H.default.stderr.write(`${String(t instanceof Error?t.message:t)}
91
+ `),R}}Oc().then(t=>H.default.exit(t),t=>{H.default.stderr.write(`${String(t instanceof Error?t.message:t)}
92
92
  `),H.default.exit(1)});