@urun-sh/openai 0.6.35 → 0.6.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ResponsesClient-_OZERUjH.d.cts → ResponsesClient-6QsC7NPJ.d.cts} +4 -1
- package/dist/{ResponsesClient-CSSrOYD8.d.ts → ResponsesClient-gfg7qUoE.d.ts} +4 -1
- package/dist/chunk-4NMMWAKD.js +1 -0
- package/dist/chunk-7HOEZLIM.js +23 -0
- package/dist/chunk-EKNKHD4H.js +2 -0
- package/dist/{chunk-ETX6IX25.js → chunk-GX243AIV.js} +1 -1
- package/dist/chunk-KKCUIOL4.js +1 -0
- package/dist/{chunk-ITPXS7D4.js → chunk-LLFROK6B.js} +1 -1
- package/dist/chunk-SYX2HJBJ.js +64 -0
- package/dist/{composite-DGytPb8F.d.cts → composite-C6Gw4HfK.d.cts} +4 -4
- package/dist/gemini-live.cjs +1 -1
- package/dist/gemini-live.d.cts +10 -1
- package/dist/gemini-live.d.ts +3 -1
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +57 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +53 -43
- package/dist/hosted/index.d.cts +2 -2
- package/dist/hosted/index.d.ts +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +4 -4
- package/dist/pi-extension/index.d.cts +1 -1
- package/dist/pi-extension/index.d.ts +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +51 -51
- package/dist/pooler/bin.cjs +20 -20
- package/dist/pooler/bin.js +24 -24
- package/dist/proxy/cli.cjs +58 -54
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.cjs +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +33 -29
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-5VMB5HKE.js +0 -17
- package/dist/chunk-EV4DZCHN.js +0 -1
- package/dist/chunk-LOPBORFM.js +0 -60
- package/dist/chunk-PAYCMH5F.js +0 -1
- package/dist/chunk-UO6N5FH7.js +0 -2
- /package/dist/{composite-D4oZXeX4.d.ts → composite-DAZrZyLN.d.ts} +0 -0
package/dist/proxy/cli.cjs
CHANGED
|
@@ -1,86 +1,90 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var ta=Object.create;var Fr=Object.defineProperty;var na=Object.getOwnPropertyDescriptor;var ra=Object.getOwnPropertyNames;var oa=Object.getPrototypeOf,sa=Object.prototype.hasOwnProperty;var ia=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ra(e))!sa.call(t,o)&&o!==n&&Fr(t,o,{get:()=>e[o],enumerable:!(r=na(e,o))||r.enumerable});return t};var Qe=(t,e,n)=>(n=t!=null?ta(oa(t)):{},ia(e||!t||!t.__esModule?Fr(n,"default",{value:t,enumerable:!0}):n,t));var aa=()=>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,C=aa();var Lr=require("child_process"),ke=require("fs"),Nr=Qe(require("path"),1),N=Qe(require("process"),1);var ne=require("@urun-sh/core");async function Br(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)})}function jr(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function qr(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 Hr(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 ua="llm-resp";async function*la(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 Hr(s);return}}}async function*$n(t,e){let n=`${ua}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*la(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var qt=class{constructor(e,n=15e3){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){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=qr(e,n,this.consumerId);return this.write(r),$n(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=jr(e,n,r,this.consumerId);return this.write(o),$n(this.session,r)})}async writeGated(e,n){try{await Br(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 Gr=0;function ca(){return Gr+=1,`req_${Date.now().toString(36)}_${Gr.toString(36)}`}var ht=class{transport;constructor(e){this.transport=new qt(e)}responses={create:async e=>{let n=ca(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var Wr="audio",Ln=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}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)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function Kr(t,e,n=1e4){let r=new Ln(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Wr).attach(o);let s=await pa(t,n);return await r.startInbound(s),r}function pa(t,e){let n=t.stream(Wr);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 Vr="rt-video-in",Jr=256e3;function zr(t){let e=t.stream(Vr),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Vr}') 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>Jr)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Jr}-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 fa=24e3,yt=480,ma=111;async function ga(){let t=await import("opusscript"),e=t.default??t;return new e(fa,1,2048)}async function Ht(){let t=await import("werift"),e=await ga();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>=yt;){let d=a.subarray(l,l+yt);l+=yt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,yt);o=o+1&65535,s=s+yt>>>0;let y=new t.RtpHeader({version:2,payloadType:ma,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),g=new t.RtpPacket(y,f);n.writeRtp(g)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{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}}}async function Yr(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 Gt=require("@urun-sh/core"),Nn="rt-video-out";var ha="h264";function ya(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function _a(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;ya(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var Xr="urun.videoOut.v2-ws";function Qr(t){let e=t.stream(Nn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Nn}') 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: "${Nn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=_a(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:ha,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 Zr={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},Ze=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function eo(t){let e=t.t;if(typeof e!="string"||!(e in Zr))throw new Ze(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Zr).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 wa(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new Ze(`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 Ze(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return eo(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Ze(`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 eo(t)}function to(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function va(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 no(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 to(e);let s=o.next();if(e!==void 0&&await va(s,e)==="aborted")throw s.catch(()=>{}),to(e);let i=await s;if(i.done)return;yield wa(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var ro=require("@urun-sh/core"),Un=2;function ba(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Sa(t){let e=t?.type;return e==="response.completed"||e==="error"}function oo(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Un;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 f=await t.createStream(a,n);for await(let y of f){if(Sa(y)&&(d=!0),ba(y)){if(i>1)continue}else c=!0;yield y}}catch(f){if(f instanceof ro.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,f)}catch{}throw f}if(i<Un&&!c){await t.evict(u,a);continue}throw f}if(d)return;if(i<Un&&!c){await t.evict(u,a);continue}return}})()}}var Qn=require("crypto");var pe=class extends Error{name="ModelPriceError"},Dn="per_million_input_tokens",Fn="per_million_output_tokens",io="model_id,variant,unit,price_usd,effective_at,expires_at",so={per_request:!0,per_minute:!0,per_output_unit:!0},ka=5e3;function xa(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new pe(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function ao(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new pe(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Ra(t,e,n){return t===null?null:ao(t,e,n)}function Ea(t,e){if(t===Dn)return"input";if(t===Fn)return"output";if(typeof t=="string"&&Object.hasOwn(so,t))return null;throw new pe(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Dn} | ${Fn}) nor a known GPU-time unit (${Object.keys(so).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 Aa(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 Bn(t,e){return`${t}\0${e}`}function Ia(t){if(!Array.isArray(t))throw new pe(`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 pe(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of io.split(","))if(!Object.hasOwn(s,l))throw new pe(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=Ea(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new pe(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new pe(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:xa(s.price_usd,o),effective_at:ao(s.effective_at,o,"effective_at"),expires_at:Ra(s.expires_at,o,"expires_at")})}return e}function uo(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=(f,y,g)=>{let w=f&&f.length>0?f:d?.[y];if(!w||w.length===0)return null;let A=Aa(w,y);return"reason"in A?A:A.rate.usd===0?y==="output"&&g!==null&&n?.has(Bn(a,g))?A.rate:{reason:`the ${y} 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`}:A.rate};for(let[f,y]of o.get(a)){let g=l.get(f),w=c(g?.input,"input",y),A=c(g?.output,"output",y);if(w!==null&&"reason"in w){i.push({model_id:a,variant:y,reason:w.reason});continue}if(A!==null&&"reason"in A){i.push({model_id:a,variant:y,reason:A.reason});continue}w===null||A===null||s.push({model_id:a,variant:y,pricing:{input:w.usd,output:A.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 _t(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 wt={prices:[],refusals:[]};async function lo(t){let e=t.fetchImpl??fetch,n=`${Dn},${Fn}`,r=await e(`${t.catalogUrl}/model_prices?select=${io}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(ka)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Ia(await r.json())}var W=class extends Error{},Oa=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Ta(t){if(typeof t!="string")return!1;let e=Oa.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 Pa(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new W(`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 W(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new W(`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 W(`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 W(`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 W(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,f)=>{if(l[c]!==void 0&&l[c]!==null&&!f)throw new W(`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",Ta(l.ready_since));for(let c of["model_id","variant"]){let f=l[c];if(f.includes(":"))throw new W(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(f)}) \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 W(`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 W(`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 W(`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 et(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function co(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 W(`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 jn(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 W(`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 po(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 W(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Pa(await r.json())}function ue(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var bt="/partners/openrouter/models",Ca={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 Ma(t){let e=t.toLowerCase();return Object.hasOwn(fo,e)?fo[e]:null}var mo={"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 $a(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(mo,o)?mo[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 go={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},ho={2:"Llama2",3:"Llama3"};function La(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(go,s))return go[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(ho,i))return ho[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Na=["context_length","max_model_len"];function Ua(t){let e=Na.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 Vt(t){let e=t.map(Ua),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Da(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function qn(t){if(t.length===0)return null;let e=t.map(Da),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Hn(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 Fa(t,e){let n=e.filter(s=>ue(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return vt(n);let r=e.filter(s=>ue(s.model_id)===t);if(r.length>0)return vt(r);let o=Hn(t,e);return o.length>0?vt(o):null}function vt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Ba(t),matches:t}:null}function Ba(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 Pe=class extends Error{name="ModelCreatedError"};function tt(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 Pe(`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 Pe(`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 Pe(`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 Pe(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function Be(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 Jt(t,e,n){let r=Fa(t,e);if(!r)return Be({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Vt(s),u=tt(s),a=_t(o.model_id,o.variant,n),l=wo(o,s),d=qn(s);return Be({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 ja=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function wo(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:[...ja],defect:o}:{published:[],defect:o}}function Gn(t){let e=t.length>0?vt(t):null;return e===null?{published:[],defect:null}:wo(e.row,e.matches)}function yo(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 _o(t){return{input:[{type:"prompt",unit:"token",cost_usd:yo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:yo(t.output)}]}}function qa(t,e,n,r){if(e.length===0)return null;let o=vt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Ca[s.task]!==!0)return null;let u=Vt(i),a=_t(s.model_id,s.variant,n),l=La(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:tt(i),quantization:Ma(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:_o(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:_o(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?et(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:$a(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=qa(l,e.filter(f=>f.model_id===l.model_id&&f.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var xo="https://api.urun.sh/v1",D=class extends Error{},j=class extends Error{},Jn="urs1.";function Kt(t,e){return Jn+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Xt(t){if(!t.startsWith(Jn))return null;try{let e=JSON.parse(Buffer.from(t.slice(Jn.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 Ro(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 bo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Ja(t);return e===null?[]:[e]}function Ha(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 fa=Object.create;var Jr=Object.defineProperty;var ma=Object.getOwnPropertyDescriptor;var ga=Object.getOwnPropertyNames;var ha=Object.getPrototypeOf,ya=Object.prototype.hasOwnProperty;var wa=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ga(e))!ya.call(t,o)&&o!==n&&Jr(t,o,{get:()=>e[o],enumerable:!(r=ma(e,o))||r.enumerable});return t};var tt=(t,e,n)=>(n=t!=null?fa(ha(t)):{},wa(e||!t||!t.__esModule?Jr(n,"default",{value:t,enumerable:!0}):n,t));var _a=()=>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,C=_a();var jr=require("child_process"),Ee=require("fs"),Br=tt(require("path"),1),U=tt(require("process"),1);var se=require("@urun-sh/core");async function Vr(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)})}function Wr(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Kr(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 zr(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 va="llm-resp";async function*ba(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 zr(s);return}}}async function*qn(t,e){let n=`${va}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*ba(e,t.stream(n).messages())}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Vt=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=Kr(e,n,this.consumerId);return this.write(r),qn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Wr(e,n,r,this.consumerId);return this.write(o),qn(this.session,r)})}async writeGated(e,n){try{await Vr(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 Yr=0;function ka(){return Yr+=1,`req_${Date.now().toString(36)}_${Yr.toString(36)}`}var vt=class{transport;constructor(e,n){this.transport=new Vt(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=ka(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var Zr="audio",jn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}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)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function eo(t,e,n=1e4){let r=new jn(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Zr).attach(o);let s=await xa(t,n);return await r.startInbound(s),r}function xa(t,e){let n=t.stream(Zr);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 Xr="rt-video-in",Qr=256e3;function to(t){let e=t.stream(Xr),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Xr}') 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>Qr)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Qr}-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 Ra=24e3,bt=480,Ea=111;async function Aa(){let t=await import("opusscript"),e=t.default??t;return new e(Ra,1,2048)}async function Wt(){let t=await import("werift"),e=await Aa();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>=bt;){let d=a.subarray(l,l+bt);l+=bt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,bt);o=o+1&65535,s=s+bt>>>0;let g=new t.RtpHeader({version:2,payloadType:Ea,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(g,p);n.writeRtp(h)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{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}}}async function no(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 Kt=require("@urun-sh/core"),Bn="rt-video-out";var Ia="h264";function Oa(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 Ta(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;Oa(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 ro="urun.videoOut.v2-ws";function oo(t){let e=t.stream(Bn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Bn}') 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: "${Bn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Ta(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:Ia,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 so={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},nt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function io(t){let e=t.t;if(typeof e!="string"||!(e in so))throw new nt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(so).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 Pa(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new nt(`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 nt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return io(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new nt(`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 io(t)}function ao(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Ca(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 uo(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 ao(e);let s=o.next();if(e!==void 0&&await Ca(s,e)==="aborted")throw s.catch(()=>{}),ao(e);let i=await s;if(i.done)return;yield Pa(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var lo=require("@urun-sh/core"),Hn=2;function $a(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Ma(t){let e=t?.type;return e==="response.completed"||e==="error"}function co(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Hn;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 g of p){if(Ma(g)&&(d=!0),$a(g)){if(i>1)continue}else c=!0;yield g}}catch(p){if(p instanceof lo.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<Hn&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<Hn&&!c){await t.evict(u,a);continue}return}})()}}var or=require("crypto");var me=class extends Error{name="ModelPriceError"},Gn="per_million_input_tokens",Jn="per_million_output_tokens",fo="model_id,variant,unit,price_usd,effective_at,expires_at",po={per_request:!0,per_minute:!0,per_output_unit:!0},La=5e3;function Na(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new me(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function mo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new me(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Ua(t,e,n){return t===null?null:mo(t,e,n)}function Da(t,e){if(t===Gn)return"input";if(t===Jn)return"output";if(typeof t=="string"&&Object.hasOwn(po,t))return null;throw new me(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Gn} | ${Jn}) nor a known GPU-time unit (${Object.keys(po).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 Fa(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 Vn(t,e){return`${t}\0${e}`}function qa(t){if(!Array.isArray(t))throw new me(`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 me(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of fo.split(","))if(!Object.hasOwn(s,l))throw new me(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=Da(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new me(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new me(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:Na(s.price_usd,o),effective_at:mo(s.effective_at,o,"effective_at"),expires_at:Ua(s.expires_at,o,"expires_at")})}return e}function go(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,g,h)=>{let w=p&&p.length>0?p:d?.[g];if(!w||w.length===0)return null;let S=Fa(w,g);return"reason"in S?S:S.rate.usd===0?g==="output"&&h!==null&&n?.has(Vn(a,h))?S.rate:{reason:`the ${g} 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`}:S.rate};for(let[p,g]of o.get(a)){let h=l.get(p),w=c(h?.input,"input",g),S=c(h?.output,"output",g);if(w!==null&&"reason"in w){i.push({model_id:a,variant:g,reason:w.reason});continue}if(S!==null&&"reason"in S){i.push({model_id:a,variant:g,reason:S.reason});continue}w===null||S===null||s.push({model_id:a,variant:g,pricing:{input:w.usd,output:S.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 St(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 kt={prices:[],refusals:[]};async function ho(t){let e=t.fetchImpl??fetch,n=`${Gn},${Jn}`,r=await e(`${t.catalogUrl}/model_prices?select=${fo}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(La)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return qa(await r.json())}var z=class extends Error{},ja=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Ba(t){if(typeof t!="string")return!1;let e=ja.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 Ha(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",Ba(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 rt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function yo(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 Wn(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 wo(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 Ha(await r.json())}function de(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Rt="/partners/openrouter/models",Ga={chat:!0,code:!0,agent:!0,vl:!0},_o={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ja(t){let e=t.toLowerCase();return Object.hasOwn(_o,e)?_o[e]:null}var vo={"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 Va(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(vo,o)?vo[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 bo={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},So={2:"Llama2",3:"Llama3"};function Wa(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(bo,s))return bo[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(So,i))return So[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Ka=["context_length","max_model_len"];function za(t){let e=Ka.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 zt(t){let e=t.map(za),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Ya(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function Kn(t){if(t.length===0)return null;let e=t.map(Ya),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function zn(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 Xa(t,e){let n=e.filter(s=>de(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return xt(n);let r=e.filter(s=>de(s.model_id)===t);if(r.length>0)return xt(r);let o=zn(t,e);return o.length>0?xt(o):null}function xt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Qa(t),matches:t}:null}function Qa(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 Me=class extends Error{name="ModelCreatedError"};function ot(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 Me(`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 Me(`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 Me(`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 Me(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function He(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 Yt(t,e,n){let r=Xa(t,e);if(!r)return He({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=zt(s),u=ot(s),a=St(o.model_id,o.variant,n),l=Ro(o,s),d=Kn(s);return He({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 Za=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Ro(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:[...Za],defect:o}:{published:[],defect:o}}function Yn(t){let e=t.length>0?xt(t):null;return e===null?{published:[],defect:null}:Ro(e.row,e.matches)}function ko(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 xo(t){return{input:[{type:"prompt",unit:"token",cost_usd:ko(t.input)}],output:[{type:"completion",unit:"token",cost_usd:ko(t.output)}]}}function eu(t,e,n,r){if(e.length===0)return null;let o=xt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Ga[s.task]!==!0)return null;let u=zt(i),a=St(s.model_id,s.variant,n),l=Wa(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:ot(i),quantization:Ja(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:xo(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:xo(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Eo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?rt(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:Va(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=eu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var To="https://api.urun.sh/v1",F=class extends Error{},B=class extends Error{},Qn="urs1.";function Qt(t,e){return Qn+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function tn(t){if(!t.startsWith(Qn))return null;try{let e=JSON.parse(Buffer.from(t.slice(Qn.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 Po(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 Ao(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ou(t);return e===null?[]:[e]}function tu(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
|
|
5
|
-
`),
|
|
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(
|
|
7
|
-
`);let a=(n?et(n):[]).map(l=>{let d=s.filter(S=>S.model_id===l.model_id&&S.variant===l.variant),c=Vt(d),f=tt(d),y=qn(d),g=_t(l.model_id,l.variant,i),w=Gn(d);return Be({id:`${l.model_id}:${l.variant}`,object:"model",created:f,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...w.published.length>0?{voices:[...w.published]}:{},...y!==null?{capabilities:{reasoning:y}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>Jt(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=Vn(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return So(`${r.modelId}:${r.variant}`,s).includes(n)}return bo(Wn(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ce(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Ce(St(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ce(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Ce(St(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Ce(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Ce(St(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):St(n,r);return Ka(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):St(n,r);return Gn(o)}async imageModelList(){let e=await this.catalogRows(),n=wt,r=[];for(let s of await this.availableIds()){let i=bo(Wn(s,e));i.length!==0&&r.push(Be({...Jt(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of et(o)){let i=Vn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=So(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Be({id:`${s.model_id}:${s.variant}`,object:"model",created:tt(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=wt,r=[];for(let s of await this.availableIds())Ce(Ao(s,e))==="stt"&&r.push(Jt(s,e,n));let o=await this.sharedBlock();if(o)for(let s of et(o)){let i=Vn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Ce(i)!=="stt")continue;let u=Be({id:`${s.model_id}:${s.variant}`,object:"model",created:tt(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 $e=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)}},kt=class extends $e{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},Kn=class extends $e{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")}},he=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Qt=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(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}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};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.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 kt;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 kt;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);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand();continue}let a=r+n-Date.now();if(a<=0)throw new Kn(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 kt}}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);(r||o)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}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)},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(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,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);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 zn=require("@urun-sh/core"),ye=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)}},en=33e4;function Io(t,e=en){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new Zt),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof j||l instanceof zn.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof Zt?(await r.return?.(void 0),new ye("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 ye("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 ye("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var Zt=class extends Error{constructor(){super("stream idle timeout")}};function Oo(t){return t instanceof ye?!1:t instanceof j?!0:t instanceof zn.SessionFailedError?t.kind==="transport-failed":!1}var za="audio";var To=new WeakMap;function Po(t,e,n){let r=t.doc(za),o=[],s=0,i=0;return{sessionId:e,appendInputAudio(u){let a=Buffer.from(u,"base64");if(a.byteLength===0||(o.push(a),s+=a.byteLength,s<4800))return;let l=Buffer.concat(o,s).toString("base64");if(o=[],s=0,n===void 0){let d=(To.get(t)??0)+1;To.set(t,d),r.set({frames:{[String(d%32)]:{s:d,pcm16:l}}})}else{let d=++i;r.set({frames:{[`${n}:${d%32}`]:{s:d,pcm16:l,c:n}}})}},onOutputAudio(){return()=>{}}}}var Ya=3,Xa="llm",Qa=new Set(["paused","error"]);function Co(t,e,n){let r=t.doc(Xa),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 f of[...a])f(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<Ya||d(new j(`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&&Qa.has(c.name)&&d(new j(`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.`))})),{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*Yn(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 eu=0,tu=4,nu=4;function $o(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):eu;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,tu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",nu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Lo(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return en;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 Xn(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 No(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=w=>({session:w,responses:new ht(w),gone:Co(w,n)});if(i.lane==="jwt"){let w=(0,ne.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Xn(w,e.appSlug,u,l))}if(i.lane==="machine"){let{machineToken:w,gatewayUrl:A}=i,S=(typeof t.subject=="function"?t.subject():t.subject)??(0,Qn.randomUUID)(),p=(0,ne.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ne.createClientToken)(w,{baseUrl:A,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:S,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Xn(p,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:f}=i,y=(typeof t.subject=="function"?t.subject():t.subject)??(0,Qn.randomUUID)(),g=(0,ne.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ne.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:y,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Xn(g,e.appSlug,u,l))}function ru(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 Uo(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 ou=new Set(["error","paused"]);function Do(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=No(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 Yt({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),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"?()=>Ro({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Yr(n):null),listPrices:n?()=>lo(n):null,shared:e.lane==="api-key"?()=>po({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return co(i)}:null,sessionKey:ru});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Me({appSlug:t.defaultApp}))),s}function Fo(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
|
|
9
|
-
`)}var au={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},qe="urun.videoOut";function Jo(t){return{framing:Xr,codec:t}}function Wo(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[qe]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var uu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},lu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",qe],jo=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function du(t){let e=Z(t);if(!e)throw new E("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new E(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=Z(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new E("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new E(`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 E("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(!jo.includes(e.activityHandling))throw new E(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${jo.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var cu=["temperature","maxOutputTokens","responseModalities"];function Ko(t){for(let[c,f]of Object.entries(uu))if(t[c]!==void 0)throw new E(f);for(let c of Object.keys(t))if(!lu.includes(c))throw new E(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new E('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=Z(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new E("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!cu.includes(c))throw new E(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new E("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new E("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 f of c){let y=String(f).toUpperCase();if(y==="AUDIO"){o=!0;continue}if(y!=="TEXT")throw new E(`responseModalities ${JSON.stringify(f)} 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:Vo(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new E("setup.tools must be an array");u=[];for(let c of t.tools){let f=Z(c);if(!f)throw new E("setup.tools entries must be objects");for(let y of Object.keys(f))if(y!=="functionDeclarations")throw new E(`unsupported tool "${y}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new E("tool.functionDeclarations must be an array");for(let y of f.functionDeclarations){let g=Z(y);if(!g||typeof g.name!="string")throw new E("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=Z(t.sessionResumption);if(!c)throw new E("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new E(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new E("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?au:du(t.realtimeInputConfig),d=!1;if(t[qe]!==void 0){if(!Z(t[qe]))throw new E(`setup["${qe}"] 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 zo(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Yo(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Xo(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new E(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new E("clientContent.turns must be an array");let n=[];for(let r of e){let o=Z(r);if(!o)throw new E("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 E(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Vo(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var on=16e3,Qo=24e3,pu=`audio/pcm;rate=${Qo}`,Zo=Buffer.alloc(960).toString("base64");function fu(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 mu(t){let e=Z(t);if(!e)throw new E("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new E(`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 E("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 E("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function gu(t){let e=Z(t);if(!e)throw new E("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new E(`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])!==on)throw new E(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${on} Hz (audio/pcm;rate=${on})`);if(typeof e.data!="string"||e.data.length===0)throw new E("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 E(`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=fu(o,on,Qo);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function es(t){if(t.mediaChunks!==void 0)throw new E('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 E("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=Z(t[o]);if(!s||Object.keys(s).length!==0)throw new E(`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 E(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new E(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:gu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:mu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new E("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new E("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 E(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new E("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=Z(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new E("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 ns(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function rs(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:pu,data:t}}]}}}}function os(t){let e=Z(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=Z(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=Z(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=Z(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new E(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Ae);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new E(`upstream function_call arguments are not valid JSON: ${c}`,Ae)}r.push({id:d.call_id,name:d.name,args:f}),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=Z(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 hu=256,Zn=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>hu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},yu="local",xt=t=>t.slice(0,120),er=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 D){this.ws.close(Ho,xt(e.message));return}if(e instanceof j){this.ws.close(an,xt(e.message));return}if(e instanceof E){this.ws.close(e.closeCode,xt(e.message));return}this.ws.close(Ae,xt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Go(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 E(`"${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}=Xo(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:Zo);return}this.transcript.push(...ts(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new E("setup may only be sent once, as the first client message");let n=Ko(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new E("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",an);if(s.model!==n.model)throw new E(`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 E("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 E(`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`,an);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(Wo(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[qe]=Jo(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 E("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new E("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ae);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(rs(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 E("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new E("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ae);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 E(`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 E("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 E("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,ss.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(zo(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(Yo(e.timeLeftMs)),this.ws.close(Ae,xt(`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 E(`upstream error: ${JSON.stringify(l)}`,Ae);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=ns(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new E("upstream produced no response.completed event",Ae);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}}},He=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function _u(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 He(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 He(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 He(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function as(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 is.WebSocketServer({noServer:!0}),o=new Zn;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===qo&&(u.on("error",()=>{}),(async()=>{let d=_u(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new He(401,"invalid local proxy api key");c={clients:e.clients,scope:yu}}r.handleUpgrade(i,u,a,f=>{new er(f,c,o)})})().catch(d=>{let c=502;(d instanceof He||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let f=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",y=d instanceof Error?d.message:String(d);u.destroyed||(u.write(`HTTP/1.1 ${c} ${f}\r
|
|
4
|
+
`),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function nu(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||de(`${r.model_id}-${r.variant}`)===e.appSlug||de(r.model_id)===e.appSlug)),n?tu(n.engine_args?.pool):null}function Xn(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 Io(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 Co="shared:",Oo="speech:";function Ne(t){return t.sharedApp?Co+t.appSlug:t.appSlug}function Zt(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 Zn(t,e){let n=e.filter(s=>de(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>de(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 ou(t){let e=t.map(ru),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var su={stt:"stt",tts:"tts"};function Le(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:su[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function $o(t,e){let n=Zn(t,e);return n.length>0?n:zn(t,e)}function Et(t,e){return $o(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 Xt=6e4,en=class{constructor(e){this.opts=e}opts;pool=new Map;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.pool.set(e,Promise.resolve(n))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??Xt):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??Xt):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??Xt):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Xt;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 me)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
|
+
`),kt}let r=go(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(Vn(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(Co)||o.startsWith(Oo)||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 F(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=Wn(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=de(s),a=n.endpoints.filter(c=>de(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:Wn(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};let o=de(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 F(`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 F(`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===de(a.model_id)||o===de(`${a.model_id}-${a.variant}`));if(u)throw new F(`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=Zt(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return nu(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ne(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ne(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Oo+Ne(n))}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.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:Zt(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:Qt(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Qt(n,this.keyOf(r))}}async sessionForHandle(e){let n=tn(e);if(!n)throw new B(`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 B(`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)throw new B(`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:kt;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?rt(n):[]).map(l=>{let d=s.filter(v=>v.model_id===l.model_id&&v.variant===l.variant),c=zt(d),p=ot(d),g=Kn(d),h=St(l.model_id,l.variant,i),w=Yn(d);return He({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...h!==null?{pricing:h}:{},...w.published.length>0?{voices:[...w.published]}:{},...g!==null?{capabilities:{reasoning:g}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>Yt(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Eo(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=Xn(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Io(`${r.modelId}:${r.variant}`,s).includes(n)}return Ao(Zn(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Le(Et(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Le(Et(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Le(Et(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):Et(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):Et(n,r);return Yn(o)}async imageModelList(){let e=await this.catalogRows(),n=kt,r=[];for(let s of await this.availableIds()){let i=Ao(Zn(s,e));i.length!==0&&r.push(He({...Yt(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of rt(o)){let i=Xn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Io(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=He({id:`${s.model_id}:${s.variant}`,object:"model",created:ot(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=kt,r=[];for(let s of await this.availableIds())Le($o(s,e))==="stt"&&r.push(Yt(s,e,n));let o=await this.sharedBlock();if(o)for(let s of rt(o)){let i=Xn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Le(i)!=="stt")continue;let u=He({id:`${s.model_id}:${s.variant}`,object:"model",created:ot(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 Ue=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)}},At=class extends Ue{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},er=class extends Ue{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")}},_e=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},nn=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(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}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};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.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 At;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 At;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);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand();continue}let a=r+n-Date.now();if(a<=0)throw new er(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 At}}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);(r||o)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}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)},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(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,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);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 tr=require("@urun-sh/core"),ve=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)}},on=33e4;function Mo(t,e=on){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new rn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof B||l instanceof tr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof rn?(await r.return?.(void 0),new ve("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 ve("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 ve("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var rn=class extends Error{constructor(){super("stream idle timeout")}};function Lo(t){return t instanceof ve?!1:t instanceof B?!0:t instanceof tr.SessionFailedError?t.kind==="transport-failed":!1}var No=require("@urun-sh/core"),au="audio";function Uo(t){let e=t.streamEndpoint(au);return{sessionId:t.id,appendInputAudio(n){let r=Buffer.from(n,"base64");r.byteLength!==0&&e.send((0,No.encodeStreamEnvelope)(new Uint8Array(r)))},onOutputAudio(){return()=>{}}}}var uu=3,lu="llm",du=new Set(["paused","error"]);function Do(t,e,n){let r=t.doc(lu),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<uu||d(new B(`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&&du.has(c.name)&&d(new B(`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.`))})),{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*nr(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 pu=0,fu=4,mu=4;function qo(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):pu;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,fu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",mu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function jo(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return on;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 rr(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 Bo(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=w=>({session:w,responses:new vt(w),gone:Do(w,n)});if(i.lane==="jwt"){let w=(0,se.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(rr(w,e.appSlug,u,l))}if(i.lane==="machine"){let{machineToken:w,gatewayUrl:S}=i,v=(typeof t.subject=="function"?t.subject():t.subject)??(0,or.randomUUID)(),f=(0,se.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,se.createClientToken)(w,{baseUrl:S,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:v,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(rr(f,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,g=(typeof t.subject=="function"?t.subject():t.subject)??(0,or.randomUUID)(),h=(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:g,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(rr(h,e.appSlug,u,l))}function gu(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 Ho(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 hu=new Set(["error","paused"]);function Go(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=Bo(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 en({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),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"?()=>Po({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>no(n):null),listPrices:n?()=>ho(n):null,shared:e.lane==="api-key"?()=>wo({apiUrl:t.apiUrl,apiKey:e.apiKey}):e.lane==="machine"&&t.catalogRows?async()=>{let i=await t.catalogRows();return yo(i)}:null,sessionKey:gu});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ne({appSlug:t.defaultApp}))),s}function Jo(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 g=new nn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let w=Bo(t,d,c,{concurrencyKey:h.concurrencyKey});return w.gone.onGone(()=>g.markSessionDead(w)),await an(w.session),u(`slot attached pool=${c} slot=${h.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,w)=>u(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${w}`),terminalOpenFailure:h=>h instanceof se.SessionFailedError&&Ho(h)});return s.set(c,{target:d,env:n}),o.set(c,g),g},l=async(d,c)=>{let p=s.get(c);if(p)try{let g=await e.poolTuningFor(d);a(d,c).retune({min:g?.min??p.env.min,max:g?.max??p.env.max,inFlightCap:g?.in_flight_cap??p.env.inFlightCap,idleGraceMs:g?.idle_grace_s!==void 0?g.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:g?.warm_wait_s!==void 0?g.warm_wait_s*1e3:void 0})}catch(g){u(`pool tuning refresh failed pool=${c} reason=${g instanceof Error?g.message:String(g)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ne(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ne(c),g=a(c,p);await l(c,p);let h=await g.acquire({timeoutMs:g.requestWaitMs}),w=i.get(h.entry)??[];return w.push(h),i.set(h.entry,w),{app:p,entry:h.entry,identity:Zt(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ne(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 yu(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 an(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:yu(t.phase),signal:e})}async function Fo(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()}function sn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Vo(t,e=Wt,n,r,o=on,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let m=f.session.id;return typeof m=="string"&&m.length>0?m:null},p="lane",g=f=>{let m=tn(f);if(!s||!m||m.app!==p)return null;let y=s.entryFor(m.key);if(!y)throw new B(`the lane behind this handle (${m.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:m.key,entry:y}},h=async f=>g(f)?.entry??(await t.sessionForHandle(f)).entry,w=f=>{let m=i.get(f);if(!m){let y={waiting:0,gone:new AbortController};d.set(f,y),m=(async()=>{if(await an(f.session,y.gone.signal),y.gone.signal.aborted)throw sn(y.gone.signal);d.get(f)===y&&d.delete(f);let _=await eo(f.session,await e());return Object.assign(_,{sessionId:f.session.id})})(),i.set(f,m),m.catch(()=>{i.get(f)===m&&i.delete(f)}),m.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return m},S=f=>{let m=l.get(f);return m||(m=(async()=>{let y=await w(f);return{appendInputAudio:_=>y.appendInputAudio(_),onOutputAudio:_=>y.onOutputAudio(_),sessionId:c(f)}})(),l.set(f,m),m.catch(()=>{l.get(f)===m&&l.delete(f)})),m},v=async(f,m,y)=>{if(y?.aborted){let b=d.get(f);throw(i.get(f)===void 0||b!==void 0&&b.waiting===0)&&await Fo(f.session),sn(y)}let _=m(f),x=d.get(f);return x!==void 0&&x.waiting++,y===void 0?_:new Promise((b,E)=>{let O=()=>{x!==void 0&&--x.waiting===0&&d.get(f)===x&&(x.gone.abort(),d.delete(f),i.delete(f),l.delete(f),Fo(f.session).catch(()=>{})),E(sn(y))};y.addEventListener("abort",O,{once:!0});let R=()=>y.removeEventListener("abort",O);_.then(I=>{R(),b(I)},I=>{R(),E(I)})})};return{createResponse:co({sessionFor:s?async f=>{let m=await t.resolveTargetFor(f);if(m.sharedApp){let y=await s.sessionFor(f,m);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,m)=>{s&&s.owns(m)?s.evict(m):r?r.evict(m):t.evict(f,m)},onAdmissionVerdict:(f,m,y)=>{Ho(y)&&(s&&s.owns(m)?s.evict(m):r?r.markSessionDead(m):t.evict(f,m),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,m)=>{try{await an(f.session);let y=Mo(nr(await f.responses.responses.create(m),f.gone),o);if(!r&&!s)return y;let _=f;return(async function*(){try{yield*y}catch(b){throw Lo(b)&&(s&&s.owns(_)?s.evict(_):r&&(b instanceof B?r.markSessionDead(_):r.evict(_))),b}finally{s&&s.owns(_)?s.release(_):r?.end(_)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,m)=>t.supportsImages(f,m),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,m)=>{let{entry:y}=await t.sessionFor(f);return await v(y,w,m)},openAudioOn:async(f,m,y)=>{let _=g(f);if(_){let b=_.entry.session;return Uo(b)}let{entry:x}=await t.sessionForHandle(f);return await v(x,S,m)},openTurnsOn:async function*(f,m){if(m?.aborted)throw sn(m);let y=await h(f);yield*uo(y.session,m)},openVideo:async f=>{let{entry:m}=await t.sessionFor(f),y=u.get(m);return y||(y=to(m.session),u.set(m,y)),y},openVideoOut:async f=>{let{entry:m}=await t.sessionFor(f),y=a.get(m);return y||(y=oo(m.session),a.set(m,y)),y},sessionHandle:async f=>{if(s){let m=await t.resolveTargetFor(f);if(m.sharedApp){let y=await s.sessionFor(f,m),_=c(y.entry);if(_===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Qt(p,_)}}return(await t.handleFor(f)).handle},releaseSessionHandle:f=>{let m=tn(f);if(!s||m?.app!==p)return;let y=s.entryFor(m.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:m,entry:y}=await t.sessionForHandle(f);await t.evict(m,y)},createResponseOn:async(f,m,y)=>{let _=await h(f);await an(_.session);let x=y!==void 0&&g(f)?new vt({..._.session,consumerId:y},{sessionTag:y}):_.responses;return nr(await x.responses.create(m),_.gone)},onSessionEnd:async(f,m)=>{let y=g(f);if(y)return y.entry.gone.onGone(E=>m({timeLeftMs:null,reason:E.message}));let{entry:_}=await t.sessionForHandle(f),x=_.session;if(typeof x.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let b=!1;return x.onPhase(E=>{if(b||!hu.has(E.name))return;b=!0;let O=x.endsAt??null;m({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:E.reason??`session ${E.name}`})})}}}var na=require("http");var cs=require("crypto"),ps=require("ws");var Ko="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",wu=1007,zo=1008,Te=1011,cn=1008,A=class extends Error{constructor(n,r=wu){super(n);this.closeCode=r}closeCode},ee=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,un=["setup","clientContent","realtimeInput","toolResponse"];function Yo(t){let e;try{e=JSON.parse(t)}catch{throw new A("client message is not valid JSON")}let n=ee(e);if(!n)throw new A("client message must be a JSON object");let r=un.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!un.includes(u));if(o.length>0)throw new A(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${un.join(", ")}`);if(r.length!==1)throw new A(`client message must contain exactly one of ${un.join(", ")} (got ${r.length})`);let s=r[0],i=ee(n[s]);if(!i)throw new A(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Xo(t,e){if(typeof t=="string")return t;let n=ee(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new A(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ee(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new A(`${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 A(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new A(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
9
|
+
`)}var _u={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Je="urun.videoOut";function Qo(t){return{framing:ro,codec:t}}function Zo(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Je]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var vu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},bu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Je],Wo=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Su(t){let e=ee(t);if(!e)throw new A("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new A(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ee(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new A("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new A(`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 A("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(!Wo.includes(e.activityHandling))throw new A(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Wo.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var ku=["temperature","maxOutputTokens","responseModalities"];function es(t){for(let[c,p]of Object.entries(vu))if(t[c]!==void 0)throw new A(p);for(let c of Object.keys(t))if(!bu.includes(c))throw new A(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new A('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ee(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new A("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!ku.includes(c))throw new A(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new A("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new A("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 g=String(p).toUpperCase();if(g==="AUDIO"){o=!0;continue}if(g!=="TEXT")throw new A(`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:Xo(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new A("setup.tools must be an array");u=[];for(let c of t.tools){let p=ee(c);if(!p)throw new A("setup.tools entries must be objects");for(let g of Object.keys(p))if(g!=="functionDeclarations")throw new A(`unsupported tool "${g}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new A("tool.functionDeclarations must be an array");for(let g of p.functionDeclarations){let h=ee(g);if(!h||typeof h.name!="string")throw new A("functionDeclarations entries require a string name");u.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ee(t.sessionResumption);if(!c)throw new A("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new A(`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 A("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?_u:Su(t.realtimeInputConfig),d=!1;if(t[Je]!==void 0){if(!ee(t[Je]))throw new A(`setup["${Je}"] 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 ts(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function ns(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 A(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new A("clientContent.turns must be an array");let n=[];for(let r of e){let o=ee(r);if(!o)throw new A("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 A(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Xo(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var ln=16e3,os=24e3,xu=`audio/pcm;rate=${os}`,ss=Buffer.alloc(960).toString("base64");function Ru(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 Eu(t){let e=ee(t);if(!e)throw new A("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new A(`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 A("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 A("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Au(t){let e=ee(t);if(!e)throw new A("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new A(`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])!==ln)throw new A(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${ln} Hz (audio/pcm;rate=${ln})`);if(typeof e.data!="string"||e.data.length===0)throw new A("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 A(`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=Ru(o,ln,os);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function is(t){if(t.mediaChunks!==void 0)throw new A('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 A("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ee(t[o]);if(!s||Object.keys(s).length!==0)throw new A(`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 A(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new A(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Au(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Eu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new A("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new A("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 A(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new A("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ee(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new A("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 us(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function ls(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:xu,data:t}}]}}}}function ds(t){let e=ee(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=ee(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=ee(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=ee(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new A(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Te);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new A(`upstream function_call arguments are not valid JSON: ${c}`,Te)}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=ee(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 Iu=256,sr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Iu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ou="local",It=t=>t.slice(0,120),ir=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 F){this.ws.close(zo,It(e.message));return}if(e instanceof B){this.ws.close(cn,It(e.message));return}if(e instanceof A){this.ws.close(e.closeCode,It(e.message));return}this.ws.close(Te,It(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Yo(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 A(`"${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:ss);return}this.transcript.push(...as(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new A("setup may only be sent once, as the first client message");let n=es(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new A("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",cn);if(s.model!==n.model)throw new A(`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 A("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 A(`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`,cn);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(Zo(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[Je]=Qo(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 A("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new A("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Te);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(ls(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 A("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new A("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Te);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 A(`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 A("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 A("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,cs.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ts(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(ns(e.timeLeftMs)),this.ws.close(Te,It(`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 A(`upstream error: ${JSON.stringify(l)}`,Te);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=us(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new A("upstream produced no response.completed event",Te);let{messages:i,assistantItems:u}=ds(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ve=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Tu(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 Ve(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new Ve(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let u;for(let a of r)u=a;if(u===void 0&&n)throw new Ve(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function fs(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new ps.WebSocketServer({noServer:!0}),o=new sr;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Ko&&(u.on("error",()=>{}),(async()=>{let d=Tu(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ve(401,"invalid local proxy api key");c={clients:e.clients,scope:Ou}}r.handleUpgrade(i,u,a,p=>{new ir(p,c,o)})})().catch(d=>{let c=502;(d instanceof Ve||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",g=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
|
-
${
|
|
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
|
|
14
|
-
`}var wu=256,vu=128;function ie(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,vu)}var Ge=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>=wu?"(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}}}},bu=256;function Su(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 Ve=class extends Error{},nt=class{conversations=new Map;thread(e,n){let r=Su(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ve(`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<=bu)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},gs=new WeakMap;function At(t){let e=gs.get(t);return e||(e=new nt,gs.set(t,e)),e}function rt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function xe(t){return t.find(e=>e.type==="response.completed")?.response??null}function ot(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 Le=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}))}},ku=["<tool_call>","<function="];function xu(t){return ku.find(e=>t.includes(e))}function Je(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 We(t,e,n){if(!(!t||e>0))return xu(n)}function st(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 Ie(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ru(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 nr(t,e){let n=Ru(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var me=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function it(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ve?new me(n.message,"previous_response_not_found",400,"previous_response_id"):new me(String(n instanceof Error?n.message:n),"invalid_input")}}function hs(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function rr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new me("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}:{},...hs(e)!==void 0?{response_format:hs(e)}:{}},o)}async function It(t){let{body:e,clients:n,store:r,stats:o}=t,s=it(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=ie(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await rr(n,e,s,!0,c?fe(c):void 0);return{responseId:i,events:Ou({events:f,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function Eu(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?Iu(o[i++],a):a),...Au(r,n)]}function Au(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 Iu(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*Ou(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=$=>$.response&&typeof $.response=="object"?{...$,response:{...$.response,id:r}}:$,f=`item_${r.slice(5)}`,y=!1,g=!1,w=0;function*A(){y||(y=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let S=[],p=($,q)=>{S.push({output_index:$,item:q})},m=!1,h=0,_="",k=0,v="";function*R(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:h,content_index:0,text:v};let $={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:h,item:$},p(h,$),v=""}let O=!1,x=0,I="",b=0,M="",B="";function*F($){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:I,output_index:x,content_index:0,text:M},yield{type:"response.content_part.done",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:M}};let q={id:I,type:"message",role:"assistant",status:$,content:[{type:"output_text",text:M}]};yield{type:"response.output_item.done",output_index:x,item:q},p(x,q),M=""}let Y=new Le,H=null,Te=-1;function*X($){if(!H)return;let q=H;H=null,yield{type:"response.function_call_arguments.done",item_id:q.fcId,output_index:q.outputIndex,arguments:q.args};let G={id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:q.args,status:$};yield{type:"response.output_item.done",output_index:q.outputIndex,item:G},p(q.outputIndex,G)}let oe=!1;for await(let $ of l.track(e,o,t.turn)){d.push($);let q=String($.type??"");if(q==="response.created"||q==="response.in_progress"){y=!0,yield c($);continue}if(q==="response.output_item.added"){g=!0,yield c($);continue}if(q==="response.reasoning_text.delta"&&!g){yield*A(),m||(m=!0,h=w++,k+=1,_=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:h,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String($.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:h,content_index:0,delta:$.delta};continue}if(q==="response.output_text.delta"&&!g){yield*A(),yield*R(),O||(O=!0,x=w++,b+=1,I=b===1?f:`${f}_${b}`,yield{type:"response.output_item.added",output_index:x,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:x,content_index:0,part:{type:"output_text",text:""}}),M+=String($.delta??""),B+=String($.delta??""),yield{type:q,item_id:I,output_index:x,content_index:0,delta:$.delta};continue}let G=g?null:ot($);if(G){if(yield*A(),yield*R(),yield*F("completed"),Y.add(G),G.tool_index!==Te){yield*X("completed"),Te=G.tool_index;let De=w++;H={fcId:`fc_${r.slice(5)}_${G.tool_index}`,outputIndex:De,callId:G.call_id,name:G.name,args:""},yield{type:"response.output_item.added",output_index:De,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(G.call_id&&(H.callId=G.call_id),G.name&&(H.name=G.name),H.args+=G.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:G.delta});continue}if(q==="response.completed"&&!g){let De=rt($.response),Xe=We(s,Y.size+De.length,B);if(Xe){oe=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Je(o,Xe)}};break}if(yield*R(),yield*F("completed"),yield*X("completed"),Y.size===0)for(let Q of De){let ge=w++,Fe=Q.id??Q.call_id??`fc_${ge}`,Mn=Q.arguments??"",Ur={id:Fe,type:"function_call",call_id:Q.call_id??Fe,name:Q.name??""};yield{type:"response.output_item.added",output_index:ge,item:{...Ur,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Fe,output_index:ge,delta:Mn},yield{type:"response.function_call_arguments.done",item_id:Fe,output_index:ge,arguments:Mn};let Dr={...Ur,arguments:Mn,status:"completed"};yield{type:"response.output_item.done",output_index:ge,item:Dr},p(ge,Dr)}let V=Eu(S,$.response);yield V.length>0?c({...$,response:{...$.response,output:V}}):c($);continue}yield c($)}if(yield*R(),yield*F("incomplete"),yield*X("incomplete"),i&&!oe){let $=xe(d);a.remember(r,n,nr($,st(d,$)),u)}}var Re=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},le=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Tu=[/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 we(t){return!Tu.some(e=>e.test(t))}function ve(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 de(t,e){if(t instanceof j)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=ys(t);return n||{message:ve(e?.inferenceId??null),redacted:!0}}function ys(t){return t instanceof Pe?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof W?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof D?{message:t.message,redacted:!1}:t instanceof Re?{message:t.message,redacted:!1}:t instanceof $e?{message:t.message,redacted:!1}:t instanceof ye?we(t.message)?{message:t.message,redacted:!1}:null:t instanceof he?{message:t.message,redacted:!1}:t instanceof le?{message:t.message,redacted:!1}:null}function at(t,e,n){let r=n??(i=>console.error(i)),o=ys(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&&we(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 Ee(t){let e=t?.message;return typeof e=="string"&&e.length>0&&we(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 Pu="/v1/responses",Cu=64*1024*1024,Mu=8*1024*1024,$u=16,_s=32,ws=3600*1e3,Lu=/^[A-Za-z0-9._-]{1,256}$/;function se(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Nu=se(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 ir(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function Uu(t){for(;t.bufferedAmount>Mu&&t.readyState===Ne.WebSocket.OPEN;){let{promise:e,resolve:n}=ir();setTimeout(n,5),await e}}var or=class extends nt{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 Ve))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)}},sr=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 or(At(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(se(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(se(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(se(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(se(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(se(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(se(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(se(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"||!Lu.test(o.stream_id)){this.sendFrame(Nu);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=_s){this.sendFrame(se(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${_s}). 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=Rt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await It({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Et(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!==Ne.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await Uu(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=Rt(),o=Et(r);try{let s=it(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 me)return se(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof D)return se(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof j){let u=de(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}`),se(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}`),se(s.status,{type:s.openaiType,message:o},n);let i=de(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}`),se(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Ee(o),u=i??ve(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)}`),se(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=$u;){let{promise:e,resolve:n}=ir();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!==Ne.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!==Ne.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function un(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
12
|
+
${g}\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 Fe=require("ws");var ms=require("crypto"),gs="Inference-Id";function Ot(){return(0,ms.randomUUID)()}function ar(t){return t==="/v1"||t.startsWith("/v1/")}function hs(t,e){if(!ar(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 Tt(t){return`resp_${t}`}function ys(t){return`chatcmpl-${t}`}function ws(t){return`msg_${t}`}function ge(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function _s(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_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 vs(t){return`${JSON.stringify(t)}
|
|
14
|
+
`}var Pu=256,Cu=128;function ae(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Cu)}var We=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>=Pu?"(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}}}},$u=256;function Mu(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 Ke=class extends Error{},st=class{conversations=new Map;thread(e,n){let r=Mu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ke(`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<=$u)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},bs=new WeakMap;function Pt(t){let e=bs.get(t);return e||(e=new st,bs.set(t,e)),e}function it(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Ae(t){return t.find(e=>e.type==="response.completed")?.response??null}function at(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 De=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}))}},Lu=["<tool_call>","<function="];function Nu(t){return Lu.find(e=>t.includes(e))}function ze(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 Ye(t,e,n){if(!(!t||e>0))return Nu(n)}function ut(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 Pe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Uu(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 ur(t,e){let n=Uu(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var he=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function lt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ke?new he(n.message,"previous_response_not_found",400,"previous_response_id"):new he(String(n instanceof Error?n.message:n),"invalid_input")}}function Ss(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function lr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new he("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}:{},...Ss(e)!==void 0?{response_format:Ss(e)}:{}},o)}async function Ct(t){let{body:e,clients:n,store:r,stats:o}=t,s=lt(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=ae(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await lr(n,e,s,!0,c?ge(c):void 0);return{responseId:i,events:ju({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function Du(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?qu(o[i++],a):a),...Fu(r,n)]}function Fu(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 qu(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*ju(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=L=>L.response&&typeof L.response=="object"?{...L,response:{...L.response,id:r}}:L,p=`item_${r.slice(5)}`,g=!1,h=!1,w=0;function*S(){g||(g=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],f=(L,H)=>{v.push({output_index:L,item:H})},m=!1,y=0,_="",x=0,b="";function*E(){if(!m)return;m=!1,yield{type:"response.reasoning_text.done",item_id:_,output_index:y,content_index:0,text:b};let L={id:_,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:b}],status:"completed"};yield{type:"response.output_item.done",output_index:y,item:L},f(y,L),b=""}let O=!1,R=0,I="",k=0,$="",j="";function*q(L){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:I,output_index:R,content_index:0,text:$},yield{type:"response.content_part.done",item_id:I,output_index:R,content_index:0,part:{type:"output_text",text:$}};let H={id:I,type:"message",role:"assistant",status:L,content:[{type:"output_text",text:$}]};yield{type:"response.output_item.done",output_index:R,item:H},f(R,H),$=""}let X=new De,G=null,$e=-1;function*Q(L){if(!G)return;let H=G;G=null,yield{type:"response.function_call_arguments.done",item_id:H.fcId,output_index:H.outputIndex,arguments:H.args};let V={id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:H.args,status:L};yield{type:"response.output_item.done",output_index:H.outputIndex,item:V},f(H.outputIndex,V)}let ie=!1;for await(let L of l.track(e,o,t.turn)){d.push(L);let H=String(L.type??"");if(H==="response.created"||H==="response.in_progress"){g=!0,yield c(L);continue}if(H==="response.output_item.added"){h=!0,yield c(L);continue}if(H==="response.reasoning_text.delta"&&!h){yield*S(),m||(m=!0,y=w++,x+=1,_=x===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${x}`,yield{type:"response.output_item.added",output_index:y,item:{id:_,type:"reasoning",summary:[],content:[],status:"in_progress"}}),b+=String(L.delta??""),yield{type:"response.reasoning_text.delta",item_id:_,output_index:y,content_index:0,delta:L.delta};continue}if(H==="response.output_text.delta"&&!h){yield*S(),yield*E(),O||(O=!0,R=w++,k+=1,I=k===1?p:`${p}_${k}`,yield{type:"response.output_item.added",output_index:R,item:{id:I,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:I,output_index:R,content_index:0,part:{type:"output_text",text:""}}),$+=String(L.delta??""),j+=String(L.delta??""),yield{type:H,item_id:I,output_index:R,content_index:0,delta:L.delta};continue}let V=h?null:at(L);if(V){if(yield*S(),yield*E(),yield*q("completed"),X.add(V),V.tool_index!==$e){yield*Q("completed"),$e=V.tool_index;let je=w++;G={fcId:`fc_${r.slice(5)}_${V.tool_index}`,outputIndex:je,callId:V.call_id,name:V.name,args:""},yield{type:"response.output_item.added",output_index:je,item:{id:G.fcId,type:"function_call",call_id:G.callId??G.fcId,name:G.name??"",arguments:"",status:"in_progress"}}}G&&(V.call_id&&(G.callId=V.call_id),V.name&&(G.name=V.name),G.args+=V.delta,yield{type:"response.function_call_arguments.delta",item_id:G.fcId,output_index:G.outputIndex,delta:V.delta});continue}if(H==="response.completed"&&!h){let je=it(L.response),et=Ye(s,X.size+je.length,j);if(et){ie=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ze(o,et)}};break}if(yield*E(),yield*q("completed"),yield*Q("completed"),X.size===0)for(let Z of je){let we=w++,Be=Z.id??Z.call_id??`fc_${we}`,Fn=Z.arguments??"",Hr={id:Be,type:"function_call",call_id:Z.call_id??Be,name:Z.name??""};yield{type:"response.output_item.added",output_index:we,item:{...Hr,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Be,output_index:we,delta:Fn},yield{type:"response.function_call_arguments.done",item_id:Be,output_index:we,arguments:Fn};let Gr={...Hr,arguments:Fn,status:"completed"};yield{type:"response.output_item.done",output_index:we,item:Gr},f(we,Gr)}let W=Du(v,L.response);yield W.length>0?c({...L,response:{...L.response,output:W}}):c(L);continue}yield c(L)}if(yield*E(),yield*q("incomplete"),yield*Q("incomplete"),i&&!ie){let L=Ae(d);a.remember(r,n,ur(L,ut(d,L)),u)}}var Ie=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ce=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Bu=[/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 Se(t){return!Bu.some(e=>e.test(t))}function ke(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 pe(t,e){if(t instanceof B)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=ks(t);return n||{message:ke(e?.inferenceId??null),redacted:!0}}function ks(t){return t instanceof Me?{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 F?{message:t.message,redacted:!1}:t instanceof Ie?{message:t.message,redacted:!1}:t instanceof Ue?{message:t.message,redacted:!1}:t instanceof ve?Se(t.message)?{message:t.message,redacted:!1}:null:t instanceof _e?{message:t.message,redacted:!1}:t instanceof ce?{message:t.message,redacted:!1}:null}function dt(t,e,n){let r=n??(i=>console.error(i)),o=ks(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${be(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Se(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${be(e)}`),`the ${t} upstream failed while serving this request`)}function Oe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Se(e)?e:null}function be(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Hu="/v1/responses",Gu=64*1024*1024,Ju=8*1024*1024,Vu=16,xs=32,Rs=3600*1e3,Wu=/^[A-Za-z0-9._-]{1,256}$/;function ue(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Ku=ue(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 pr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function zu(t){for(;t.bufferedAmount>Ju&&t.readyState===Fe.WebSocket.OPEN;){let{promise:e,resolve:n}=pr();setTimeout(n,5),await e}}var dr=class extends st{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 Ke))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)}},cr=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 dr(Pt(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(ue(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Rs/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Rs).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(ue(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(ue(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(ue(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(ue(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(ue(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(ue(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"||!Wu.test(o.stream_id)){this.sendFrame(Ku);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=xs){this.sendFrame(ue(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${xs}). 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=Ot();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Ct({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Tt(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!==Fe.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await zu(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=Ot(),o=Tt(r);try{let s=lt(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:be(e);if(e instanceof he)return ue(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof F)return ue(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof B){let u=pe(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}`),ue(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}`),ue(s.status,{type:s.openaiType,message:o},n);let i=pe(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}`),ue(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Oe(o),u=i??ke(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)}`),ue(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=Vu;){let{promise:e,resolve:n}=pr();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!==Fe.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!==Fe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function pn(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
|
|
21
|
-
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of
|
|
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
|
|
20
|
+
${o}`)}function Es(t,e){let n=new Fe.WebSocketServer({noServer:!0,maxPayload:Gu}),r=new We,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 g;try{g=new URL(d.url??"/","http://localhost")}catch{pn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),g.pathname!==Hu){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){pn(c,401,"invalid local proxy api key");return}let w;try{w=await u(d)}catch(S){let v=e.statusOf?.(S)??null;pn(c,v?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,S=>{s.delete(c),o.add(S),S.on("close",()=>o.delete(S));try{new cr(S,w,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(S),S.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&pn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=pr();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let g of s)g.destroy();s.clear();for(let g of i)g.destroy();i.clear();for(let g of o)g.close(1001,"server shutting down");let p=setTimeout(()=>{for(let g of o)g.readyState!==Fe.WebSocket.CLOSED&&g.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Er=require("@urun-sh/core");var As=require("@urun-sh/core"),Yu={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},Xu={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 $t(t,e){let n=Xu[t.code];return e?`${n} (${e})`:n}function fn(t){if(t==null)return null;let e=Yu[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 mn(t){if(t.kind==="create-failed")return fn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=As.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return fn(e?"cold_start_exceeded":"queue_timeout")}var Os=tt(require("os"),1),Ts=tt(require("path"),1),Ps=require("url"),Cs=require("util");var Is="0.6.37";var $s=4141,Zu=Is,hn={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 gr(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 Ms(t,e,n){let r={...t,...gr(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Ls(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 Ns(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Us(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Ds(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,Ps.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 Fs(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 qs(t){if(t[0]!=="--port")return null;let e=Fs(t[1]);return t.splice(0,2),e}function hr(t){let e=t.indexOf("--port");if(e===-1)return $s;let n=Fs(t[e+1]);return t.splice(e,2),n}function js(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 fr(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 ct(t){let e=el(fr(t,"URUN_BASE_URL")),n=fr(t,"URUN_ORG_ID"),r=fr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?gn(s,"URUN_API_URL"):To,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?gn(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 el(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 gn(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 yr(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:Zu}}function tl(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 nl=250;async function wr(t,e=nl){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 Bs=2e3;async function rl(t,e=Bs){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 Hs(t,e,n=$s,r=Bs){if(t!=null)return{mode:"spawn",port:t};let o=await wr(n);if(o!==null&&tl(o,e)){let s=await rl(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=Os.default.homedir()){return Ts.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var mr=["log","info","warn","error","debug","trace"];function Gs(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(mr.map(u=>[u,n[u]]));for(let u of mr)n[u]=(...a)=>{t.write(`${(0,Cs.format)(...a)}
|
|
21
|
+
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of mr)n[u]=i[u]}}var ol=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Js(t){let e=t?.code;return typeof e=="string"&&ol.has(e)}function xe(t,e){try{return t.write(e),!0}catch(n){if(Js(n))return!1;throw n}}function Vs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Js(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 Ws(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 qs(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 Ks=require("ws");var Ws=require("@urun-sh/core");var Gs=require("crypto");function T(t){return`${t}_${(0,Gs.randomUUID)().replace(/-/g,"").slice(0,24)}`}var fn=4*1024*1024,mr=8*1024*1024,mn=512,gn=20*1024*1024;function ee(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function dt(t,e){return{type:"server_error",code:t,message:e}}function J(t){return{type:"error",event_id:T("event"),error:t}}function gr(){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},Wu={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},Ku={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},zu={format:!0,voice:!0,speed:!0};function Yu(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function lt(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 Hs(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 Xu=10;function hr(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:Xu})}function Tt(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 Wu));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=lt(o.modalities,"modalities"),a=lt(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=lt(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(!Yu(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=hr(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[f,y]of Object.entries(l))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new P(`turn_detection.${f} 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.${f}`,"unsupported_field");if(y!=null&&y!==c[f])throw new P(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(y)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"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 Ku))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&Hs(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Tt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Tt({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 zu))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&Hs(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 hn(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 yr(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:T("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}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:T("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 yn(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 Qu=1001,Zu=1011,Vs=t=>t.slice(0,120),el=/^[A-Za-z0-9+/=]*$/,tl=2;function nl(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>tl)return!1;return!0}var Pt=class{id=T("conn");ws;binding;onClosed;operatorLog;config=gr();sessionId=T("sess");conversationId=T("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;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.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.send({type:"session.created",event_id:T("event"),session:hn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof j&&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(J(dt("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:T("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:T("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:T("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:T("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:T("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:T("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:T("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:T("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=T("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:T("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("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:T("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")>fn){this.fail(ee("frame_too_large",`frame exceeds the ${fn}-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}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(J({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(dt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=Tt(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(J(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:T("event"),session:hn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=yr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:T("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(J(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:T("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(J(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("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(J(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:T("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(J(ee("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!el.test(e.audio)){this.send(J(ee("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>gn){this.send(J(ee("buffer_full",`uncommitted input audio exceeds the ${gn}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(J(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=T("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:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("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:T("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:T("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(J(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(J(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}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(J(ee("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(J(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 Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(J({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(J(ee("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?lt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?lt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(J(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.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=T("req"),u=`resp_${i}`;this.activeResponseId=u;let a=this.binding.composite===!0,l=a?0:this.items.length,d=a?null:yn(this.items),c=hr(typeof n.instructions=="string"?n.instructions:this.config.instructions),f=typeof n.temperature=="number"?n.temperature:this.config.temperature,y=n.max_output_tokens??this.config.maxOutputTokens,g=y==="inf"||y===void 0?void 0:y,w=n.tools!==void 0?n.tools:this.config.tools,A=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...f!==void 0?{temperature:f}:{},...g!==void 0?{max_output_tokens:g}:{},...w!==void 0?{tools:w}:{},...A!==void 0?{tool_choice:A}:{}};if(!(a&&!this.ensureVoice())){for(let p of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(p);this.inFlight=(async()=>{let p=[],m=v=>{this.responseFlushed?this.send(v):p.push(v)},h=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(u,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(u,"in_progress")});for(let v of p)this.send(v);p.length=0,this.responseFlushed=!0}},_={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},k=null;try{if(a){if(this.pendingTranscriptItemId!==null&&(await new Promise(I=>{this.pendingTranscriptSettled=I}),this.cancelled||this.closed))return;l=this.items.length,d=yn(this.items)}let{input:v,sawAudioOnlyItem:R}=d??{input:[],sawAudioOnlyItem:!1},O={...S,input:v,...a?this.compositeTurnAsk(n):{}};R&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let x;try{x=await this.upstreamStream(O,i)}catch(I){this.upstreamTurnFault(I,u);return}try{for await(let I of x){if(this.cancelled)break;let b=I;if(b.type==="error"){let M=this.upstreamErrorBody(b);this.responseFlushed?this.send(J(M)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(u,M)});return}if(b.type==="response.output_text.delta"&&typeof b.delta=="string"){h(),_.messageOpen||(this.beginMessageItem(u,_.nextOutputIndex++),_.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:b.delta}),this.turnOutputIsAudio()&&(_.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:b.delta})),_.messageText+=b.delta;continue}if(b.type==="response.function_call_arguments.delta"){h();let M=typeof b.delta=="string"?b.delta:"",B=typeof b.call_id=="string"&&b.call_id.length>0?b.call_id:`${u}_fc_${_.nextOutputIndex}`,F=_.tools.get(B);if(!F){let Y=typeof b.name=="string"&&b.name.length>0?b.name:void 0;F={outputIndex:_.nextOutputIndex++,name:Y,args:""},_.tools.set(B,F);let H={id:B,object:"realtime.item",type:"function_call",call_id:B,name:Y??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:T("event"),response_id:u,output_index:F.outputIndex,item:H}),this.emitAssistantItemAdded(H)}typeof b.name=="string"&&b.name.length>0&&(F.name=b.name),F.args+=M,m({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:B,response_id:u,output_index:F.outputIndex,call_id:B,name:F.name??"",delta:M});continue}if(b.type==="response.completed"){k=b.response??null;continue}}}catch(I){this.upstreamTurnFault(I,u);return}if(this.cancelled)return;this.closeOpenItems(u,_,l),h(),this.send({type:"response.done",event_id:T("event"),response:this.doneResponse(u,l,k)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(nl(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(J({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:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:T("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:T("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:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("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:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("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:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:T("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:T("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:T("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:T("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:T("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:T("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:T("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=Ee(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??ve(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&we(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(dt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof j){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ws.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=dt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(J(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(J(ee("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>mn&&(this.items.shift(),this.send(J({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${mn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>mr){this.ws.close(Qu,Vs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=de(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(J(e)),this.ws.close(Zu,Vs(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.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Js(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Js(this.id,e)}},_r=[];function Js(t,e){_r.push({id:t,reason:e}),_r.length>256&&_r.shift()}var br="/v1/realtime",rl=t=>t.slice(0,120);function ol(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 Ks(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 ei=require("ws");var Zs=require("@urun-sh/core");var Ys=require("crypto");function T(t){return`${t}_${(0,Ys.randomUUID)().replace(/-/g,"").slice(0,24)}`}var yn=4*1024*1024,vr=8*1024*1024,wn=512,_n=20*1024*1024;function te(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ft(t,e){return{type:"server_error",code:t,message:e}}function K(t){return{type:"error",event_id:T("event"),error:t}}function br(){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},sl={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},il={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},al={format:!0,voice:!0,speed:!0};function ul(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function pt(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 zs(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 ll=10;function Sr(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:ll})}function Mt(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 sl));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=pt(o.modalities,"modalities"),a=pt(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=pt(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(!ul(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=Sr(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,g]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(g!=null&&g!==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(g)}, 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 il))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&zs(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Mt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Mt({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 al))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&zs(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 vn(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 kr(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:T("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}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:T("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 bn(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 dl=1001,cl=1011,Xs=t=>t.slice(0,120),pl=/^[A-Za-z0-9+/=]*$/,fl=2;function ml(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 Lt=class{id=T("conn");ws;binding;onClosed;operatorLog;config=br();sessionId=T("sess");conversationId=T("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;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.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.send({type:"session.created",event_id:T("event"),session:vn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof B&&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(ft("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:T("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:T("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:T("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:T("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:T("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:T("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:T("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:T("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=T("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:T("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("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:T("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(te("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>yn){this.fail(te("frame_too_large",`frame exceeds the ${yn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(te("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(te("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(K({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(ft(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=Mt(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(te("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:T("event"),session:vn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=kr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.added",event_id:T("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(te("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:T("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(te("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("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(te("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:T("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(te("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!pl.test(e.audio)){this.send(K(te("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>_n){this.send(K(te("buffer_full",`uncommitted input audio exceeds the ${_n}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=n;return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(K(te("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=T("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:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("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:T("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:T("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(te("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(te("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(K(te("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(K(te("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(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 upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(K(te("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?pt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?pt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(K(te("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=T("req"),u=`resp_${i}`;this.activeResponseId=u;let a=this.binding.composite===!0,l=a?0:this.items.length,d=a?null:bn(this.items),c=Sr(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,g=n.max_output_tokens??this.config.maxOutputTokens,h=g==="inf"||g===void 0?void 0:g,w=n.tools!==void 0?n.tools:this.config.tools,S=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,v={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...h!==void 0?{max_output_tokens:h}:{},...w!==void 0?{tools:w}:{},...S!==void 0?{tool_choice:S}:{}};if(!(a&&!this.ensureVoice())){for(let f of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(f);this.inFlight=(async()=>{let f=[],m=b=>{this.responseFlushed?this.send(b):f.push(b)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(u,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(u,"in_progress")});for(let b of f)this.send(b);f.length=0,this.responseFlushed=!0}},_={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},x=null;try{if(a){if(this.pendingTranscriptItemId!==null&&(await new Promise(I=>{this.pendingTranscriptSettled=I}),this.cancelled||this.closed))return;l=this.items.length,d=bn(this.items)}let{input:b,sawAudioOnlyItem:E}=d??{input:[],sawAudioOnlyItem:!1},O={...v,input:b,...a?this.compositeTurnAsk(n):{}};E&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let R;try{R=await this.upstreamStream(O,i)}catch(I){this.upstreamTurnFault(I,u);return}try{for await(let I of R){if(this.cancelled)break;let k=I;if(k.type==="error"){let $=this.upstreamErrorBody(k);this.responseFlushed?this.send(K($)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(u,$)});return}if(k.type==="response.output_text.delta"&&typeof k.delta=="string"){y(),_.messageOpen||(this.beginMessageItem(u,_.nextOutputIndex++),_.messageOpen=!0),this.config.outputModalities.includes("text")&&m({type:"response.output_text.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:k.delta}),this.turnOutputIsAudio()&&(_.transcriptDelta=!0,m({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:k.delta})),_.messageText+=k.delta;continue}if(k.type==="response.function_call_arguments.delta"){y();let $=typeof k.delta=="string"?k.delta:"",j=typeof k.call_id=="string"&&k.call_id.length>0?k.call_id:`${u}_fc_${_.nextOutputIndex}`,q=_.tools.get(j);if(!q){let X=typeof k.name=="string"&&k.name.length>0?k.name:void 0;q={outputIndex:_.nextOutputIndex++,name:X,args:""},_.tools.set(j,q);let G={id:j,object:"realtime.item",type:"function_call",call_id:j,name:X??"",arguments:"",status:"in_progress"};m({type:"response.output_item.added",event_id:T("event"),response_id:u,output_index:q.outputIndex,item:G}),this.emitAssistantItemAdded(G)}typeof k.name=="string"&&k.name.length>0&&(q.name=k.name),q.args+=$,m({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:j,response_id:u,output_index:q.outputIndex,call_id:j,name:q.name??"",delta:$});continue}if(k.type==="response.completed"){x=k.response??null;continue}}}catch(I){this.upstreamTurnFault(I,u);return}if(this.cancelled)return;this.closeOpenItems(u,_,l),y(),this.send({type:"response.done",event_id:T("event"),response:this.doneResponse(u,l,x)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(ml(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:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:T("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:T("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:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("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:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("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:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:T("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:T("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:T("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:T("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:T("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:T("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:T("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Oe(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??ke(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Se(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: ${be(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(ft("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof B){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Zs.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ft(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(K(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(K(te("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>wn&&(this.items.shift(),this.send(K({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${wn} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>vr){this.ws.close(dl,Xs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=pe(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${be(e)}`),r.message}fail(e,n){this.send(K(e)),this.ws.close(cl,Xs(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.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Qs(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Qs(this.id,e)}},xr=[];function Qs(t,e){xr.push({id:t,reason:e}),xr.length>256&&xr.shift()}var Ar="/v1/realtime",gl=t=>t.slice(0,120);function hl(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
|
|
26
26
|
Connection: close\r
|
|
27
27
|
Content-Type: text/plain\r
|
|
28
28
|
\r
|
|
29
|
-
${
|
|
30
|
-
`),t.destroy()}function
|
|
31
|
-
`}function il(t){be(process.stdout,t)}function al(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function wr(t){return t.audioSession?.audio.sessionId??void 0}function Sr(t,e){let n=new Ks.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==br)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=T("rtup"),l=al(o),d=_=>{(e.log??il)(sl(_))};d({stage:"accept",conn:a,model:l}),s.resume();let c=new AbortController,f=null,y=_=>{f??=_,c.abort(new Error(f))},g=()=>y("client socket closed"),w=()=>y("client socket closed (half-close)"),A=_=>y(`client socket error: ${_.message}`);s.once("close",g),s.once("end",w),s.once("error",A);let S=()=>{s.removeListener("close",g),s.removeListener("end",w),s.removeListener("error",A)},p=_=>{d({stage:"close",conn:a,model:l,..._})},m=_=>{let k=_,v=k.session!=null&&typeof k.session.sendResponseCreate=="function",R=k.clients!=null&&typeof k.clients.createResponse=="function";if(!v&&!R)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((O,x)=>{n.handleUpgrade(o,s,i,I=>{try{new Pt({ws:I,binding:_,operatorLog:e.operatorLog,onClosed:(b,M)=>{p({while:"live",reason:M.reason})}}),d({stage:"admit",conn:a,model:l,...wr(_)===void 0?{}:{session:wr(_)}}),O()}catch(b){x(b)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async _=>{if(c.signal.aborted){S();let k=wr(_);try{await _.release?.()}catch(v){p({while:"queued",...k===void 0?{}:{session:k},reason:f??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}p({while:"queued",...k===void 0?{}:{session:k},reason:f??"client socket closed",released:!0}),s.destroy();return}S(),await m(_)}).catch(_=>{let k=_ instanceof vr.SessionFailedError?dn(_):null,v=null;if(_!==null&&typeof _=="object"&&"status"in _){let I=_.status;typeof I=="number"&&(v=I)}let R=v??k?.status??502,O=_ instanceof Error?_.message:String(_),x=v!==null?O:k!==null?Ot(k,_ instanceof vr.SessionFailedError&&_.status.sessionId?`session ${_.status.sessionId}`:void 0):de(_).message;p({while:"queued",...c.signal.aborted?{reason:f??"client socket closed"}:{reason:O,status:R}}),s.destroyed||ol(s,R,x)}).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 Zs=require("crypto");var xr="x-urun-profile",Ct="voice";var ae=class extends Error{status=400},ul=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,ll=/\s/;function dl(t){return ul.test(t)}function kr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new ae(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function zs(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 ae(`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 ae(`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 ae(`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 Ys(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 ae(`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 ae(`the ${xr} header is empty \u2014 the only profile this lane accepts is "${Ct}" (omit the header for the ordinary lane)`);if(l!==Ct)throw new ae(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Ct}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Ct)throw new ae(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Ct}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new ae("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 ae("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:zs(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:zs(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 ct=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&&dl(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(ll.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 Oe=(t,e)=>Object.assign(new Error(e),{status:t}),fl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Er=(t,e,n)=>new j(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Rr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof D?Oe(404,n.message):n}};async function Xs(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Oe(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${fl}`);if(o==="transcription")throw Oe(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 Oe(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 Oe(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 f;try{f=await t.supportsTranscription(n.stt)}catch(y){throw y instanceof D?Oe(404,y.message):y}if(!f)throw Oe(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 f;try{f=await t.transcriptStreamFor(n.stt)}catch(y){throw y instanceof D?Oe(404,y.message):y}if(f!=="stt")throw Oe(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \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 Rr(t,n.stt),i=await Rr(t,e),u=await Rr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:f=>{let y=new AbortController;return d=y,ml({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},f,y.signal,()=>{d===y&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{a.appendInputAudio(f)},onOutputAudio:f=>l.onOutputAudio(f),sessionId:l.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(y){throw y instanceof j?Er("stt",n.stt,y):y}},composite:!0};return e!==void 0&&(c.model=e),c}function Qs(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var _n=class extends Error{};async function*ml(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,f=!Array.isArray(c)||c.includes("audio"),y=!1,g=null,w=null,A=[],S=null,p=new Promise((I,b)=>{n&&n.addEventListener("abort",()=>b(new _n),{once:!0})}),m=()=>y||n?.aborted===!0,h=async I=>{if(m())return;let b;try{b=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(B){throw B instanceof j?Er("tts",a.tts,B):B}let M=b[Symbol.asyncIterator]();w=M;try{for(;;){let B=M.next(),F;try{F=await Promise.race([B,p])}catch(H){if(B.catch(()=>{}),H instanceof _n)return;throw H}if(F.done)return;let Y=F.value;if(Y.type==="error"){let H=Y.error&&typeof Y.error.message=="string"?Y.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${H}`)}if(Y.type==="response.completed")return}}finally{w===M&&(w=null)}},_=async()=>{for(;A.length>0&&!m();){let I=A.shift();await h(I)}},k=I=>{if(I===""||m()||(A.push(I),S!==null))return;let b=_();S=b,b.then(()=>{S===b&&(S=null)},M=>{S===b&&(S=null),g??=M})},v=()=>{y=!0,A.length=0;let I=w;if(w=null,I){let b=I.return?.();b&&b.catch(()=>{})}},R=async()=>{for(;A.length>0||S!==null;){let I=S;if(I===null){await h(A.shift());continue}await I}},O=f?new ct({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>k(I)):null,x=null;try{let I;try{I=await o.createResponseOn(s,d)}catch(b){throw b instanceof j?Er("chat",u,b):b}for await(let b of I){if(m())return;let M=b;if(M.type==="error"){yield b;return}if(M.type==="response.output_text.delta"&&typeof M.delta=="string"){yield b,O?.push(M.delta);continue}if(M.type==="response.function_call_arguments.delta"){O?.flush(),yield b;continue}if(M.type==="response.completed"){x=b.response;continue}}O?.flush(),O?.dispose(),f&&await R(),x!==null&&(yield{type:"response.completed",response:x})}finally{O?.dispose(),v();try{if(g instanceof j)throw g}finally{r?.()}}}var ce=(t,e)=>Object.assign(new Error(e),{status:t});function gl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function hl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var yl='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function _l(t,e,n,r){if(!t.supportsAudio)throw ce(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 o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof D?ce(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof D?ce(404,c.message):c}if(d!==null)return await Xs(t,e,d,n,r);throw ce(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 ce(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 s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof D?ce(404,d.message):d}if(s&&!t.openTurnsOn)throw ce(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(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(c){throw c instanceof D?ce(404,c.message):c}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${yl}`);if(r==="transcription"&&!s)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=await t.sessionHandle(e)}catch(d){throw d instanceof le?ce(503,d.message):d}let u=`conn_${(0,Zs.randomUUID)()}`,a={audio:await t.openAudioOn(i,n,u)},l={clients:{createResponse:async d=>await t.createResponseOn(i,d,u)},voice:o,audioSession:a};return s&&(l.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),t.releaseSessionHandle&&(l.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function ei(t,e,n){let r=Qs(t,n);return{resolve:async(o,s)=>{if(e!==void 0){let i=o.headers.authorization,u=typeof i=="string"?i.trim():"",a=u.startsWith("Bearer ")?u.slice(7).trim():"";if(a===""||a!==e)throw ce(401,"invalid local proxy api key")}return _l(r,gl(o),s,hl(o))}}}var te=class extends Error{};async function wn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new te(`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 te(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function vn(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 te(`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 te?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ti="/v1/images/generations",bn="/v1/images/edits";function ni(t){return t===ti||t===bn}var ri="/v1/images/models";async function oi(t,e,n){if(t){if(t.model=ie({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 U=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},wl=16*1024*1024,si=64*1024*1024;function ii(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 Mt(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 ai(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 w=g.error??{},A=typeof w.message=="string"&&w.message.length>0&&we(w.message)?w.message:null;throw A===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(g)}`),new U(502,"the image upstream failed while serving this request")):new U(502,`image upstream error: ${A}`)}if(g.type==="response.completed"){a=g.response??null;break}}if(a===null)throw new U(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ie(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new U(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],f=Buffer.from(c,"base64");if(ii(f)===null)throw new U(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${f.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function ui(t,e){if(t instanceof U)return t;if(t instanceof Re)throw t;return t instanceof D?new U(404,t.message):new U(502,at("image",t,e))}async function li(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 Mt(r,new U(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 di(t,e){t&&(t.outputUnits=e.images.length)}function ci(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 vl={model:!0,prompt:!0,response_format:!0,n:!0};async function pi(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??si;try{if(t.method!=="POST")throw new U(405,`${String(t.method)} is not supported on ${ti}`);let s;try{s=JSON.parse((await wn(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof te?new U(413,f.message):new U(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new U(400,"request body must be a JSON object");let i=s;for(let f of Object.keys(i))if(!vl[f])throw new U(400,`request field "${f}" 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.`,f);let u=i.prompt;if(typeof u!="string"||u.trim().length===0)throw new U(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 U(400,"model must be a string","model");await oi(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new U(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 U(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 li(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let f=await ai(n.clients,a,c,n.turn?fe(n.turn):void 0,n.turn,r);di(n.turn,f),ci(e,f)}catch(f){throw ui(f,r)}}catch(s){if(s instanceof te){Mt(e,new U(413,s.message));return}if(s instanceof U){Mt(e,s);return}throw s}}var bl={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function fi(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??si,s=n.maxImagePartBytes??wl;try{if(t.method!=="POST")throw new U(405,`${String(t.method)} is not supported on ${bn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new U(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await vn(t,o)}catch(g){throw g instanceof te?new U(413,g.message):new U(400,String(g instanceof Error?g.message:g))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new U(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 U(400,"model must be a string field","model");let d=l===null?void 0:l;await oi(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new U(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(!bl[g])throw new U(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 f=[];for(let g of["image","image[]"])for(let w of u.getAll(g)){if(!(w instanceof File))throw new U(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",g);if(w.size>s)throw new U(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let A=new Uint8Array(await w.arrayBuffer()),S=ii(A);if(S===null)throw new U(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",g);f.push({bytes:A,mime:S})}if(f.length===0)throw new U(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await li(n.imageModels,d,"edit",e))return;let y=[{type:"input_text",text:a}];for(let{bytes:g,mime:w}of f)y.push({type:"input_image",image_url:`data:${w};base64,${Buffer.from(g).toString("base64")}`});try{let g=await ai(n.clients,d,y,n.turn?fe(n.turn):void 0,n.turn,r);di(n.turn,g),ci(e,g)}catch(g){throw ui(g,r)}}catch(i){if(i instanceof te){Mt(e,new U(413,i.message));return}if(i instanceof U){Mt(e,i);return}throw i}}var $t="/v1/audio/speech";function Si(t){return t===$t}var mi=4096,gi=18e4,hi=5e3,Sl=64*1024*1024,yi=8,_i=5,wi=1024*1024,pt="voice_applied",kn="X-Urun-Voice-Applied",L=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Ar(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 xn=class extends L{constructor(e){super(502,e)}};function ki(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 xi(t){return new L(502,`the runtime's ${pt} receipt ${JSON.stringify(t)} cannot be relayed as the ${kn} 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 kl(t,e,n){if(t){if(t.model=ie({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 Ri(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var xl=2;function Rl(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>xl)return!1;return!0}function El(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 vi=new WeakMap,Sn=new WeakMap;function Al(t,e){let n=Sn.get(t)??0;if(n>=yi)throw new L(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 ${_i}s`,void 0,_i);Sn.set(t,n+1);let r=vi.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return vi.set(t,s),(async()=>{await r;try{return await e()}finally{Sn.set(t,(Sn.get(t)??1)-1),o()}})()}async function Il(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new L(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 j))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Ke(t,e){if(t instanceof L)return t;if(t instanceof Re)throw t;return t instanceof D?new L(404,t.message):new L(502,at("speech",t,e))}async function bi(t,e,n,r,o,s,i,u,a,l){let d=l??(f=>console.error(f)),c=u??(()=>{});return Al(e,async()=>{if(i?.()===!0)return null;let f=!1,y=!1,g=!1,w,A=new Promise(R=>{w=R}),S=[],p=()=>{y&&!g&&S.length>=o.quietRunFrames&&(g=!0,w())},m=e.onOutputAudio(R=>{let O=Buffer.from(R,"base64");if(O.byteLength===0)return;let x=Rl(O);if(!f){if(x)return;f=!0}if(x){S.push(O),p();return}for(let I of S)c(I);S.length=0,c(O),p()}),h=null,_,k,v;try{v=(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 O=new Promise(b=>{k=setTimeout(b,s.capMs)}),x=!1;for(;;){let b=v.next(),M=await Promise.race([b,O]);if(M===void 0){x=!0,b.catch(()=>{});break}if(M.done)break;let B=M.value;if(B.type==="error"){let F=B.error??{};await v.return?.();let Y=typeof F.message=="string"&&F.message.length>0&&we(F.message)?F.message:null;throw Y===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(B)}`),new L(502,"the speech upstream failed while serving this request")):new L(502,`speech upstream error: ${Y}`)}if(B.type==="response.completed"){h=B.response??null,y=!0,a?.(h),p(),await v.return?.();break}}if(clearTimeout(k),x)throw new L(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(h===null)throw new L(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let I=!1;if(await Promise.race([A,new Promise(b=>{_=setTimeout(()=>{I=!0,b()},o.capMs)})]),_!==void 0&&clearTimeout(_),r.voice!==void 0){let b=h[pt];if(typeof b!="string"||b!==r.voice){let M=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof b=="string"?`${pt} ${JSON.stringify(b)}`:`no ${pt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new xn(M):new L(502,M)}}if(!f)throw new L(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(I&&!g&&S.length<1)throw new L(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return h}catch(R){throw R instanceof xn||await Il(t,n,v,s.returnBoundMs),R}finally{_!==void 0&&clearTimeout(_),k!==void 0&&clearTimeout(k),m()}})}function Ol(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",kn)),t.write(u,a=>{a||(s+=u.byteLength,Ri(e,s))}),t.writableLength>wi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${wi} 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[pt];if(typeof a=="string"){if(!ki(a))throw xi(a);t.addTrailers({[kn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function Tl(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Ke(s,r)}return o?!0:(Ar(n,new L(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 Pl={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Cl="wav, pcm";async function Ei(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??Sl,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${$t}`);let u;try{u=JSON.parse((await wn(t,o)).toString("utf8")||"{}")}catch(h){throw h instanceof te?new L(413,h.message):new L(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new L(400,"request body must be a JSON object");let a=u;for(let h of Object.keys(a))if(!Pl[h])throw new L(400,`request field "${h}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,h);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new L(400,"input is required and must be a non-empty string","input");if(l.length>mi)throw new L(400,`input is ${l.length} chars \u2014 over the ${mi}-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 L(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new L(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new L(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 ${$t} against a stale copy of the list`);let f;try{f=await n.clients.speechVoices(d)}catch(h){throw Ke(h,r)}if(f.defect!==null)throw new L(500,`the voice set for this model cannot be resolved: ${f.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let y=typeof c=="string"?c:void 0;if(y!==void 0&&f.published.length>0&&!f.published.includes(y))throw new L(400,`voice ${JSON.stringify(y)} is not one of the voices this model publishes \u2014 accepted voices: ${f.published.join(", ")}`,"voice");let g=a.response_format??"wav";if(g!=="wav"&&g!=="pcm")throw new L(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 ${Cl} \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 L(400,"stream_format, when present, must be a string","stream_format");let w=a.speed;if(w!==void 0){if(typeof w!="number"||!Number.isFinite(w))throw new L(400,"speed, when present, must be a number","speed");if(w!==1)throw new L(400,`speed=${JSON.stringify(w)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let A=a.instructions;if(A!==void 0){if(typeof A!="string")throw new L(400,"instructions, when present, must be a string","instructions");if(A.trim().length>0)throw new L(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 kl(n.turn,n.clients,d);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await Tl(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new L(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 L(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 L(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 p;try{p=await n.clients.speechSessionHandle(d)}catch(h){throw Ke(h,r)}let m;try{m=await n.clients.openAudioOn(p)}catch(h){throw Ke(h,r)}n.turn&&(n.turn.sessionId=m.sessionId);try{if(g==="wav"){let h=[],_=await bi(n.clients,m,p,{model:d,text:l,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??gi,returnBoundMs:n.turnReturnBoundMs??hi},i,v=>h.push(v),v=>{n.turn&&(n.turn.outputSeconds=Ie(v))},r);if(_===null||i())return;let k=Buffer.concat(h);if(y===void 0){let v=_[pt];if(typeof v=="string"){if(!ki(v))throw xi(v);e.setHeader(kn,v)}}Ri(n.turn,k.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([El(k.byteLength),k]))}else{let h=Ol(e,n.turn,i,y===void 0),_;try{_=await bi(n.clients,m,p,{model:d,text:l,...y!==void 0?{voice:y}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??gi,returnBoundMs:n.turnReturnBoundMs??hi},i,h.sink,k=>{n.turn&&(n.turn.outputSeconds=Ie(k))},r)}catch(k){let v=Ke(k,r);if(!h.started())throw v;n.turn&&(n.turn.streamError=!0),h.fail(v);return}if(_===null)return;try{await h.finish(_)}catch(k){let v=Ke(k,r);n.turn&&(n.turn.streamError=!0),h.fail(v);return}}}catch(h){throw Ke(h,r)}}catch(u){if(u instanceof te){Ar(e,new L(413,u.message));return}if(u instanceof L){Ar(e,u);return}throw u}}var Rn="/v1/audio/transcriptions";function Ai(t){return t===Rn}var Ii="/v1/audio/models",Ml=16*1024*1024,$l=64*1024*1024,K=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Ir(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 Oi(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 Ll(t){if(!Oi(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 Nl(t,e,n){if(t){if(t.model=ie({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 Ul(t,e){t&&(t.outputUnits=e.seconds)}async function Dl(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 f=c.error??{},y=typeof f.type=="string"?f.type:"upstream_error",g=typeof f.message=="string"&&f.message.length>0&&we(f.message)?f.message:null;throw g===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new K(y==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new K(y==="invalid_request_error"?400:502,`transcription upstream error: ${g}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new K(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Ie(d)),st(l,d)}function Ti(t,e){if(t instanceof K)return t;if(t instanceof Re)throw t;return t instanceof D?new K(404,t.message):new K(502,at("transcription",t,e))}async function Fl(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Ti(s,r)}return o?!0:(Ir(n,new K(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 Bl=new Set(["file","model","language","response_format"]);async function Pi(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??$l,s=n.maxAudioPartBytes??Ml;try{if(t.method!=="POST")throw new K(405,`${String(t.method)} is not supported on ${Rn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new K(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await vn(t,o)}catch(p){throw p instanceof te?new K(413,p.message):new K(400,String(p instanceof Error?p.message:p))}let a=new Map;for(let p of u.keys()){if(!Bl.has(p))throw new K(400,`form field "${p}" 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.`,p);a.set(p,(a.get(p)??0)+1)}for(let[p,m]of a)if(m>1)throw new K(400,`form field "${p}" appears ${m} 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`,p);let l=u.get("model");if(l!==null&&typeof l!="string")throw new K(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 K(400,"language, when present, must be a non-empty string","language");let f=c===null?void 0:c,y=u.get("response_format")??"json";if(y!=="json")throw new K(400,`response_format ${JSON.stringify(y)} 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 K(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 K(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let w=new Uint8Array(await g.arrayBuffer());if(!Oi(w))throw new K(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 A=Ll(w);if(A===null)throw new K(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 Nl(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",w.length,w.length),!await Fl(n.transcriptionModels,d,e,r))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(w).toString("base64"),format:"wav"}}];try{let p=await Dl(n.clients,d,S,f,n.turn?fe(n.turn):void 0,n.turn,r);Ul(n.turn,A),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:p}))}catch(p){throw Ti(p,r)}}catch(i){if(i instanceof te){Ir(e,new K(413,i.message));return}if(i instanceof K){Ir(e,i);return}throw i}}var Mi="/v1/usage/requests",Ci=1e4,jl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ue=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},ft=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var $i=1024*1024;function Or(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ue(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ue(`"${e}" must be an array of uuid strings`);if(n.length>Ci)throw new Ue(`"${e}" carries ${n.length} ids; at most ${Ci} 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"||!jl.test(s))throw new Ue(`"${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 Li(t){return Or(t,"inference_ids")}function En(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 ft(`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 ft(`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 Tn=require("@urun-sh/core");var Tr="/partners/huggingface/v1/billing/requests";function ql(t){return Or(t,"requestIds")}function Hl(t){return t>=200&&t<=399}function Gl(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Hl(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Ni(t,e){let n=ql(t),r=await e(n);return En(r,n),Gl(r)}var Vl={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Jl(t){return Vl[t]??null}var Bi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Wl(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Kl(t){return t==="surface"}function zl(t){let e=t?.ledgerFailureReason;return Bi.includes(e)?e:"unknown"}var Yl=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Ui=["priced","unpriced"],Xl={written:Ui,already_written:Ui,skipped:Yl,failed:Bi},rm=Object.entries(Xl).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ql(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Zl(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 ed=256,Di=4096,Nt=12e4,td=250,nd=8e3,Ut=[],Fi=new Set,Dt=0,Lt=!1;var rd=new Set;function od(){return Dt===0&&Ut.length===0}function sd(){if(od()){Lt=!1;for(let t of[...rd])t()}}function ji(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
32
|
-
`}function id(t){be(process.stdout,t)}function qi(t,e){try{t(e)}catch{}}function Hi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??id,o=Jl(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),qi(r,ji("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:Zl(e),completed_at:e.ts,billable_outcome:Ql(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,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(Ut.length>=Di){i("queue_full",`${Ut.length} ledger writes are already waiting (capacity ${Di}, ${Dt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Ut.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Dt<ed&&(Dt+=1,ad())}async function ad(){try{for(;;){let t=ud();if(t===void 0)return;Fi.add(t);try{await ld(t)}finally{Fi.delete(t)}}}finally{Dt-=1,sd()}}function ud(){let t=Date.now();for(;;){let e=Ut.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Nt)return e;mt(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 ${Nt}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 ld(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);mt(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=Wl(o);if(s!==null){mt(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=zl(o),u=Date.now()-t.queuedAt;if(Lt){mt(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(Kl(i)&&u<Nt){if(await cd(dd(t.attempts)),Lt||Date.now()-t.queuedAt>=Nt){let a=Date.now()-t.queuedAt;mt(t,{outcome:"failed",reason:Lt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Lt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${Nt}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}mt(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 dd(t){return Math.min(nd,td*2**Math.max(0,t-1))}function cd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function mt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;qi(t.report,ji(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Mr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function pd(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 re(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function z(t,e,n,r="invalid_request_error",o){re(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function $r(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Ee(r),u=i??ve(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"),re(t,l,{error:{message:u,type:o,code:a}})}function Se(t,e,n,r){re(t,e,{type:"error",error:{type:n,message:r}})}function gt(t,e,n){if(e==="anthropic"){re(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}re(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var fd=64*1024*1024,Ft=class extends Error{};async function Gi(t,e=fd){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Ft(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ze(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 Wi(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 An(t){let e=Wi(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Vi(t){let e=An(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function md(t,e){let n=Wi(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function gd(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 hd(t,e){let n=gd(e);n&&(t.timing=n),t.outputSeconds=Ie(e)}function Ye(t,e){md(t,e),hd(t,e)}async function Pn(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 Ki(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 yd(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 In=class extends Error{};function _d(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 In(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function wd(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:_d(n.role,n.content)})}return e}function Pr(t){return rt(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 vd(t,e,n,r,o,s,i){let u=Et(s.id),a=t.stream===!0;if(s.model=ie(t),s.stream=a,await Pn(s,e,typeof t.model=="string"?t.model:void 0),a){let p;try{p=await It({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(m){if(m instanceof D){gt(r,"openai",m);return}if(m instanceof me){z(r,m.status,m.message);return}if(m instanceof he||m instanceof le){r.setHeader("retry-after","2"),z(r,503,m.message,"capacity_error");return}throw m}Mr(r);for await(let m of p.events){if(m.type==="error"){s.streamError=!0;let h=m.error,_=Ee(h),k=_??ve(s.id);_===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(m)}`),r.write(`event: error
|
|
33
|
-
data: ${JSON.stringify({error:{message:k,type:h?.type??"upstream_error",code:h?.code??null}})}
|
|
29
|
+
${gl(n)}\r
|
|
30
|
+
`),t.destroy()}function yl(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
31
|
+
`}function wl(t){xe(process.stdout,t)}function _l(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Rr(t){return t.audioSession?.audio.sessionId??void 0}function Ir(t,e){let n=new ei.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Ar)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=T("rtup"),l=_l(o),d=_=>{(e.log??wl)(yl(_))};d({stage:"accept",conn:a,model:l}),s.resume();let c=new AbortController,p=null,g=_=>{p??=_,c.abort(new Error(p))},h=()=>g("client socket closed"),w=()=>g("client socket closed (half-close)"),S=_=>g(`client socket error: ${_.message}`);s.once("close",h),s.once("end",w),s.once("error",S);let v=()=>{s.removeListener("close",h),s.removeListener("end",w),s.removeListener("error",S)},f=_=>{d({stage:"close",conn:a,model:l,..._})},m=_=>{let x=_,b=x.session!=null&&typeof x.session.sendResponseCreate=="function",E=x.clients!=null&&typeof x.clients.createResponse=="function";if(!b&&!E)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((O,R)=>{n.handleUpgrade(o,s,i,I=>{try{new Lt({ws:I,binding:_,operatorLog:e.operatorLog,onClosed:(k,$)=>{f({while:"live",reason:$.reason})}}),d({stage:"admit",conn:a,model:l,...Rr(_)===void 0?{}:{session:Rr(_)}}),O()}catch(k){R(k)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async _=>{if(c.signal.aborted){v();let x=Rr(_);try{await _.release?.()}catch(b){f({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",release_failed:b instanceof Error?b.message:String(b)});return}f({while:"queued",...x===void 0?{}:{session:x},reason:p??"client socket closed",released:!0}),s.destroy();return}v(),await m(_)}).catch(_=>{let x=_ instanceof Er.SessionFailedError?mn(_):null,b=null;if(_!==null&&typeof _=="object"&&"status"in _){let I=_.status;typeof I=="number"&&(b=I)}let E=b??x?.status??502,O=_ instanceof Error?_.message:String(_),R=b!==null?O:x!==null?$t(x,_ instanceof Er.SessionFailedError&&_.status.sessionId?`session ${_.status.sessionId}`:void 0):pe(_).message;f({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:O,status:E}}),s.destroyed||hl(s,E,R)}).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 si=require("crypto");var Tr="x-urun-profile",Nt="voice";var le=class extends Error{status=400},vl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,bl=/\s/;function Sl(t){return vl.test(t)}function Or(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new le(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function ti(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 le(`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 le(`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 le(`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 ni(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 le(`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 le(`the ${Tr} header is empty \u2014 the only profile this lane accepts is "${Nt}" (omit the header for the ordinary lane)`);if(l!==Nt)throw new le(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Nt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Nt)throw new le(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Nt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new le("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 le("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:ti(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:ti(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Or(a,"sentence_flush",!0),includeReasoning:Or(a,"include_reasoning",!1),metadata:Or(a,"metadata",!1)}}var mt=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&&Sl(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(bl.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 Ce=(t,e)=>Object.assign(new Error(e),{status:t}),Rl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Cr=(t,e,n)=>new B(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Pr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof F?Ce(404,n.message):n}};async function ri(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Ce(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Rl}`);if(o==="transcription")throw Ce(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 Ce(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 Ce(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(g){throw g instanceof F?Ce(404,g.message):g}if(!p)throw Ce(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(g){throw g instanceof F?Ce(404,g.message):g}if(p!=="stt")throw Ce(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 Pr(t,n.stt),i=await Pr(t,e),u=await Pr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:p=>{let g=new AbortController;return d=g,El({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},p,g.signal,()=>{d===g&&(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(g){throw g instanceof B?Cr("stt",n.stt,g):g}},composite:!0};return e!==void 0&&(c.model=e),c}function oi(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Sn=class extends Error{};async function*El(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"),g=!1,h=null,w=null,S=[],v=null,f=new Promise((I,k)=>{n&&n.addEventListener("abort",()=>k(new Sn),{once:!0})}),m=()=>g||n?.aborted===!0,y=async I=>{if(m())return;let k;try{k=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(j){throw j instanceof B?Cr("tts",a.tts,j):j}let $=k[Symbol.asyncIterator]();w=$;try{for(;;){let j=$.next(),q;try{q=await Promise.race([j,f])}catch(G){if(j.catch(()=>{}),G instanceof Sn)return;throw G}if(q.done)return;let X=q.value;if(X.type==="error"){let G=X.error&&typeof X.error.message=="string"?X.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${G}`)}if(X.type==="response.completed")return}}finally{w===$&&(w=null)}},_=async()=>{for(;S.length>0&&!m();){let I=S.shift();await y(I)}},x=I=>{if(I===""||m()||(S.push(I),v!==null))return;let k=_();v=k,k.then(()=>{v===k&&(v=null)},$=>{v===k&&(v=null),h??=$})},b=()=>{g=!0,S.length=0;let I=w;if(w=null,I){let k=I.return?.();k&&k.catch(()=>{})}},E=async()=>{for(;S.length>0||v!==null;){let I=v;if(I===null){await y(S.shift());continue}await I}},O=p?new mt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>x(I)):null,R=null;try{let I;try{I=await o.createResponseOn(s,d)}catch(k){throw k instanceof B?Cr("chat",u,k):k}for await(let k of I){if(m())return;let $=k;if($.type==="error"){yield k;return}if($.type==="response.output_text.delta"&&typeof $.delta=="string"){yield k,O?.push($.delta);continue}if($.type==="response.function_call_arguments.delta"){O?.flush(),yield k;continue}if($.type==="response.completed"){R=k.response;continue}}O?.flush(),O?.dispose(),p&&await E(),R!==null&&(yield{type:"response.completed",response:R})}finally{O?.dispose(),b();try{if(h instanceof B)throw h}finally{r?.()}}}var fe=(t,e)=>Object.assign(new Error(e),{status:t});function Al(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Il(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Ol='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Tl(t,e,n,r){if(!t.supportsAudio)throw fe(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 o;try{o=await t.supportsAudio(e)}catch(d){throw d instanceof F?fe(404,d.message):d}if(!o){let d=null;if(t.realtimeCompanionsFor)try{d=await t.realtimeCompanionsFor(e)}catch(c){throw c instanceof F?fe(404,c.message):c}if(d!==null)return await ri(t,e,d,n,r);throw fe(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 fe(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 s=!1;if(t.supportsTranscription)try{s=await t.supportsTranscription(e)}catch(d){throw d instanceof F?fe(404,d.message):d}if(s&&!t.openTurnsOn)throw fe(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(s&&t.transcriptStreamFor){let d;try{d=await t.transcriptStreamFor(e)}catch(c){throw c instanceof F?fe(404,c.message):c}if(d!=="stt")throw fe(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw fe(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Ol}`);if(r==="transcription"&&!s)throw fe(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=await t.sessionHandle(e)}catch(d){throw d instanceof ce?fe(503,d.message):d}let u=`conn_${(0,si.randomUUID)()}`,a={audio:await t.openAudioOn(i,n,u)},l={clients:{createResponse:async d=>await t.createResponseOn(i,d,u)},voice:o,audioSession:a};return s&&(l.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),t.releaseSessionHandle&&(l.release=()=>t.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function ii(t,e,n){let r=oi(t,n);return{resolve:async(o,s)=>{if(e!==void 0){let i=o.headers.authorization,u=typeof i=="string"?i.trim():"",a=u.startsWith("Bearer ")?u.slice(7).trim():"";if(a===""||a!==e)throw fe(401,"invalid local proxy api key")}return Tl(r,Al(o),s,Il(o))}}}var M=class extends Error{},ye=class extends Error{};function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function gt(t,e){if(t!=null)throw new M(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function kn(t){let e=xn(t);return e!==null&&e<=1?e:null}function ai(t,e){if(!ne(t))throw new M("decisions requires a JSON object body");gt(t.prompt_cache_key,"prompt_cache_key"),gt(t.prompt_cache_options,"prompt_cache_options"),gt(t.safety_identifier,"safety_identifier");let n=[],r=Pl(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new M("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}=Ll(o[l],l,o.length,n);if(u.has(c.key))throw new M(`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 Pl(t,e){if(typeof t=="string")return t;if(!ne(t)&&!Array.isArray(t))throw new M("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)$l(o,r,e);return Cl(r)}function Cl(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
34
32
|
|
|
35
|
-
`),r.
|
|
33
|
+
`)}function $l(t,e,n){if(!ne(t))throw new M("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Ml(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)){ui(s,e,n,void 0,!1);return}throw new M(`${o} output must be a string or an array of parts`)}default:throw new M(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function Ml(t,e,n,r){e==="assistant"&>(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 M(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!ne(s))throw new M("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 M(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}ui(o,n,r,e)}function ui(t,e,n,r,o=!0){for(let s of t){if(!ne(s))throw new M("decisions content parts must be JSON objects");switch(gt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new M("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new M("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(!ne(i)&&!(Array.isArray(i)&&i.every(ne)))throw new M("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(li(s));break}default:throw new M(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function li(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new M("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new M("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 M("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 M("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 M("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 Ll(t,e,n,r){if(!ne(t))throw new M(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new M(`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 M(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=Nl(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:a,options:[["no","the condition is not true"],["yes","the condition is 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 M(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let w of l){if(!ne(w))throw new M(`questions[${e}] choices must be JSON objects`);let S=w.value;if(typeof S!="string"&&typeof S!="boolean")throw new M(`questions[${e}] choice value must be a string or boolean`);let v=String(S);if(c.has(v))throw new M(`questions[${e}] has duplicate choice value ${JSON.stringify(v)} (choices must be unique)`);c.add(v);let f=w.description;if(f!==void 0&&typeof f!="string")throw new M(`questions[${e}] choice description must be a string`);d.push(S),p.push(f)}let g=l.map((w,S)=>({name:String(d[S]),description:p[S]??String(d[S])}));return{entry:{kind:"choice",prompt:a,options:g},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 M(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let g of l){if(!ne(g)||typeof g.label!="string")throw new M(`questions[${e}] score levels must carry a string label`);if(d.includes(g.label))throw new M(`questions[${e}] has duplicate level label ${JSON.stringify(g.label)}`);d.push(g.label);let h=g.description;if(h!==void 0&&typeof h!="string")throw new M(`questions[${e}] score level description must be a string`);let w=h!==void 0?`${g.label}: ${h}`:g.label;if(c.includes(w))throw new M(`questions[${e}] has duplicate score criterion ${JSON.stringify(w)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(w)}return{entry:{kind:"score",prompt:a,criteria:c},spec:{type:o,key:u,name:i,levelLabels:d,scoreCriteria:c}}}}}function Nl(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new M(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!ne(s))throw new M(`questions[${e}] instruction parts must be JSON objects`);switch(gt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new M(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new M(`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(li(s));break}case"input_json":{let i=s.data;if(!ne(i)&&!(Array.isArray(i)&&i.every(ne)))throw new M(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new M(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
|
|
34
|
+
|
|
35
|
+
`)}function di(t,e){if(!ne(e))throw new ye("decision answer was not a JSON object");let n=e.choices;if(!ne(n))throw new ye("decision answer carried no choices object");let r=[];for(let o of t){let s=n[o.key];if(!ne(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=ne(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=kn(i.yes),a=kn(i.no),l=u??(a!==null?1-a:null);if(l===null)throw new ye(`the predicate answer for "${o.key}" carries neither a yes nor a no probability to translate`);r.push({type:"predicate",name:o.name,probability:l});continue}case"choice":{let u=o.choiceValues??[],a=s.choice;if(typeof a!="string")throw new ye(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new ye(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=xn(s.confidence);if(d===null)throw new ye(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let g=kn(i[String(p)]);g!==null&&c.push({value:p,probability:g})}r.push({type:"choice",name:o.name,choice:u[l],confidence:d,probabilities:c});continue}case"score":{let u=o.levelLabels??[],a=o.scoreCriteria??[],l=xn(s.score);if(l===null)throw new ye(`the score answer for "${o.key}" carries no numeric score to translate`);let d=xn(s.confidence);if(d===null)throw new ye(`the score answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p=0;p<u.length;p++){let g=kn(i[a[p]]);g!==null&&c.push({value:p,label:u[p],probability:g})}r.push({type:"score",name:o.name,score:l,confidence:d,probabilities:c});continue}}}return r}var re=class extends Error{};async function Rn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new re(`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 re(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function En(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 re(`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 re?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var ci="/v1/images/generations",An="/v1/images/edits";function pi(t){return t===ci||t===An}var fi="/v1/images/models";async function mi(t,e,n){if(t){if(t.model=ae({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 D=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Ul=16*1024*1024,gi=64*1024*1024;function hi(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 Ut(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 yi(t,e,n,r,o,s){let i=s??(h=>console.error(h)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),a=null;for await(let h of u){if(h.type==="error"){let w=h.error??{},S=typeof w.message=="string"&&w.message.length>0&&Se(w.message)?w.message:null;throw S===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new D(502,"the image upstream failed while serving this request")):new D(502,`image upstream error: ${S}`)}if(h.type==="response.completed"){a=h.response??null;break}}if(a===null)throw new D(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Pe(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new D(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(hi(p)===null)throw new D(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 wi(t,e){if(t instanceof D)return t;if(t instanceof Ie)throw t;return t instanceof F?new D(404,t.message):new D(502,dt("image",t,e))}async function _i(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 Ut(r,new D(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 vi(t,e){t&&(t.outputUnits=e.images.length)}function bi(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var Dl={model:!0,prompt:!0,response_format:!0,n:!0};async function Si(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??gi;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${ci}`);let s;try{s=JSON.parse((await Rn(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof re?new D(413,p.message):new D(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new D(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!Dl[p])throw new D(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 D(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 D(400,"model must be a string","model");await mi(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new D(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 D(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 _i(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await yi(n.clients,a,c,n.turn?ge(n.turn):void 0,n.turn,r);vi(n.turn,p),bi(e,p)}catch(p){throw wi(p,r)}}catch(s){if(s instanceof re){Ut(e,new D(413,s.message));return}if(s instanceof D){Ut(e,s);return}throw s}}var Fl={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ki(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??gi,s=n.maxImagePartBytes??Ul;try{if(t.method!=="POST")throw new D(405,`${String(t.method)} is not supported on ${An}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new D(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await En(t,o)}catch(h){throw h instanceof re?new D(413,h.message):new D(400,String(h instanceof Error?h.message:h))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new D(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 D(400,"model must be a string field","model");let d=l===null?void 0:l;await mi(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new D(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 h of u.keys())if(!Fl[h])throw new D(400,`form field "${h}" 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[]).`,h);let p=[];for(let h of["image","image[]"])for(let w of u.getAll(h)){if(!(w instanceof File))throw new D(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(w.size>s)throw new D(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let S=new Uint8Array(await w.arrayBuffer()),v=hi(S);if(v===null)throw new D(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",h);p.push({bytes:S,mime:v})}if(p.length===0)throw new D(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await _i(n.imageModels,d,"edit",e))return;let g=[{type:"input_text",text:a}];for(let{bytes:h,mime:w}of p)g.push({type:"input_image",image_url:`data:${w};base64,${Buffer.from(h).toString("base64")}`});try{let h=await yi(n.clients,d,g,n.turn?ge(n.turn):void 0,n.turn,r);vi(n.turn,h),bi(e,h)}catch(h){throw wi(h,r)}}catch(i){if(i instanceof re){Ut(e,new D(413,i.message));return}if(i instanceof D){Ut(e,i);return}throw i}}var Dt="/v1/audio/speech";function Ci(t){return t===Dt}var xi=4096,Ri=18e4,Ei=5e3,ql=64*1024*1024,Ai=8,Ii=5,Oi=1024*1024,ht="voice_applied",On="X-Urun-Voice-Applied",N=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function $r(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 Tn=class extends N{constructor(e){super(502,e)}};function $i(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 Mi(t){return new N(502,`the runtime's ${ht} receipt ${JSON.stringify(t)} cannot be relayed as the ${On} 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 jl(t,e,n){if(t){if(t.model=ae({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 Li(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Bl=2;function Hl(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Bl)return!1;return!0}function Gl(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 Ti=new WeakMap,In=new WeakMap;function Jl(t,e){let n=In.get(t)??0;if(n>=Ai)throw new N(503,`this model's speech queue is full \u2014 ${Ai} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Ii}s`,void 0,Ii);In.set(t,n+1);let r=Ti.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ti.set(t,s),(async()=>{await r;try{return await e()}finally{In.set(t,(In.get(t)??1)-1),o()}})()}async function Vl(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new N(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 B))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}function Xe(t,e){if(t instanceof N)return t;if(t instanceof Ie)throw t;return t instanceof F?new N(404,t.message):new N(502,dt("speech",t,e))}async function Pi(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return Jl(e,async()=>{if(i?.()===!0)return null;let p=!1,g=!1,h=!1,w,S=new Promise(E=>{w=E}),v=[],f=()=>{g&&!h&&v.length>=o.quietRunFrames&&(h=!0,w())},m=e.onOutputAudio(E=>{let O=Buffer.from(E,"base64");if(O.byteLength===0)return;let R=Hl(O);if(!p){if(R)return;p=!0}if(R){v.push(O),f();return}for(let I of v)c(I);v.length=0,c(O),f()}),y=null,_,x,b;try{b=(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 O=new Promise(k=>{x=setTimeout(k,s.capMs)}),R=!1;for(;;){let k=b.next(),$=await Promise.race([k,O]);if($===void 0){R=!0,k.catch(()=>{});break}if($.done)break;let j=$.value;if(j.type==="error"){let q=j.error??{};await b.return?.();let X=typeof q.message=="string"&&q.message.length>0&&Se(q.message)?q.message:null;throw X===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(j)}`),new N(502,"the speech upstream failed while serving this request")):new N(502,`speech upstream error: ${X}`)}if(j.type==="response.completed"){y=j.response??null,g=!0,a?.(y),f(),await b.return?.();break}}if(clearTimeout(x),R)throw new N(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(y===null)throw new N(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let I=!1;if(await Promise.race([S,new Promise(k=>{_=setTimeout(()=>{I=!0,k()},o.capMs)})]),_!==void 0&&clearTimeout(_),r.voice!==void 0){let k=y[ht];if(typeof k!="string"||k!==r.voice){let $=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof k=="string"?`${ht} ${JSON.stringify(k)}`:`no ${ht} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new Tn($):new N(502,$)}}if(!p)throw new N(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(I&&!h&&v.length<1)throw new N(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return y}catch(E){throw E instanceof Tn||await Vl(t,n,b,s.returnBoundMs),E}finally{_!==void 0&&clearTimeout(_),x!==void 0&&clearTimeout(x),m()}})}function Wl(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",On)),t.write(u,a=>{a||(s+=u.byteLength,Li(e,s))}),t.writableLength>Oi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Oi} 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[ht];if(typeof a=="string"){if(!$i(a))throw Mi(a);t.addTrailers({[On]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function Kl(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Xe(s,r)}return o?!0:($r(n,new N(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 zl={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Yl="wav, pcm";async function Ni(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??ql,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new N(405,`${String(t.method)} is not supported on ${Dt}`);let u;try{u=JSON.parse((await Rn(t,o)).toString("utf8")||"{}")}catch(y){throw y instanceof re?new N(413,y.message):new N(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new N(400,"request body must be a JSON object");let a=u;for(let y of Object.keys(a))if(!zl[y])throw new N(400,`request field "${y}" 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.`,y);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new N(400,"input is required and must be a non-empty string","input");if(l.length>xi)throw new N(400,`input is ${l.length} chars \u2014 over the ${xi}-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 N(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new N(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new N(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 ${Dt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(y){throw Xe(y,r)}if(p.defect!==null)throw new N(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 g=typeof c=="string"?c:void 0;if(g!==void 0&&p.published.length>0&&!p.published.includes(g))throw new N(400,`voice ${JSON.stringify(g)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let h=a.response_format??"wav";if(h!=="wav"&&h!=="pcm")throw new N(400,`response_format ${JSON.stringify(h)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Yl} \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 N(400,"stream_format, when present, must be a string","stream_format");let w=a.speed;if(w!==void 0){if(typeof w!="number"||!Number.isFinite(w))throw new N(400,"speed, when present, must be a number","speed");if(w!==1)throw new N(400,`speed=${JSON.stringify(w)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let S=a.instructions;if(S!==void 0){if(typeof S!="string")throw new N(400,"instructions, when present, must be a string","instructions");if(S.trim().length>0)throw new N(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 jl(n.turn,n.clients,d);let v=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",v,v),!await Kl(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new N(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 N(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 N(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 f;try{f=await n.clients.speechSessionHandle(d)}catch(y){throw Xe(y,r)}let m;try{m=await n.clients.openAudioOn(f)}catch(y){throw Xe(y,r)}n.turn&&(n.turn.sessionId=m.sessionId);try{if(h==="wav"){let y=[],_=await Pi(n.clients,m,f,{model:d,text:l,...g!==void 0?{voice:g}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ri,returnBoundMs:n.turnReturnBoundMs??Ei},i,b=>y.push(b),b=>{n.turn&&(n.turn.outputSeconds=Pe(b))},r);if(_===null||i())return;let x=Buffer.concat(y);if(g===void 0){let b=_[ht];if(typeof b=="string"){if(!$i(b))throw Mi(b);e.setHeader(On,b)}}Li(n.turn,x.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Gl(x.byteLength),x]))}else{let y=Wl(e,n.turn,i,g===void 0),_;try{_=await Pi(n.clients,m,f,{model:d,text:l,...g!==void 0?{voice:g}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ri,returnBoundMs:n.turnReturnBoundMs??Ei},i,y.sink,x=>{n.turn&&(n.turn.outputSeconds=Pe(x))},r)}catch(x){let b=Xe(x,r);if(!y.started())throw b;n.turn&&(n.turn.streamError=!0),y.fail(b);return}if(_===null)return;try{await y.finish(_)}catch(x){let b=Xe(x,r);n.turn&&(n.turn.streamError=!0),y.fail(b);return}}}catch(y){throw Xe(y,r)}}catch(u){if(u instanceof re){$r(e,new N(413,u.message));return}if(u instanceof N){$r(e,u);return}throw u}}var Pn="/v1/audio/transcriptions";function Ui(t){return t===Pn}var Di="/v1/audio/models",Xl=16*1024*1024,Ql=64*1024*1024,Y=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Mr(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 Fi(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 Zl(t){if(!Fi(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 ed(t,e,n){if(t){if(t.model=ae({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 td(t,e){t&&(t.outputUnits=e.seconds)}async function nd(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??{},g=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&Se(p.message)?p.message:null;throw h===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Y(g==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Y(g==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Y(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Pe(d)),ut(l,d)}function qi(t,e){if(t instanceof Y)return t;if(t instanceof Ie)throw t;return t instanceof F?new Y(404,t.message):new Y(502,dt("transcription",t,e))}async function rd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw qi(s,r)}return o?!0:(Mr(n,new Y(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 od=new Set(["file","model","language","response_format"]);async function ji(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ql,s=n.maxAudioPartBytes??Xl;try{if(t.method!=="POST")throw new Y(405,`${String(t.method)} is not supported on ${Pn}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Y(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await En(t,o)}catch(f){throw f instanceof re?new Y(413,f.message):new Y(400,String(f instanceof Error?f.message:f))}let a=new Map;for(let f of u.keys()){if(!od.has(f))throw new Y(400,`form field "${f}" 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.`,f);a.set(f,(a.get(f)??0)+1)}for(let[f,m]of a)if(m>1)throw new Y(400,`form field "${f}" appears ${m} 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`,f);let l=u.get("model");if(l!==null&&typeof l!="string")throw new Y(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 Y(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,g=u.get("response_format")??"json";if(g!=="json")throw new Y(400,`response_format ${JSON.stringify(g)} 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 h=u.get("file");if(!(h instanceof File))throw new Y(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(h.size>s)throw new Y(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let w=new Uint8Array(await h.arrayBuffer());if(!Fi(w))throw new Y(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let S=Zl(w);if(S===null)throw new Y(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 ed(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",w.length,w.length),!await rd(n.transcriptionModels,d,e,r))return;let v=[{type:"input_audio",input_audio:{data:Buffer.from(w).toString("base64"),format:"wav"}}];try{let f=await nd(n.clients,d,v,p,n.turn?ge(n.turn):void 0,n.turn,r);td(n.turn,S),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:f}))}catch(f){throw qi(f,r)}}catch(i){if(i instanceof re){Mr(e,new Y(413,i.message));return}if(i instanceof Y){Mr(e,i);return}throw i}}var Hi="/v1/usage/requests",Bi=1e4,sd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,qe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},yt=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var Gi=1024*1024;function Lr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new qe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new qe(`"${e}" must be an array of uuid strings`);if(n.length>Bi)throw new qe(`"${e}" carries ${n.length} ids; at most ${Bi} 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"||!sd.test(s))throw new qe(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function Ji(t){return Lr(t,"inference_ids")}function Cn(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 yt(`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 yt(`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 Nn=require("@urun-sh/core");var Nr="/partners/huggingface/v1/billing/requests";function id(t){return Lr(t,"requestIds")}function ad(t){return t>=200&&t<=399}function ud(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&ad(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Vi(t,e){let n=id(t),r=await e(n);return Cn(r,n),ud(r)}var ld={"/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"};function dd(t){return ld[t]??null}var Yi=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function cd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function pd(t){return t==="surface"}function fd(t){let e=t?.ledgerFailureReason;return Yi.includes(e)?e:"unknown"}var md=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Wi=["priced","unpriced"],gd={written:Wi,already_written:Wi,skipped:md,failed:Yi},xm=Object.entries(gd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function hd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function yd(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,Ki=4096,qt=12e4,_d=250,vd=8e3,jt=[],zi=new Set,Bt=0,Ft=!1;var bd=new Set;function Sd(){return Bt===0&&jt.length===0}function kd(){if(Sd()){Ft=!1;for(let t of[...bd])t()}}function Xi(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
36
|
+
`}function xd(t){xe(process.stdout,t)}function Qi(t,e){try{t(e)}catch{}}function Zi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??xd,o=dd(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),Qi(r,Xi("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:yd(e),completed_at:e.ts,billable_outcome:hd(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,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(jt.length>=Ki){i("queue_full",`${jt.length} ledger writes are already waiting (capacity ${Ki}, ${Bt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}jt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Bt<wd&&(Bt+=1,Rd())}async function Rd(){try{for(;;){let t=Ed();if(t===void 0)return;zi.add(t);try{await Ad(t)}finally{zi.delete(t)}}}finally{Bt-=1,kd()}}function Ed(){let t=Date.now();for(;;){let e=jt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<qt)return e;wt(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 Ad(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);wt(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=cd(o);if(s!==null){wt(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=fd(o),u=Date.now()-t.queuedAt;if(Ft){wt(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(pd(i)&&u<qt){if(await Od(Id(t.attempts)),Ft||Date.now()-t.queuedAt>=qt){let a=Date.now()-t.queuedAt;wt(t,{outcome:"failed",reason:Ft?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Ft?"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}wt(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 Id(t){return Math.min(vd,_d*2**Math.max(0,t-1))}function Od(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function wt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Qi(t.report,Xi(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Fr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Td(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 oe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function J(t,e,n,r="invalid_request_error",o){oe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function qr(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Oe(r),u=i??ke(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"),oe(t,l,{error:{message:u,type:o,code:a}})}function Re(t,e,n,r){oe(t,e,{type:"error",error:{type:n,message:r}})}function _t(t,e,n){if(e==="anthropic"){oe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}oe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Pd=64*1024*1024,Ht=class extends Error{};async function ea(t,e=Pd){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Ht(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Qe(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 ra(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 $n(t){let e=ra(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ta(t){let e=$n(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:Cd(t)},completion_tokens_details:{reasoning_tokens:0}}}function Cd(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 $d(t,e){let n=ra(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Md(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 Ld(t,e){let n=Md(e);n&&(t.timing=n),t.outputSeconds=Pe(e)}function Ze(t,e){$d(t,e),Ld(t,e)}async function Un(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 oa(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 Nd(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 Mn=class extends Error{};function Ud(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 Mn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Dd(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:Ud(n.role,n.content)})}return e}function Ur(t){return it(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 Fd(t,e,n,r,o,s,i){let u=Tt(s.id),a=t.stream===!0;if(s.model=ae(t),s.stream=a,await Un(s,e,typeof t.model=="string"?t.model:void 0),a){let f;try{f=await Ct({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(m){if(m instanceof F){_t(r,"openai",m);return}if(m instanceof he){J(r,m.status,m.message);return}if(m instanceof _e||m instanceof ce){r.setHeader("retry-after","2"),J(r,503,m.message,"capacity_error");return}throw m}Fr(r);for await(let m of f.events){if(m.type==="error"){s.streamError=!0;let y=m.error,_=Oe(y),x=_??ke(s.id);_===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(m)}`),r.write(`event: error
|
|
37
|
+
data: ${JSON.stringify({error:{message:x,type:y?.type??"upstream_error",code:y?.code??null}})}
|
|
38
|
+
|
|
39
|
+
`),r.end();return}m.type==="response.completed"&&Ze(s,m.response),r.write(`event: ${String(m.type??"message")}
|
|
36
40
|
data: ${JSON.stringify(m)}
|
|
37
41
|
|
|
38
42
|
`)}r.write(`data: [DONE]
|
|
39
43
|
|
|
40
|
-
`),r.end();return}let l;try{l=
|
|
44
|
+
`),r.end();return}let l;try{l=lt(n,t)}catch(f){if(f instanceof he){J(r,f.status,f.message);return}throw f}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ae(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await lr(e,t,l,!1,ge(s))}catch(f){if(f instanceof F){_t(r,"openai",f);return}if(f instanceof he){J(r,f.status,f.message);return}if(f instanceof _e||f instanceof ce){r.setHeader("retry-after","2"),J(r,503,f.message,"capacity_error");return}throw f}let h=[],w=null;for await(let f of o.track(g,c,s)){if(h.push(f),f.type==="error"){qr(r,f,{inferenceId:s.id,operatorError:i});return}f.type==="response.completed"&&(w=f.response)}if(w==null){J(r,502,"upstream produced no response.completed event","upstream_error");return}Ze(s,w);let S=ut(h,w),v=Ye(p,it(w).length,S);if(v){J(r,502,ze(c,v),"upstream_error");return}d&&n.remember(u,l,ur(w,S),d),oe(r,200,{...w,id:u})}async function qd(t,e,n,r,o,s,i){let u=t.messages;if(!Array.isArray(u)){J(n,400,"chat/completions requires a messages array");return}let a;try{a=ni(s,t)}catch(R){if(R instanceof le){J(n,R.status,R.message);return}throw R}let l=String(t.model??"urun"),d=ys(o.id),c;try{c=Dd(u)}catch(R){if(R instanceof Mn){J(n,400,R.message);return}throw R}let p=ae(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Un(o,e,typeof t.model=="string"?t.model:void 0);let g=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:Nd(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}:{}},ge(o))}catch(R){if(R instanceof F){_t(n,"openai",R);return}if(R instanceof _e||R instanceof ce){n.setHeader("retry-after","2"),J(n,503,R.message,"capacity_error");return}throw R}if(t.stream===!0){a?Td(n):Fr(n);let R=[],I=new De,k="",$=a?new mt(a,q=>{n.write(`data: ${JSON.stringify(Qe(d,l,{content:q},null))}
|
|
41
45
|
|
|
42
|
-
`)}):null,
|
|
46
|
+
`)}):null,j=q=>{$?.flush(),n.write(q),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}})}
|
|
43
47
|
|
|
44
|
-
`),n.write(`data: ${JSON.stringify(
|
|
48
|
+
`),n.write(`data: ${JSON.stringify(Qe(d,l,{role:"assistant"},null))}
|
|
45
49
|
|
|
46
|
-
`);for await(let
|
|
50
|
+
`);for await(let Q of r.track(h,p,o)){R.push(Q);let ie=at(Q);if(Q.type==="response.output_text.delta"&&typeof Q.delta=="string")k+=Q.delta,$?$.push(Q.delta):n.write(`data: ${JSON.stringify(Qe(d,l,{content:Q.delta},null))}
|
|
47
51
|
|
|
48
|
-
`);else if(
|
|
52
|
+
`);else if(Q.type==="response.reasoning_text.delta"&&typeof Q.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(Qe(d,l,{reasoning_content:Q.delta},null))}
|
|
49
53
|
|
|
50
|
-
`);else if(
|
|
54
|
+
`);else if(ie){$?.flush();let{call:L,isNew:H}=I.add(ie),V=H?{index:ie.tool_index,id:L.id??`call_${ie.tool_index}`,type:"function",function:{name:L.name??"",arguments:ie.delta}}:{index:ie.tool_index,function:{arguments:ie.delta}};n.write(`data: ${JSON.stringify(Qe(d,l,{tool_calls:[V]},null))}
|
|
51
55
|
|
|
52
|
-
`)}else if(
|
|
56
|
+
`)}else if(Q.type==="error"){o.streamError=!0;let L=Q.error??{},H=Oe(L),V=H??ke(o.id);H===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Q)}`),j(`data: ${JSON.stringify({error:{message:V,type:L.type??"upstream_error",code:L.code??null}})}
|
|
53
57
|
|
|
54
|
-
`);return}}let
|
|
58
|
+
`);return}}let q=Ur(Ae(R)),X=Ye(g,I.size+q.length,k);if(X){o.streamError=!0,j(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ze(p,X)}})}
|
|
55
59
|
|
|
56
|
-
`);return}
|
|
60
|
+
`);return}$?.flush(),I.size===0&&q.length>0&&n.write(`data: ${JSON.stringify(Qe(d,l,{tool_calls:q},null))}
|
|
57
61
|
|
|
58
|
-
`);let
|
|
62
|
+
`);let G=I.size>0||q.length>0;n.write(`data: ${JSON.stringify(Qe(d,l,{},G?"tool_calls":"stop"))}
|
|
59
63
|
|
|
60
|
-
`);let
|
|
64
|
+
`);let $e=$n(Ae(R));Ze(o,Ae(R)),$e&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:ta(Ae(R))})}
|
|
61
65
|
|
|
62
66
|
`),n.write(`data: [DONE]
|
|
63
67
|
|
|
64
|
-
`),n.end();return}finally{
|
|
65
|
-
data: ${JSON.stringify({type:
|
|
66
|
-
|
|
67
|
-
`)};if(t.stream===!0){let R=r.track(y,c,o);Mr(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 O=0,x="",I=0,b="none",M=()=>b,B=-1,F=-1,Y=new Le,H=[],Te=()=>{b!=="none"&&(b="none",g("content_block_stop",{index:B}))},X=(V,Q)=>{Te(),b=V,B=I++,g("content_block_start",{index:B,content_block:Q})};for await(let V of R){if(n.destroyed)break;H.push(V);let Q=ot(V);if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")M()!=="thinking"&&X("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:B,delta:{type:"thinking_delta",thinking:V.delta}});else if(V.type==="response.output_text.delta"&&typeof V.delta=="string")M()!=="text"&&X("text",{type:"text",text:""}),O+=1,x+=V.delta,g("content_block_delta",{index:B,delta:{type:"text_delta",text:V.delta}});else if(Q){let{call:ge}=Y.add(Q);(M()!=="tool"||Q.tool_index!==F)&&(F=Q.tool_index,X("tool",{type:"tool_use",id:ge.id??`call_${Q.tool_index}`,name:ge.name??"",input:{}})),Q.delta&&g("content_block_delta",{index:B,delta:{type:"input_json_delta",partial_json:Q.delta}})}else if(V.type==="error"){o.streamError=!0;let ge=V.error,Fe=Ee(ge);Fe===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(V)}`),g("error",{error:{type:"api_error",message:Fe??ve(o.id)}}),n.end();return}}if(n.destroyed)return;let oe=xe(H),$=rt(oe),q=We(f,Y.size+$.length,x);if(q){o.streamError=!0,g("error",{error:{type:"api_error",message:Je(c,q)}}),n.end();return}Te();let G=[];if(Y.size===0)try{G=Cr(oe)}catch(V){o.streamError=!0;let Q=de(V,{inferenceId:o.id});Q.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(V instanceof Error?V.message:V)}`),g("error",{error:{type:"api_error",message:Q.message}}),n.end();return}I===0&&G.length===0&&(X("text",{type:"text",text:""}),Te()),G.forEach(V=>{let Q=I++;g("content_block_start",{index:Q,content_block:{...V,input:{}}}),g("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:JSON.stringify(V.input??{})}}),g("content_block_stop",{index:Q})});let De=Y.size>0||G.length>0,Xe=An(oe);Ye(o,oe),g("message_delta",{delta:{stop_reason:De?"tool_use":"end_turn"},usage:Xe?{input_tokens:Xe.input_tokens,output_tokens:Xe.output_tokens}:{output_tokens:O}}),g("message_stop",{}),n.end();return}let w="",A="",S=[],p=new Le;for await(let R of r.track(y,c,o)){S.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(w+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(A+=R.delta);let O=ot(R);if(O&&p.add(O),R.type==="error"){let x=R.error,I=x?.type==="invalid_request_error",b=Ee(x);b===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(R)}`),Se(n,I?400:502,I?"invalid_request_error":"api_error",b??ve(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=xe(S);Ye(o,m);let h;try{h=Cr(m),h.length===0&&p.size>0&&(h=Cr({output:p.items()}))}catch(R){let O=de(R,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(R instanceof Error?R.message:R)}`),Se(n,502,"api_error",O.message);return}let _=We(f,h.length,w);if(_){Se(n,502,"api_error",Je(c,_));return}let k=[],v=A||Ki(m);v&&k.push({type:"thinking",thinking:v}),(w||h.length===0)&&k.push({type:"text",text:w}),k.push(...h),re(n,200,{id:a,type:"message",role:"assistant",content:k,model:u,stop_reason:h.length>0?"tool_use":"end_turn",usage:An(m)??{input_tokens:0,output_tokens:0}})}function Td(t){be(process.stdout,t)}function Pd(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Td,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new Ge;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),y=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),g=(m,h,_,k,v)=>y?Se(c,m,k,h):z(c,m,h,_,v),w=tr(f.pathname),A=f.pathname.startsWith("/partners/"),S=w||A?{id:Rt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;S&&(c.setHeader(ls,S.id),c.once("close",()=>{let m=fs({turn:S,method:d.method??"",path:f.pathname,res:c});i(ms(m)),a?.(m),Hi({record:m,ledger:t.ledger??null,req:d})}));let p=()=>ds(f.pathname,S);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){re(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){re(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 m=f.pathname===Mi?"canonical":f.pathname===Tr?"huggingface":null;if(m){if(d.method!=="POST"){g(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let v=t.usage;if(!v){g(501,`${f.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let R=v.authorize(d),O;try{O=await Gi(d,$i)}catch(b){if(b instanceof Ft){g(413,b.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=b=>v.lookup(R,b),I;try{if(m==="canonical"){let b=Li(O),M=await x(b);En(M,b),I={requests:M}}else I=await Ni(O,x)}catch(b){if(b instanceof Ue){g(b.status,b.message,"invalid_request_error","invalid_request_error");return}throw b}re(c,200,I);return}if(d.method==="GET"&&f.pathname===bt){let v=await s(d);if(S&&(S.org=v.tenant??null),!v.openRouterModels){g(501,`GET ${bt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}re(c,200,await v.openRouterModels());return}if(f.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${Tr} and GET ${bt}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(S&&(S.org=h.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:bt}),c.end();return}re(c,200,await h.listModels());return}if(d.method==="GET"&&f.pathname===ri){if(!h.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}re(c,200,await h.listImageModels());return}if(ni(f.pathname)){if(!h.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let v={clients:h,imageModels:h.supportsImages,stats:l,turn:p(),operatorLog:u};f.pathname===bn?await fi(d,c,v):await pi(d,c,v);return}if(d.method==="GET"&&f.pathname===Ii){if(!h.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}re(c,200,await h.listSpeechToTextModels());return}if(Ai(f.pathname)){if(!h.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Rn}`,"not_implemented","not_implemented_error");return}let v={clients:h,transcriptionModels:h.supportsTranscription,stats:l,turn:p(),operatorLog:u};await Pi(d,c,v);return}if(Si(f.pathname)){if(!h.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${$t}`,"not_implemented","not_implemented_error");return}let v={clients:h,speechModels:h.supportsSpeech,stats:l,turn:p(),operatorLog:u};await Ei(d,c,v);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let _;try{_=await Gi(d)}catch(v){if(v instanceof Ft){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 k=Buffer.byteLength(JSON.stringify(_));if(f.pathname==="/v1/responses"){l.request("responses",k,k),await vd(_,h,At(h),c,l,p(),u);return}if(f.pathname==="/v1/chat/completions"){l.request("chat_completions",k,k),await bd(_,h,c,l,p(),d.headers[xr],u);return}if(f.pathname==="/v1/systemone"){l.request("systemone",k,k),await kd(_,h,c,l,p(),u);return}if(f.pathname==="/v1/messages"){l.request("messages",k,k),await Od(_,h,c,l,p(),u);return}if(f.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",k,k),Se(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(m=>{let h=String(m instanceof Error?m.message:m);if(!c.headersSent){let v=o?.(m)??null;if(v){v.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${v.operatorDetail}`),g(v.status,h,v.openaiType,v.anthropicType,v.code);return}if(m instanceof Tn.SessionAllocationError){let O=ln(m.code);if(O){let x=m.retryAfterSeconds??(O.status===429?30:void 0);x!==void 0&&c.setHeader("Retry-After",String(x)),g(O.status,Ot(O,m.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof Tn.SessionFailedError){let O=dn(m);if(O){let x=O.status===429?30:void 0;x!==void 0&&c.setHeader("Retry-After",String(x)),g(O.status,Ot(O,m.status.sessionId?`session ${m.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof ft){g(502,h,"upstream_error","api_error");return}if(m instanceof ye){m.retryable&&c.setHeader("Retry-After","1");let O=de(m,{inferenceId:S?.id??null});O.redacted&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),g(502,O.message,"upstream_error","api_error",m.code);return}if(m instanceof $e){c.setHeader("Retry-After",String(m.retryAfterSeconds)),g(m.status,h,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let R=de(m,{inferenceId:S?.id??null});R.redacted&&u(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),g(500,R.message,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let _=m instanceof ye?m.code:null,k=de(m,{inferenceId:S?.id??null});k.redacted&&u(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:_e(m)}`),c.destroyed||(y?c.write(`event: error
|
|
68
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:
|
|
69
|
-
|
|
70
|
-
`):c.write(`data: ${JSON.stringify({error:{message:
|
|
71
|
-
|
|
72
|
-
`)),c.end()})}}function
|
|
73
|
-
`),null):{catalogUrl:r,anonKey:o}}function
|
|
74
|
-
`),o(127)})})}function
|
|
75
|
-
`)}async function
|
|
76
|
-
`)),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=
|
|
77
|
-
`),
|
|
78
|
-
`),0):(
|
|
79
|
-
`),1)}if(n==="proxy"){let o=e??
|
|
80
|
-
`):u.reason&&
|
|
81
|
-
`);let d=null,c=null,
|
|
82
|
-
`)}),
|
|
83
|
-
`),d=
|
|
84
|
-
`),
|
|
85
|
-
`),
|
|
86
|
-
`),
|
|
68
|
+
`),n.end();return}finally{$?.flush(),$?.dispose()}}let w="",S="",v=[],f=new De;for await(let R of r.track(h,p,o)){v.push(R),R.type==="response.output_text.delta"&&typeof R.delta=="string"&&(w+=R.delta),R.type==="response.reasoning_text.delta"&&typeof R.delta=="string"&&(S+=R.delta);let I=at(R);if(I&&f.add(I),R.type==="error"){qr(n,R,{inferenceId:o.id,operatorError:i});return}}let m=Ae(v);Ze(o,m);let y=Ur(m),_=y.length>0?y:Ur({output:f.items()}),x=Ye(g,_.length,w);if(x){J(n,502,ze(p,x),"upstream_error");return}let b=_.map(({index:R,...I})=>I),E={role:"assistant",content:w||null},O=S||oa(m);O&&(E.reasoning_content=O),b.length>0&&(E.tool_calls=b),oe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:E,finish_reason:b.length>0?"tool_calls":"stop"}],usage:ta(m)})}var sa="sense-latest";async function jd(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:sa,u=ae({model:i});if(o.model=u,o.stream=!1,t.state===void 0||t.state===null){J(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){J(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){J(n,400,"systemone media, when present, must be an array");return}let l=await ia(t,i,u,e,n,r,o,s);l!==null&&oe(n,200,l.answer)}async function ia(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 Un(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},ge(i))}catch(v){if(v instanceof F)return _t(o,"openai",v),null;if(v instanceof _e||v instanceof ce)return o.setHeader("retry-after","2"),J(o,503,v.message,"capacity_error"),null;throw v}a.dial_ms=Math.round(performance.now()-c);let p=[],g=null;try{for await(let v of s.track(d,n,i))if(g===null&&(g=performance.now(),a.first_event_ms=Math.round(g-c)),p.push(v),v.type==="error")return qr(o,v,{inferenceId:i.id,operatorError:u}),null}catch(v){if(v instanceof F)return g!==null&&(a.stream_ms=Math.round(performance.now()-g)),_t(o,"openai",v),null;if(v instanceof _e||v instanceof ce)return g!==null&&(a.stream_ms=Math.round(performance.now()-g)),o.setHeader("retry-after","2"),J(o,503,v.message,"capacity_error"),null;throw g!==null&&(a.stream_ms=Math.round(performance.now()-g)),v}g!==null&&(a.stream_ms=Math.round(performance.now()-g));let h=Ae(p);if(h==null)return J(o,502,"upstream produced no response.completed event","upstream_error"),null;Ze(i,h);let w=ut(p,h),S;try{S=JSON.parse(w)}catch{return J(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(S===null||typeof S!="object"||Array.isArray(S))return J(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"timing"in S){let v=S.timing;if(typeof v=="object"&&v!==null&&!Array.isArray(v)&&"question_fwd_ms"in v&&"head_ms"in v){let f=m=>typeof m=="number"&&Number.isFinite(m)&&m>=0?Math.round(m):null;a.question_fwd_ms=f(v.question_fwd_ms),a.head_ms=f(v.head_ms)}}return{answer:S,completed:h}}async function Bd(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:sa,u=ae({model:i});o.model=u,o.stream=!1;let a;try{a=ai(t,i)}catch(p){if(p instanceof M){J(n,400,p.message);return}throw p}let l=await ia(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=di(a.specs,l.answer)}catch(p){if(p instanceof ye){J(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;oe(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function Hd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Gt=class extends Error{};function Ln(t){return new Gt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function Gd(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 Jd(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 Gt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Vd(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Ln(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Ln(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Wd(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 Ln(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:Vd(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw Ln(u)}}return s(),r}function Dr(t){return it(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 Kd(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Re(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){Re(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Re(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"))){Re(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=ws(o.id),l=[],d;try{t.system&&l.push({role:"system",content:Hd(t.system)});for(let E of i)l.push(...Wd(E));d=Jd(t.tool_choice)}catch(E){if(E instanceof Gt){Re(n,400,"invalid_request_error",E.message);return}throw E}let c=ae(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Un(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,g;try{g=await e.createResponse({model:t.model,input:l,stream:!0,tools:Gd(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ge(o))}catch(E){if(E instanceof F){_t(n,"anthropic",E);return}if(E instanceof _e||E instanceof ce){n.setHeader("retry-after","2"),Re(n,503,"capacity_error",E.message);return}throw E}let h=(E,O)=>{n.destroyed||n.write(`event: ${E}
|
|
69
|
+
data: ${JSON.stringify({type:E,...O})}
|
|
70
|
+
|
|
71
|
+
`)};if(t.stream===!0){let E=r.track(g,c,o);Fr(n),h("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,R="",I=0,k="none",$=()=>k,j=-1,q=-1,X=new De,G=[],$e=()=>{k!=="none"&&(k="none",h("content_block_stop",{index:j}))},Q=(W,Z)=>{$e(),k=W,j=I++,h("content_block_start",{index:j,content_block:Z})};for await(let W of E){if(n.destroyed)break;G.push(W);let Z=at(W);if(W.type==="response.reasoning_text.delta"&&typeof W.delta=="string")$()!=="thinking"&&Q("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:j,delta:{type:"thinking_delta",thinking:W.delta}});else if(W.type==="response.output_text.delta"&&typeof W.delta=="string")$()!=="text"&&Q("text",{type:"text",text:""}),O+=1,R+=W.delta,h("content_block_delta",{index:j,delta:{type:"text_delta",text:W.delta}});else if(Z){let{call:we}=X.add(Z);($()!=="tool"||Z.tool_index!==q)&&(q=Z.tool_index,Q("tool",{type:"tool_use",id:we.id??`call_${Z.tool_index}`,name:we.name??"",input:{}})),Z.delta&&h("content_block_delta",{index:j,delta:{type:"input_json_delta",partial_json:Z.delta}})}else if(W.type==="error"){o.streamError=!0;let we=W.error,Be=Oe(we);Be===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(W)}`),h("error",{error:{type:"api_error",message:Be??ke(o.id)}}),n.end();return}}if(n.destroyed)return;let ie=Ae(G),L=it(ie),H=Ye(p,X.size+L.length,R);if(H){o.streamError=!0,h("error",{error:{type:"api_error",message:ze(c,H)}}),n.end();return}$e();let V=[];if(X.size===0)try{V=Dr(ie)}catch(W){o.streamError=!0;let Z=pe(W,{inferenceId:o.id});Z.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(W instanceof Error?W.message:W)}`),h("error",{error:{type:"api_error",message:Z.message}}),n.end();return}I===0&&V.length===0&&(Q("text",{type:"text",text:""}),$e()),V.forEach(W=>{let Z=I++;h("content_block_start",{index:Z,content_block:{...W,input:{}}}),h("content_block_delta",{index:Z,delta:{type:"input_json_delta",partial_json:JSON.stringify(W.input??{})}}),h("content_block_stop",{index:Z})});let je=X.size>0||V.length>0,et=$n(ie);Ze(o,ie),h("message_delta",{delta:{stop_reason:je?"tool_use":"end_turn"},usage:et?{input_tokens:et.input_tokens,output_tokens:et.output_tokens}:{output_tokens:O}}),h("message_stop",{}),n.end();return}let w="",S="",v=[],f=new De;for await(let E of r.track(g,c,o)){v.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(w+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(S+=E.delta);let O=at(E);if(O&&f.add(O),E.type==="error"){let R=E.error,I=R?.type==="invalid_request_error",k=Oe(R);k===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(E)}`),Re(n,I?400:502,I?"invalid_request_error":"api_error",k??ke(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let m=Ae(v);Ze(o,m);let y;try{y=Dr(m),y.length===0&&f.size>0&&(y=Dr({output:f.items()}))}catch(E){let O=pe(E,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(E instanceof Error?E.message:E)}`),Re(n,502,"api_error",O.message);return}let _=Ye(p,y.length,w);if(_){Re(n,502,"api_error",ze(c,_));return}let x=[],b=S||oa(m);b&&x.push({type:"thinking",thinking:b}),(w||y.length===0)&&x.push({type:"text",text:w}),x.push(...y),oe(n,200,{id:a,type:"message",role:"assistant",content:x,model:u,stop_reason:y.length>0?"tool_use":"end_turn",usage:$n(m)??{input_tokens:0,output_tokens:0}})}function zd(t){xe(process.stdout,t)}function Yd(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??zd,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new We;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),g=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(m,y,_,x,b)=>g?Re(c,m,x,y):J(c,m,y,_,b),w=ar(p.pathname),S=p.pathname.startsWith("/partners/"),v=w||S?{id:Ot(),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;v&&(c.setHeader(gs,v.id),c.once("close",()=>{let m=_s({turn:v,method:d.method??"",path:p.pathname,res:c});i(vs(m)),a?.(m),Zi({record:m,ledger:t.ledger??null,req:d})}));let f=()=>hs(p.pathname,v);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){oe(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){oe(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let m=p.pathname===Hi?"canonical":p.pathname===Nr?"huggingface":null;if(m){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let b=t.usage;if(!b){h(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=b.authorize(d),O;try{O=await ea(d,Gi)}catch(k){if(k instanceof Ht){h(413,k.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=k=>b.lookup(E,k),I;try{if(m==="canonical"){let k=Ji(O),$=await R(k);Cn($,k),I={requests:$}}else I=await Vi(O,R)}catch(k){if(k instanceof qe){h(k.status,k.message,"invalid_request_error","invalid_request_error");return}throw k}oe(c,200,I);return}if(d.method==="GET"&&p.pathname===Rt){let b=await s(d);if(v&&(v.org=b.tenant??null),!b.openRouterModels){h(501,`GET ${Rt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}oe(c,200,await b.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Nr} and GET ${Rt}`,"invalid_request_error","not_found_error");return}let y=await s(d);if(v&&(v.org=y.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:Rt}),c.end();return}oe(c,200,await y.listModels());return}if(d.method==="GET"&&p.pathname===fi){if(!y.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}oe(c,200,await y.listImageModels());return}if(pi(p.pathname)){if(!y.supportsImages){h(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let b={clients:y,imageModels:y.supportsImages,stats:l,turn:f(),operatorLog:u};p.pathname===An?await ki(d,c,b):await Si(d,c,b);return}if(d.method==="GET"&&p.pathname===Di){if(!y.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}oe(c,200,await y.listSpeechToTextModels());return}if(Ui(p.pathname)){if(!y.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Pn}`,"not_implemented","not_implemented_error");return}let b={clients:y,transcriptionModels:y.supportsTranscription,stats:l,turn:f(),operatorLog:u};await ji(d,c,b);return}if(Ci(p.pathname)){if(!y.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Dt}`,"not_implemented","not_implemented_error");return}let b={clients:y,speechModels:y.supportsSpeech,stats:l,turn:f(),operatorLog:u};await Ni(d,c,b);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let _;try{_=await ea(d)}catch(b){if(b instanceof Ht){h(413,b.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=Buffer.byteLength(JSON.stringify(_));if(p.pathname==="/v1/responses"){l.request("responses",x,x),await Fd(_,y,Pt(y),c,l,f(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",x,x),await qd(_,y,c,l,f(),d.headers[Tr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",x,x),await jd(_,y,c,l,f(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",x,x),await Bd(_,y,c,l,f(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",x,x),await Kd(_,y,c,l,f(),u);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",x,x),Re(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}h(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(m=>{let y=String(m instanceof Error?m.message:m);if(!c.headersSent){let b=o?.(m)??null;if(b){b.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${b.operatorDetail}`),h(b.status,y,b.openaiType,b.anthropicType,b.code);return}if(m instanceof Nn.SessionAllocationError){let O=fn(m.code);if(O){let R=m.retryAfterSeconds??(O.status===429?30:void 0);R!==void 0&&c.setHeader("Retry-After",String(R)),h(O.status,$t(O,m.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof Nn.SessionFailedError){let O=mn(m);if(O){let R=O.status===429?30:void 0;R!==void 0&&c.setHeader("Retry-After",String(R)),h(O.status,$t(O,m.status.sessionId?`session ${m.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(m instanceof yt){h(502,y,"upstream_error","api_error");return}if(m instanceof ve){m.retryable&&c.setHeader("Retry-After","1");let O=pe(m,{inferenceId:v?.id??null});O.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:be(m)}`),h(502,O.message,"upstream_error","api_error",m.code);return}if(m instanceof Ue){c.setHeader("Retry-After",String(m.retryAfterSeconds)),h(m.status,y,m.status===429?"capacity_error":"upstream_error",m.status===429?"rate_limit_error":"overloaded_error",m.code);return}let E=pe(m,{inferenceId:v?.id??null});E.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:be(m)}`),h(500,E.message,"proxy_error","api_error","proxy_error");return}v&&(v.streamError=!0);let _=m instanceof ve?m.code:null,x=pe(m,{inferenceId:v?.id??null});x.redacted&&u(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${m instanceof Error?`${m.name}: ${m.message}`:be(m)}`),c.destroyed||(g?c.write(`event: error
|
|
72
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:x.message}})}
|
|
73
|
+
|
|
74
|
+
`):c.write(`data: ${JSON.stringify({error:{message:x.message,type:"upstream_error",code:_}})}
|
|
75
|
+
|
|
76
|
+
`)),c.end()})}}function aa(t){let{clients:e,apiKey:n}=t,r=(0,na.createServer)(Yd(t)),o=Es(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=Ir(r,{resolver:ii(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(u=>(o.close(),s(),i(u))),fs(r,{clients:e,apiKey:n}),r}var Dn=require("@urun-sh/core/internal");var Xd={ensureWebRTC:Dn.ensureNodeWebRTC,webrtcUnavailableReason:Dn.nodeWebRTCUnavailableReason,audioBackend:Wt};async function ua(t=Xd){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 Zd(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?gn(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
|
|
77
|
+
`),null):{catalogUrl:r,anonKey:o}}function ec(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:Zd(U.default.env,r=>U.default.stderr.write(r)),decisionPool:qo(U.default.env,U.default.env.HOSTNAME)??void 0},n=Go(e);return{router:n,decision:e.decisionPool?Jo(e,n):null}}async function la(t,e,n){let r=(0,jr.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{U.default.stderr.write(`failed to launch ${t}: ${String(s)}
|
|
78
|
+
`),o(127)})})}function da(){return Ds(U.default.env,C,Ee.existsSync)}function pa(t){for(let[e,n]of Object.entries(gr(t)))U.default.stdout.write(`export ${e}=${n}
|
|
79
|
+
`)}async function ca(t,e){let n=ct(U.default.env),r=e?yr(n):void 0,{router:o,decision:s}=ec(n);s&&(s.boot().then(()=>s.reap()).catch(c=>U.default.stderr.write(`[decision-pool] boot FAILED: ${String(c instanceof Error?c.message:c)}
|
|
80
|
+
`)),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,Ee.mkdirSync)(Br.default.dirname(i),{recursive:!0})}(0,Ee.appendFileSync)(i,d)},a=aa({clients:Vo(o,void 0,void 0,s??void 0,jo(U.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(Ks(t,await wr(t))):d}let l=a.address().port;return e&&(U.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${l}/v1
|
|
81
|
+
`),pa(l)),{port:l,close:async()=>{s&&await s.drain(5e3).catch(()=>{});let d=new Promise(c=>a.close(()=>c()));a.closeAllConnections(),await d,await o.closeAll(),s&&await s.close()}}}async function tc(){let t=U.default.argv.slice(2),e=qs(t),n=t.shift()??"proxy";if(n==="env")return pa(js(e??hr(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await ua();return o?(U.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
|
|
82
|
+
`),0):(U.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
|
|
83
|
+
`),1)}if(n==="proxy"){let o=e??hr(t),s=await ca(o,!0);return await new Promise(i=>{U.default.once("SIGINT",i),U.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(hn).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let f=ct(U.default.env);return la("pi",["-e",da(),...Ns(f.appId,t)],U.default.env)}if(r==="omp"){let f=ct(U.default.env);return la("omp",["-e",da(),...Us(f.appId,t)],U.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 f=hn[r];if(!f)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(hn).join(" | ")} \u2014 or \`-- <cmd>\``);o=f.bin,s=[...f.args??[],...t],i=f.env}let u=await Hs(e,yr(ct(U.default.env))),a=null,l=u.port;u.mode==="reuse"?U.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})
|
|
84
|
+
`):u.reason&&U.default.stderr.write(`urun compat: ${u.reason}
|
|
85
|
+
`);let d=null,c=null,p=null,g=null;u.mode!=="reuse"&&(a=await ca(u.port,!1),l=a.port,g=_r(l),(0,Ee.mkdirSync)(Br.default.dirname(g),{recursive:!0}),p=(0,Ee.createWriteStream)(g,{flags:"a"}),c=Vs({streams:U.default,note:f=>(0,Ee.appendFileSync)(g,f)}).uninstall,p.on("error",f=>{d?.(),d=null,xe(U.default.stderr,`urun compat: proxy log ${g} failed: ${String(f)} \u2014 proxy output continues on the terminal
|
|
86
|
+
`)}),U.default.stdout.write(`urun openai proxy on http://127.0.0.1:${l}/v1 \u2014 proxy logs: ${g}
|
|
87
|
+
`),d=Gs(p)),r==="codex"&&(s=Ls(l,ct(U.default.env).appId,s));let h=(0,jr.spawn)(o,s,{stdio:"inherit",env:Ms(U.default.env,l,i)}),w=g!==null?Ws({logPath:g,appendSync:Ee.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:f=>U.default.stderr.write(f),killChild:()=>h.kill("SIGTERM"),exit:f=>U.default.exit(f),proc:U.default}):null,S=await new Promise(f=>{h.once("exit",m=>f(m??1)),h.once("error",m=>{d?.(),d=null,xe(U.default.stderr,`failed to launch ${o}: ${String(m)}
|
|
88
|
+
`),f(127)})});w?.();let v=null;try{a&&await a.close()}catch(f){v=f}finally{d?.(),d=null,c?.(),c=null,p?.end()}return v!==null&&xe(U.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${S} preserved): ${String(v instanceof Error?v.message:v)}
|
|
89
|
+
`),S}}tc().then(t=>U.default.exit(t),t=>{U.default.stderr.write(`${String(t instanceof Error?t.message:t)}
|
|
90
|
+
`),U.default.exit(1)});
|