@urun-sh/openai 0.6.28 → 0.6.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-AEMDPBN7.js → chunk-7E2KNW2C.js} +1 -1
- package/dist/{chunk-W3BULR2V.js → chunk-LCW3OUIV.js} +1 -1
- package/dist/chunk-RUJPI6BV.js +62 -0
- package/dist/hosted/bin.cjs +37 -37
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +32 -32
- package/dist/hosted/index.d.cts +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +1 -1
- package/dist/proxy/cli.cjs +46 -46
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +25 -25
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/dist/{responses-turn-Cxfv-oXb.d.ts → responses-turn-BGb_XPOa.d.ts} +4 -0
- package/dist/{responses-turn-BFURb0jK.d.cts → responses-turn-DXrwiPJh.d.cts} +13 -0
- package/package.json +1 -1
- package/dist/chunk-ZWFOK53M.js +0 -62
package/dist/proxy/cli.cjs
CHANGED
|
@@ -1,81 +1,81 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ai=Object.create;var mr=Object.defineProperty;var Ii=Object.getOwnPropertyDescriptor;var Oi=Object.getOwnPropertyNames;var Ti=Object.getPrototypeOf,Pi=Object.prototype.hasOwnProperty;var Ci=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Oi(e))!Pi.call(t,o)&&o!==n&&mr(t,o,{get:()=>e[o],enumerable:!(r=Ii(e,o))||r.enumerable});return t};var Be=(t,e,n)=>(n=t!=null?Ai(Ti(t)):{},Ci(e||!t||!t.__esModule?mr(n,"default",{value:t,enumerable:!0}):n,t));var Mi=()=>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,O=Mi();var lr=require("child_process"),pe=require("fs"),cr=Be(require("path"),1),C=Be(require("process"),1);var ie=require("@urun-sh/core");function gr(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 hr(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 yr(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 Li="llm-resp";async function*hn(t,e){let n=`${Li}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let u of i.tool_calls){let a=typeof u.index=="number"?u.index:0,d=o.get(a)??{};u.id&&(d.id=u.id),u.function?.name&&(d.name=u.function.name),o.set(a,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${a}`,tool_index:a,call_id:d.id,name:d.name,delta:u.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield yr(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var xt=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}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=hr(e,n,this.consumerId);return this.write(r),hn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=gr(e,n,r,this.consumerId);return this.write(o),hn(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var _r=0;function $i(){return _r+=1,`req_${Date.now().toString(36)}_${_r.toString(36)}`}var Rt=class{transport;constructor(e){this.transport=new xt(e)}responses={create:async e=>{let n=$i(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var br="audio",yn=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 Sr(t,e,n=1e4){let r=new yn(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(br).attach(o);let s=await Ui(t,n);return await r.startInbound(s),r}function Ui(t,e){let n=t.stream(br);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 wr="rt-video-in",vr=256e3;function kr(t){let e=t.stream(wr),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${wr}') 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>vr)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${vr}-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 Ni=24e3,tt=480,Di=111;async function Fi(){let t=await import("opusscript"),e=t.default??t;return new e(Ni,1,2048)}async function Et(){let t=await import("werift"),e=await Fi();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 d=0;for(;a.length-d>=tt;){let l=a.subarray(d,d+tt);d+=tt;let c=Buffer.from(l.buffer,l.byteOffset,l.byteLength),h=e.encode(c,tt);o=o+1&65535,s=s+tt>>>0;let f=new t.RtpHeader({version:2,payloadType:Di,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),p=new t.RtpPacket(f,h);n.writeRtp(p)}i=a.slice(d)}}},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 xr(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,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 At=require("@urun-sh/core"),_n="rt-video-out";var Bi="h264";function qi(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 ji(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;qi(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 Rr="urun.videoOut.v2-ws";function Er(t){let e=t.stream(_n);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${_n}') 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 d of r)d(a)},i=!1,u=async()=>{for await(let a of e.messages()){if(!(a instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${_n}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=ji(a)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let a of o)a()};return{codec:Bi,onOutputFrame:a=>(n.add(a),i||(i=!0,u().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(a)),onLaneError:a=>(r.add(a),()=>r.delete(a)),onEnd:a=>(o.add(a),()=>o.delete(a))}}var Ar={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},qe=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Ir(t){let e=t.t;if(typeof e!="string"||!(e in Ar))throw new qe(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ar).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 Gi(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new qe(`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 qe(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Ir(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new qe(`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 Ir(t)}function Or(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Hi(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 Tr(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 Or(e);let s=o.next();if(e!==void 0&&await Hi(s,e)==="aborted")throw s.catch(()=>{}),Or(e);let i=await s;if(i.done)return;yield Gi(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Pr=require("@urun-sh/core"),wn=2;function Vi(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Ji(t){let e=t?.type;return e==="response.completed"||e==="error"}function Cr(t){return async function(n,r){return(async function*(){for(let s=1;s<=wn;s++){let{app:i,entry:u,identity:a}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(u)??null,identity:a});let d=!1,l=!1;try{let c=await t.createStream(u,n);for await(let h of c){if(Ji(h)&&(d=!0),Vi(h)){if(s>1)continue}else l=!0;yield h}}catch(c){if(c instanceof Pr.SessionFailedError&&(c.kind==="never-live"||c.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,u,c)}catch{}throw c}if(s<wn&&!l){await t.evict(i,u);continue}throw c}if(d)return;if(s<wn&&!l){await t.evict(i,u);continue}return}})()}}var uo=require("crypto");var se=class extends Error{name="ModelPriceError"},vn="per_million_input_tokens",bn="per_million_output_tokens",Lr="model_id,variant,unit,price_usd,effective_at,expires_at",Mr={per_request:!0,per_minute:!0,per_output_unit:!0},Wi=5e3;function Ki(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new se(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function $r(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new se(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function zi(t,e,n){return t===null?null:$r(t,e,n)}function Yi(t,e){if(t===vn)return"input";if(t===bn)return"output";if(typeof t=="string"&&Object.hasOwn(Mr,t))return null;throw new se(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${vn} | ${bn}) nor a known GPU-time unit (${Object.keys(Mr).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 Xi(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 Sn(t,e){return`${t}\0${e}`}function Qi(t){if(!Array.isArray(t))throw new se(`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 se(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of Lr.split(","))if(!Object.hasOwn(s,d))throw new se(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=Yi(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new se(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new se(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:Ki(s.price_usd,o),effective_at:$r(s.effective_at,o,"effective_at"),expires_at:zi(s.expires_at,o,"expires_at")})}return e}function Ur(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 d=r.get(a.model_id);d||(d=new Map,r.set(a.model_id,d),o.set(a.model_id,new Map));let l=a.variant??"",c=d.get(l);c||(c={input:[],output:[]},d.set(l,c),o.get(a.model_id).set(l,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let s=[],i=[];for(let[a,d]of r){let l=d.get(""),c=(h,f,p)=>{let _=h&&h.length>0?h:l?.[f];if(!_||_.length===0)return null;let m=Xi(_,f);return"reason"in m?m:m.rate.usd===0?f==="output"&&p!==null&&n?.has(Sn(a,p))?m.rate:{reason:`the ${f} 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`}:m.rate};for(let[h,f]of o.get(a)){let p=d.get(h),_=c(p?.input,"input",f),m=c(p?.output,"output",f);if(_!==null&&"reason"in _){i.push({model_id:a,variant:f,reason:_.reason});continue}if(m!==null&&"reason"in m){i.push({model_id:a,variant:f,reason:m.reason});continue}_===null||m===null||s.push({model_id:a,variant:f,pricing:{input:_.usd,output:m.usd}})}}let u=(a,d)=>a.model_id.localeCompare(d.model_id)||(a.variant===null?1:0)-(d.variant===null?1:0)||(a.variant??"").localeCompare(d.variant??"");return{prices:s.sort(u),refusals:i.sort(u)}}function nt(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 rt={prices:[],refusals:[]};async function Nr(t){let e=t.fetchImpl??fetch,n=`${vn},${bn}`,r=await e(`${t.catalogUrl}/model_prices?select=${Lr}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Wi)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Qi(await r.json())}var W=class extends Error{},Zi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function ea(t){if(typeof t!="string")return!1;let e=Zi.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 ta(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 d=u;for(let c of["model_id","variant","app_slug","function"])if(typeof d[c]!="string"||d[c].length===0)throw new W(`catalog shared endpoints[${a}] (${JSON.stringify(d)}) has no valid "${c}"`);let l=(c,h)=>{if(d[c]!==void 0&&d[c]!==null&&!h)throw new W(`catalog shared endpoints[${a}] (${d.model_id}:${d.variant}) carries a malformed "${c}": ${JSON.stringify(d[c])}`)};l("ready",typeof d.ready=="boolean"),l("ready_runtimes",typeof d.ready_runtimes=="number"&&Number.isInteger(d.ready_runtimes)&&d.ready_runtimes>=0),l("ready_since",ea(d.ready_since));for(let c of["model_id","variant"]){let h=d[c];if(h.includes(":"))throw new W(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(h)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return l("output_free",typeof d.output_free=="boolean"),d});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 je(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Dr(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(d=>d.model_id===o);if(u.length===0)return null;if(s!==void 0){let d=u.find(l=>l.variant===s);return d?{shared_org_id:t.shared_org_id,endpoint:d}:null}if(u.length===1)return{shared_org_id:t.shared_org_id,endpoint:u[0]};let a=u.filter(d=>d.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(d=>d.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:a[0]}}async function Fr(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 ta(await r.json())}function he(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ot="/partners/openrouter/models",na={chat:!0,code:!0,agent:!0,vl:!0},Br={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ra(t){let e=t.toLowerCase();return Object.hasOwn(Br,e)?Br[e]:null}var qr={"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 oa(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(qr,o)?qr[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 jr={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Gr={2:"Llama2",3:"Llama3"};function sa(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(jr,s))return jr[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Gr,i))return Gr[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var ia=["context_length","max_model_len"];function aa(t){let e=ia.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 Ot(t){let e=t.map(aa),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function ua(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(ua),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function da(t,e){let n=e.filter(o=>he(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return It(n);let r=e.filter(o=>he(o.model_id)===t);return r.length>0?It(r):null}function It(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:la(t),matches:t}:null}function la(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")}}function Jr(t){return 0}function Ie(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 Tt(t,e,n){let r=da(t,e);if(!r)return Ie({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Ot(s),u=nt(o.model_id,o.variant,n),a=Wr(o,s),d=kn(s);return Ie({id:t,object:"model",created:Jr(o),owned_by:"urun",...i!==null?{context_length:i}:{},...u!==null?{pricing:u}:{},...a.published.length>0?{voices:[...a.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var ca=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Wr(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:[...ca],defect:o}:{published:[],defect:o}}function xn(t){let e=t.length>0?It(t):null;return e===null?{published:[],defect:null}:Wr(e.row,e.matches)}function Hr(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 Vr(t){return{input:[{type:"prompt",unit:"token",cost_usd:Hr(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Hr(t.output)}]}}function pa(t,e,n,r){if(e.length===0)return null;let o=It(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||na[s.task]!==!0)return null;let u=Ot(i),a=nt(s.model_id,s.variant,n),d=sa(s.hf_repo),l={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return u!==null&&(l.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:Jr(s),quantization:ra(s.variant),...d!==null?{tokenizer:d}:{},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:Vr(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:l,...a?{pricing:Vr(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Kr(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?je(t):[];if(s.length>0){let d=s.filter(l=>l.ready===void 0);if(d.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(d.length>0){let l=d.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${l} carry no ready field and are declared not ready`)}}let i={datacenters:oa(t?.regions,o),compliance:t?.compliance??null},u=[],a=new Set;for(let d of s){let l=`${d.model_id}:${d.variant}`;if(a.has(l))continue;a.add(l);let c=pa(d,e.filter(h=>h.model_id===d.model_id&&h.variant===d.variant),n,i);c&&u.push(c)}return{data:u}}var eo="https://api.urun.sh/v1",N=class extends Error{},J=class extends Error{},En="urs1.";function zr(t,e){return En+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function fa(t){if(!t.startsWith(En))return null;try{let e=JSON.parse(Buffer.from(t.slice(En.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 to(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 Yr(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ga(t);return e===null?[]:[e]}function Rn(t,e,n,r,o){if(!o)throw new W(`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 W(`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 W(`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 Xr(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 W(`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 no="shared:",Qr="speech:";function ke(t){return t.sharedApp?no+t.appSlug:t.appSlug}function Ct(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function be(t,e){let n=e.filter(s=>he(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>he(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function ma(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function ga(t){let e=t.map(ma),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Zr={stt:"stt",tts:"tts"};function Se(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Zr[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Zr[e]:null}function ha(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 Error(`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 Pt=6e4,Mt=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Pt;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??Pt;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Pt;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Pt;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 se)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
|
|
3
|
-
`),
|
|
4
|
-
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(
|
|
5
|
-
`);let a=(n?je(n):[]).map(d=>{let l=s.filter(m=>m.model_id===d.model_id&&m.variant===d.variant),c=Ot(l),h=kn(l),f=nt(d.model_id,d.variant,i),p=xn(l);return Ie({id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",...c!==null?{context_length:c}:{},...f!==null?{pricing:f}:{},...p.published.length>0?{voices:[...p.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(d=>Tt(d,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Kr(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=Rn(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Xr(`${r.modelId}:${r.variant}`,s).includes(n)}return Yr(be(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Se(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Se(be(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Se(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Se(be(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Se(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Se(be(n.appSlug,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):be(n.appSlug,r);return ha(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):be(n.appSlug,r);return xn(o)}async imageModelList(){let e=await this.catalogRows(),n=rt,r=[];for(let s of await this.availableIds()){let i=Yr(be(s,e));i.length!==0&&r.push(Ie({...Tt(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of je(o)){let i=Rn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Xr(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Ie({id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=rt,r=[];for(let s of await this.availableIds())Se(be(s,e))==="stt"&&r.push(Tt(s,e,n));let o=await this.sharedBlock();if(o)for(let s of je(o)){let i=Rn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Se(i)!=="stt")continue;let u=Ie({id:`${s.model_id}:${s.variant}`,object:"model",created:0,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 Ge=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)}},st=class extends Ge{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},An=class extends Ge{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},Oe=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},$t=class{constructor(e){this.opts=e;if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}opts;slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}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};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.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n)),this.pump();return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new st;this.lastDemandAt=this.now();let e=this.opts.acquireTimeoutMs??6e5,n=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new st;if(!this.slots.some(a=>a.state==="queued")&&this.slots.length<this.opts.max){this.openForDemand();continue}let s=n+e-Date.now();if(s<=0)throw new An(e);let i,u={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(a=>{u.resolve=a,this.waiters.push(u)}),new Promise(a=>{i=setTimeout(a,s)})])}finally{clearTimeout(i);let a=this.waiters.indexOf(u);a!==-1&&this.waiters.splice(a,1),u.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new st}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();return n||(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max&&this.openForDemand(),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())}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,o)=>(r.idleSince??0)-(o.idleSince??0)||o.slot.index-r.slot.index);for(let r of n)this.endSlot(r)}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 In=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)}},Nt=33e4;function ro(t,e=Nt){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((d,l)=>{o=l}),i=setTimeout(()=>o(new Ut),e),u;try{u=await Promise.race([r.next(),s])}catch(d){throw d instanceof J||d instanceof In.SessionFailedError&&d.kind==="transport-failed"?d:d instanceof Ut?(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(d instanceof Error?d.message:d)}`,"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 Ut=class extends Error{constructor(){super("stream idle timeout")}};function oo(t){return t instanceof ye?!1:t instanceof J?!0:t instanceof In.SessionFailedError?t.kind==="transport-failed":!1}var ya=3,_a="llm",wa=new Set(["paused","error"]);function so(t,e){let n=t.doc(_a),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)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 s=null,i=!1,u=new Set,a=[],d=l=>{if(!s){s=l;for(let c of[...u])c(l);u.clear()}};return r&&a.push(n.onConnectionState(l=>{i&&(l.consecutiveFailures<ya||d(new J(`the pooled session for app "${e}" is gone: its doc backhaul failed ${l.consecutiveFailures} consecutive times (last close ${l.lastCloseCode===null?"by provider liveness reap":`code ${l.lastCloseCode}`}${l.lastCloseReason?`, reason ${JSON.stringify(l.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&a.push(t.onPhase(l=>{if(l.name==="live"){i=!0;return}i&&wa.has(l.name)&&d(new J(`the pooled session for app "${e}" lost its compute binding (phase "${l.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:()=>s,onGone(l){return s?(l(s),()=>{}):(u.add(l),()=>u.delete(l))},dispose(){u.clear();for(let l of a.splice(0))l()}}}async function*On(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 ba=1,Sa=4,ka=4;function lo(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let d=Number.parseInt(a,10);if(!Number.isInteger(d)||d<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return d},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):ba;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,Sa));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",ka),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function co(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return Nt;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 io(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 po(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),d=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,l=_=>({session:_,responses:new Rt(_),gone:so(_,n)});if(i.lane==="jwt"){let _=(0,ie.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return l(io(_,e.appSlug,u,d))}let{apiKey:c,gatewayUrl:h}=i,f=(typeof t.subject=="function"?t.subject():t.subject)??(0,uo.randomUUID)(),p=(0,ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ie.createClientToken)(c,{baseUrl:h,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:f,...e.sharedApp?{sharedApp:!0}:{}})).token});return l(io(p,e.appSlug,u,d))}function xa(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 Ra(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 Ea=new Set(["error","paused"]);function fo(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=po(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 Mt({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"?()=>to({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>xr(n):null,listPrices:n?()=>Nr(n):null,shared:e.lane==="api-key"?()=>Fr({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:xa});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},ke({appSlug:t.defaultApp}))),s}function mo(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=a=>{process.stderr.write(`[decision-pool] ${a}
|
|
6
|
-
`)},
|
|
7
|
-
`)}var Oa={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Te="urun.videoOut";function bo(t){return{framing:Rr,codec:t}}function So(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Te]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Ta={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Pa=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Te],ho=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Ca(t){let e=j(t);if(!e)throw new S("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new S(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=j(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new S("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new S(`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 S("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(!ho.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ho.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Ma=["temperature","maxOutputTokens","responseModalities"];function ko(t){for(let[c,h]of Object.entries(Ta))if(t[c]!==void 0)throw new S(h);for(let c of Object.keys(t))if(!Pa.includes(c))throw new S(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new S('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=j(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new S("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Ma.includes(c))throw new S(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new S("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new S("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 h of c){let f=String(h).toUpperCase();if(f==="AUDIO"){o=!0;continue}if(f!=="TEXT")throw new S(`responseModalities ${JSON.stringify(h)} 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 S("setup.tools must be an array");u=[];for(let c of t.tools){let h=j(c);if(!h)throw new S("setup.tools entries must be objects");for(let f of Object.keys(h))if(f!=="functionDeclarations")throw new S(`unsupported tool "${f}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(h.functionDeclarations))throw new S("tool.functionDeclarations must be an array");for(let f of h.functionDeclarations){let p=j(f);if(!p||typeof p.name!="string")throw new S("functionDeclarations entries require a string name");u.push({type:"function",name:p.name,description:p.description,parameters:p.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=j(t.sessionResumption);if(!c)throw new S("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let h of Object.keys(c))if(h!=="handle")throw new S(`unsupported sessionResumption field "${h}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new S("sessionResumption.handle must be a non-empty string when present");a={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let d=t.realtimeInputConfig===void 0?Oa:Ca(t.realtimeInputConfig),l=!1;if(t[Te]!==void 0){if(!j(t[Te]))throw new S(`setup["${Te}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:i,tools:u,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:a,videoOut:l}}function xo(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Ro(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Eo(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new S(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new S("clientContent.turns must be an array");let n=[];for(let r of e){let o=j(r);if(!o)throw new S("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 S(`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 qt=16e3,Ao=24e3,La=`audio/pcm;rate=${Ao}`,Io=Buffer.alloc(960).toString("base64");function $a(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,d=Math.floor(a);if(d>=i){o[u]=t[i];continue}let l=a-d;o[u]=Math.round(t[d]+(t[d+1]-t[d])*l)}return o}function Ua(t){let e=j(t);if(!e)throw new S("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new S(`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 S("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 S("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Na(t){let e=j(t);if(!e)throw new S("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new S(`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])!==qt)throw new S(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${qt} Hz (audio/pcm;rate=${qt})`);if(typeof e.data!="string"||e.data.length===0)throw new S("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 S(`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=$a(o,qt,Ao);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Oo(t){if(t.mediaChunks!==void 0)throw new S('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 S("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=j(t[o]);if(!s||Object.keys(s).length!==0)throw new S(`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 S(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new S(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Na(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Ua(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new S("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new S("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function To(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new S(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new S("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=j(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new S("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 Po(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Co(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:La,data:t}}]}}}}function Mo(t){let e=j(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let d of n){let l=j(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let c of l.content){let h=j(c);h?.type==="output_text"&&typeof h.text=="string"&&(s+=h.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let l=j(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new S(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,_e);let c=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",h;try{h=JSON.parse(c)}catch{throw new S(`upstream function_call arguments are not valid JSON: ${c}`,_e)}r.push({id:l.call_id,name:l.name,args:h}),o.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let u=j(e.usage),a={serverContent:{turnComplete:!0}};if(u){let d={};typeof u.input_tokens=="number"&&(d.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(d.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(d.totalTokenCount=u.total_tokens),Object.keys(d).length>0&&(a.usageMetadata=d)}return i.push(a),{messages:i,assistantItems:o}}var Da=256,Tn=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Da;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Fa="local",it=t=>t.slice(0,120),Pn=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 N){this.ws.close(_o,it(e.message));return}if(e instanceof J){this.ws.close(Gt,it(e.message));return}if(e instanceof S){this.ws.close(e.closeCode,it(e.message));return}this.ws.close(_e,it(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=wo(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 S(`"${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}=Eo(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Oo(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:Io);return}this.transcript.push(...To(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new S("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 S("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",Gt);if(s.model!==n.model)throw new S(`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 S("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 S(`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`,Gt);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(d=>this.send(So(d))),a=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{u(),a()},o[Te]=bo(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 S("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new S("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",_e);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Co(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 S("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new S("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",_e);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 S(`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 S("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 S("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,Lo.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(xo(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(Ro(e.timeLeftMs)),this.ws.close(_e,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 d=a;if(d.type==="error")throw new S(`upstream error: ${JSON.stringify(d)}`,_e);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=Po(d);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new S("upstream produced no response.completed event",_e);let{messages:i,assistantItems:u}=Mo(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Pe=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Ba(t,e,n){let r=new Set;(a=>{if(typeof a=="string")a!==""&&r.add(a);else if(Array.isArray(a))for(let d of a)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Pe(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 Pe(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 Pe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function Uo(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 $o.WebSocketServer({noServer:!0}),o=new Tn;t.on("upgrade",(i,u,a)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===yo&&(u.on("error",()=>{}),(async()=>{let l=Ba(i,d,n),c;if(e.authenticate)c=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new Pe(401,"invalid local proxy api key");c={clients:e.clients,scope:Fa}}r.handleUpgrade(i,u,a,h=>{new Pn(h,c,o)})})().catch(l=>{let c=502;(l instanceof Pe||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(c=l.status);let h=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=l instanceof Error?l.message:String(l);u.destroyed||(u.write(`HTTP/1.1 ${c} ${h}\r
|
|
2
|
+
"use strict";var Ii=Object.create;var gr=Object.defineProperty;var Oi=Object.getOwnPropertyDescriptor;var Ti=Object.getOwnPropertyNames;var Pi=Object.getPrototypeOf,Ci=Object.prototype.hasOwnProperty;var Mi=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ti(e))!Ci.call(t,o)&&o!==n&&gr(t,o,{get:()=>e[o],enumerable:!(r=Oi(e,o))||r.enumerable});return t};var qe=(t,e,n)=>(n=t!=null?Ii(Pi(t)):{},Mi(e||!t||!t.__esModule?gr(n,"default",{value:t,enumerable:!0}):n,t));var Li=()=>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,O=Li();var cr=require("child_process"),pe=require("fs"),pr=qe(require("path"),1),L=qe(require("process"),1);var ie=require("@urun-sh/core");function hr(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 yr(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 _r(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 $i="llm-resp";async function*yn(t,e){let n=`${$i}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;try{for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let u=typeof a.index=="number"?a.index:0,d=o.get(u)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),o.set(u,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield _r(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var Rt=class t{constructor(e,n=t.DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;docSyncTimeoutMs;sessionTag;static DEFAULT_DOC_SYNC_GATE_TIMEOUT_MS=15e3;get consumerId(){return this.session.consumerId}async ensureDocSynced(){let e=this.session.doc("llm");if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((o,s)=>{let i=e.onSynced(()=>{clearTimeout(n),o()});n=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${this.docSyncTimeoutMs}ms \u2014 the request envelope write is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},this.docSyncTimeoutMs)})}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=yr(e,n,this.consumerId);return this.write(r),yn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=hr(e,n,r,this.consumerId);return this.write(o),yn(this.session,r)})}async writeGated(e,n){try{await this.ensureDocSynced()}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var wr=0;function Ui(){return wr+=1,`req_${Date.now().toString(36)}_${wr.toString(36)}`}var Et=class{transport;constructor(e){this.transport=new Rt(e)}responses={create:async e=>{let n=Ui(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var Sr="audio",_n=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 _n(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Sr).attach(o);let s=await Ni(t,n);return await r.startInbound(s),r}function Ni(t,e){let n=t.stream(Sr);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),a=u=>{u!=null&&(clearTimeout(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var vr="rt-video-in",br=256e3;function xr(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>br)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${br}-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 Di=24e3,nt=480,Fi=111;async function Bi(){let t=await import("opusscript"),e=t.default??t;return new e(Di,1,2048)}async function At(){let t=await import("werift"),e=await Bi();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:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let d=0;for(;u.length-d>=nt;){let l=u.subarray(d,d+nt);d+=nt;let c=Buffer.from(l.buffer,l.byteOffset,l.byteLength),m=e.encode(c,nt);o=o+1&65535,s=s+nt>>>0;let f=new t.RtpHeader({version:2,payloadType:Fi,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),p=new t.RtpPacket(f,m);n.writeRtp(p)}i=u.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}async function Rr(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,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 It=require("@urun-sh/core"),wn="rt-video-out";var qi="h264";function ji(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 Gi(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;ji(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 Er="urun.videoOut.v2-ws";function Ar(t){let e=t.stream(wn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${wn}') 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=u=>{for(let d of r)d(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${wn}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=Gi(u)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let u of o)u()};return{codec:qi,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var Ir={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},je=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Or(t){let e=t.t;if(typeof e!="string"||!(e in Ir))throw new je(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Ir).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 Hi(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new je(`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 je(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Or(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new je(`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 Or(t)}function Tr(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Vi(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 Pr(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 Tr(e);let s=o.next();if(e!==void 0&&await Vi(s,e)==="aborted")throw s.catch(()=>{}),Tr(e);let i=await s;if(i.done)return;yield Hi(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Cr=require("@urun-sh/core"),vn=2;function Ji(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Wi(t){let e=t?.type;return e==="response.completed"||e==="error"}function Mr(t){return async function(n,r){return(async function*(){for(let s=1;s<=vn;s++){let{app:i,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let d=!1,l=!1;try{let c=await t.createStream(a,n);for await(let m of c){if(Wi(m)&&(d=!0),Ji(m)){if(s>1)continue}else l=!0;yield m}}catch(c){if(c instanceof Cr.SessionFailedError&&(c.kind==="never-live"||c.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,c)}catch{}throw c}if(s<vn&&!l){await t.evict(i,a);continue}throw c}if(d)return;if(s<vn&&!l){await t.evict(i,a);continue}return}})()}}var lo=require("crypto");var se=class extends Error{name="ModelPriceError"},bn="per_million_input_tokens",Sn="per_million_output_tokens",$r="model_id,variant,unit,price_usd,effective_at,expires_at",Lr={per_request:!0,per_minute:!0,per_output_unit:!0},Ki=5e3;function zi(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new se(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Ur(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new se(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Yi(t,e,n){return t===null?null:Ur(t,e,n)}function Xi(t,e){if(t===bn)return"input";if(t===Sn)return"output";if(typeof t=="string"&&Object.hasOwn(Lr,t))return null;throw new se(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${bn} | ${Sn}) nor a known GPU-time unit (${Object.keys(Lr).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 Qi(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 kn(t,e){return`${t}\0${e}`}function Zi(t){if(!Array.isArray(t))throw new se(`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 se(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of $r.split(","))if(!Object.hasOwn(s,d))throw new se(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=Xi(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new se(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new se(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:zi(s.price_usd,o),effective_at:Ur(s.effective_at,o,"effective_at"),expires_at:Yi(s.expires_at,o,"expires_at")})}return e}function Nr(t,e=Date.now(),n){let r=new Map,o=new Map;for(let u of t){if(u.effective_at>e||u.expires_at!==null&&u.expires_at<=e)continue;let d=r.get(u.model_id);d||(d=new Map,r.set(u.model_id,d),o.set(u.model_id,new Map));let l=u.variant??"",c=d.get(l);c||(c={input:[],output:[]},d.set(l,c),o.get(u.model_id).set(l,u.variant)),c[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,d]of r){let l=d.get(""),c=(m,f,p)=>{let y=m&&m.length>0?m:l?.[f];if(!y||y.length===0)return null;let g=Qi(y,f);return"reason"in g?g:g.rate.usd===0?f==="output"&&p!==null&&n?.has(kn(u,p))?g.rate:{reason:`the ${f} 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`}:g.rate};for(let[m,f]of o.get(u)){let p=d.get(m),y=c(p?.input,"input",f),g=c(p?.output,"output",f);if(y!==null&&"reason"in y){i.push({model_id:u,variant:f,reason:y.reason});continue}if(g!==null&&"reason"in g){i.push({model_id:u,variant:f,reason:g.reason});continue}y===null||g===null||s.push({model_id:u,variant:f,pricing:{input:y.usd,output:g.usd}})}}let a=(u,d)=>u.model_id.localeCompare(d.model_id)||(u.variant===null?1:0)-(d.variant===null?1:0)||(u.variant??"").localeCompare(d.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function rt(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 ot={prices:[],refusals:[]};async function Dr(t){let e=t.fetchImpl??fetch,n=`${bn},${Sn}`,r=await e(`${t.catalogUrl}/model_prices?select=${$r}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Ki)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Zi(await r.json())}var K=class extends Error{},ea=/^(\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=ea.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let u=new Date(Date.UTC(n,r-1,o,s,i,a));return u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===o&&u.getUTCHours()===s&&u.getUTCMinutes()===i&&u.getUTCSeconds()===a}function na(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new K(`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 K(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new K(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,u)=>{if(a===null||typeof a!="object")throw new K(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let d=a;for(let c of["model_id","variant","app_slug","function"])if(typeof d[c]!="string"||d[c].length===0)throw new K(`catalog shared endpoints[${u}] (${JSON.stringify(d)}) has no valid "${c}"`);let l=(c,m)=>{if(d[c]!==void 0&&d[c]!==null&&!m)throw new K(`catalog shared endpoints[${u}] (${d.model_id}:${d.variant}) carries a malformed "${c}": ${JSON.stringify(d[c])}`)};l("ready",typeof d.ready=="boolean"),l("ready_runtimes",typeof d.ready_runtimes=="number"&&Number.isInteger(d.ready_runtimes)&&d.ready_runtimes>=0),l("ready_since",ta(d.ready_since));for(let c of["model_id","variant"]){let m=d[c];if(m.includes(":"))throw new K(`catalog shared endpoints[${u}] has "${c}" containing ":" (${JSON.stringify(m)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return l("output_free",typeof d.output_free=="boolean"),d});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new K(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new K(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let u of Object.keys(a))if(u!=="zdr"&&u!=="hipaa")throw new K(`catalog "shared" block compliance carries "${u}" 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 Ge(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Fr(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 a=t.endpoints.filter(d=>d.model_id===o);if(a.length===0)return null;if(s!==void 0){let d=a.find(l=>l.variant===s);return d?{shared_org_id:t.shared_org_id,endpoint:d}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(d=>d.compat_default===!0);if(u.length!==1)throw new K(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(d=>d.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function Br(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 K(`catalog read failed: GET ${n} \u2192 ${r.status}`);return na(await r.json())}function he(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var st="/partners/openrouter/models",ra={chat:!0,code:!0,agent:!0,vl:!0},qr={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function oa(t){let e=t.toLowerCase();return Object.hasOwn(qr,e)?qr[e]:null}var jr={"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 sa(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(jr,o)?jr[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.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 Gr={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Hr={2:"Llama2",3:"Llama3"};function ia(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(Gr,s))return Gr[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Hr,i))return Hr[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var aa=["context_length","max_model_len"];function ua(t){let e=aa.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 Tt(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 xn(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 la(t,e){let n=e.filter(o=>he(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return Ot(n);let r=e.filter(o=>he(o.model_id)===t);return r.length>0?Ot(r):null}function Ot(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:ca(t),matches:t}:null}function ca(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")}}function Wr(t){return 0}function Oe(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 Pt(t,e,n){let r=la(t,e);if(!r)return Oe({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Tt(s),a=rt(o.model_id,o.variant,n),u=Kr(o,s),d=xn(s);return Oe({id:t,object:"model",created:Wr(o),owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var pa=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Kr(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,a)=>i===r[a])))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:[...pa],defect:o}:{published:[],defect:o}}function Rn(t){let e=t.length>0?Ot(t):null;return e===null?{published:[],defect:null}:Kr(e.row,e.matches)}function Vr(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 Jr(t){return{input:[{type:"prompt",unit:"token",cost_usd:Vr(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Vr(t.output)}]}}function fa(t,e,n,r){if(e.length===0)return null;let o=Ot(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||ra[s.task]!==!0)return null;let a=Tt(i),u=rt(s.model_id,s.variant,n),d=ia(s.hf_repo),l={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(l.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:Wr(s),quantization:oa(s.variant),...d!==null?{tokenizer:d}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&u!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...u?{pricing:Jr(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:l,...u?{pricing:Jr(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function zr(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?Ge(t):[];if(s.length>0){let d=s.filter(l=>l.ready===void 0);if(d.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(d.length>0){let l=d.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${l} carry no ready field and are declared not ready`)}}let i={datacenters:sa(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let d of s){let l=`${d.model_id}:${d.variant}`;if(u.has(l))continue;u.add(l);let c=fa(d,e.filter(m=>m.model_id===d.model_id&&m.variant===d.variant),n,i);c&&a.push(c)}return{data:a}}var to="https://api.urun.sh/v1",N=class extends Error{},J=class extends Error{},An="urs1.";function Yr(t,e){return An+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function ma(t){if(!t.startsWith(An))return null;try{let e=JSON.parse(Buffer.from(t.slice(An.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 no(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 Xr(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=ha(t);return e===null?[]:[e]}function En(t,e,n,r,o){if(!o)throw new K(`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 K(`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 K(`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 Qr(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 K(`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 ro="shared:",Zr="speech:";function xe(t){return t.sharedApp?ro+t.appSlug:t.appSlug}function Mt(t){return typeof t.modelId=="string"&&typeof t.variant=="string"?{kind:"catalog",model_id:t.modelId,variant:t.variant}:{kind:"not-a-catalog-model",model:t.appSlug}}function Se(t,e){let n=e.filter(s=>he(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>he(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function ga(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function ha(t){let e=t.map(ga),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var eo={stt:"stt",tts:"tts"};function ke(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||eo[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?eo[e]:null}function ya(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 Error(`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 Ct=6e4,Lt=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Ct;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??Ct;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Ct;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Ct;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 se)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
|
|
3
|
+
`),ot}let r=Nr(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}
|
|
4
|
+
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(kn(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(ro)||o.startsWith(Zr)||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 N(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 resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=he(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(o))return{appSlug:o};let a=i.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new N(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=s.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new N(`model "${n}" maps to app "${u.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.shared){let s=await this.sharedBlock();if(s){let i=Fr(s,n);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:s.shared_org_id}}}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===he(a.model_id)||o===he(`${a.model_id}-${a.variant}`));if(i)throw new N(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=Mt(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return xe(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,xe(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Zr+xe(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:Mt(e)}}keyOf(e){let n=this.opts.sessionKey;if(!n)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let r=n(e);if(typeof r!="string"||r.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return r}async handleFor(e){let{app:n,entry:r}=await this.sessionFor(e);return{app:n,handle:Yr(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Yr(n,this.keyOf(r))}}async sessionForHandle(e){let n=ma(e);if(!n)throw new J(`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(a=>a,()=>null):null;if(i===null)throw new J(`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 J(`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(d=>({ok:!0,rows:d}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:ot;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)
|
|
5
|
+
`);let u=(n?Ge(n):[]).map(d=>{let l=s.filter(g=>g.model_id===d.model_id&&g.variant===d.variant),c=Tt(l),m=xn(l),f=rt(d.model_id,d.variant,i),p=Rn(l);return Oe({id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",...c!==null?{context_length:c}:{},...f!==null?{pricing:f}:{},...p.published.length>0?{voices:[...p.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(d=>Pt(d,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return zr(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=En(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Qr(`${r.modelId}:${r.variant}`,s).includes(n)}return Xr(Se(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:ke(Se(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":ke(Se(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ke(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":ke(Se(n.appSlug,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):Se(n.appSlug,r);return ya(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):Se(n.appSlug,r);return Rn(o)}async imageModelList(){let e=await this.catalogRows(),n=ot,r=[];for(let s of await this.availableIds()){let i=Xr(Se(s,e));i.length!==0&&r.push(Oe({...Pt(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of Ge(o)){let i=En(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Qr(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u=Oe({id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",image_modes:a});r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=ot,r=[];for(let s of await this.availableIds())ke(Se(s,e))==="stt"&&r.push(Pt(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Ge(o)){let i=En(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(ke(i)!=="stt")continue;let a=Oe({id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun"});r.push(a)}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 He=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)}},it=class extends He{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},In=class extends He{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},Te=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Ut=class{constructor(e){this.opts=e;if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}opts;slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}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};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.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n)),this.pump();return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new it;this.lastDemandAt=this.now();let e=this.opts.acquireTimeoutMs??6e5,n=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new it;if(!this.slots.some(u=>u.state==="queued")&&this.slots.length<this.opts.max){this.openForDemand();continue}let s=n+e-Date.now();if(s<=0)throw new In(e);let i,a={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(u=>{a.resolve=u,this.waiters.push(a)}),new Promise(u=>{i=setTimeout(u,s)})])}finally{clearTimeout(i);let u=this.waiters.indexOf(a);u!==-1&&this.waiters.splice(u,1),a.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new it}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();return n||(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max&&this.openForDemand(),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 a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&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())}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,o)=>(r.idleSince??0)-(o.idleSince??0)||o.slot.index-r.slot.index);for(let r of n)this.endSlot(r)}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 On=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)}},Dt=33e4;function oo(t,e=Dt){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((d,l)=>{o=l}),i=setTimeout(()=>o(new Nt),e),a;try{a=await Promise.race([r.next(),s])}catch(d){throw d instanceof J||d instanceof On.SessionFailedError&&d.kind==="transport-failed"?d:d instanceof Nt?(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(d instanceof Error?d.message:d)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new ye("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var Nt=class extends Error{constructor(){super("stream idle timeout")}};function so(t){return t instanceof ye?!1:t instanceof J?!0:t instanceof On.SessionFailedError?t.kind==="transport-failed":!1}var _a=3,wa="llm",va=new Set(["paused","error"]);function io(t,e){let n=t.doc(wa),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)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 s=null,i=!1,a=new Set,u=[],d=l=>{if(!s){s=l;for(let c of[...a])c(l);a.clear()}};return r&&u.push(n.onConnectionState(l=>{i&&(l.consecutiveFailures<_a||d(new J(`the pooled session for app "${e}" is gone: its doc backhaul failed ${l.consecutiveFailures} consecutive times (last close ${l.lastCloseCode===null?"by provider liveness reap":`code ${l.lastCloseCode}`}${l.lastCloseReason?`, reason ${JSON.stringify(l.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(l=>{if(l.name==="live"){i=!0;return}i&&va.has(l.name)&&d(new J(`the pooled session for app "${e}" lost its compute binding (phase "${l.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:()=>s,onGone(l){return s?(l(s),()=>{}):(a.add(l),()=>a.delete(l))},dispose(){a.clear();for(let l of u.splice(0))l()}}}async function*Tn(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});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 Sa=1,ka=4,xa=4;function co(t,e){let n=(i,a)=>{let u=(t[i]??"").trim();if(!u)return a;let d=Number.parseInt(u,10);if(!Number.isInteger(d)||d<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return d},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Sa;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,ka));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",xa),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function po(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return Dt;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 ao(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 fo(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,u=t.sessionStartOptions?.(n),d=r||u||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...u,...r}:void 0,l=y=>({session:y,responses:new Et(y),gone:io(y,n)});if(i.lane==="jwt"){let y=(0,ie.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return l(ao(y,e.appSlug,a,d))}let{apiKey:c,gatewayUrl:m}=i,f=(typeof t.subject=="function"?t.subject():t.subject)??(0,lo.randomUUID)(),p=(0,ie.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,ie.createClientToken)(c,{baseUrl:m,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:f,...e.sharedApp?{sharedApp:!0}:{}})).token});return l(ao(p,e.appSlug,a,d))}function Ra(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 Ea(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 Aa=new Set(["error","paused"]);function mo(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=fo(t,i,a);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},s=new Lt({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"?()=>no({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>Rr(n):null,listPrices:n?()=>Dr(n):null,shared:e.lane==="api-key"?()=>Br({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Ra});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},xe({appSlug:t.defaultApp}))),s}function go(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=u=>{process.stderr.write(`[decision-pool] ${u}
|
|
6
|
+
`)},a=(u,d)=>{let l=o.get(d);if(l)return l;let c=new Ut({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async m=>{let f=fo(t,u,d,{concurrencyKey:m.concurrencyKey});return f.gone.onGone(()=>c.evict(f)),await Bt(f.session),i(`slot attached pool=${d} slot=${m.concurrencyKey} session=${f.session.id??"(no id)"}`),f},closeSlot:async m=>{m.gone.dispose(),await m.session.end()},onDetach:(m,f)=>i(`slot detached pool=${d} slot=${m.concurrencyKey} reason=${f}`)});return o.set(d,c),c};return{async boot(){if(t.defaultApp===null)return;let u={appSlug:t.defaultApp};await a(u,xe(u)).boot()},async sessionFor(u){let d=await e.resolveTargetFor(u),l=xe(d),c=a(d,l).tryAcquireReady();if(!c)throw new Te(a(d,l).stats().lastMissAgeMs);let m=s.get(c.entry)??[];return m.push(c),s.set(c.entry,m),{app:l,entry:c.entry,identity:Mt(d)}},async warmFor(u){let d=await e.resolveTargetFor(u);await a(d,xe(d)).boot()},end(u){let d=s.get(u)?.shift();d&&(s.get(u)?.length===0&&s.delete(u),d.release())},evict(u){for(let d of o.values())d.evict(u)},reap(){for(let u of o.values())u.reap()},async pingReady(u){for(let d of o.values())if(await d.pingReady(u))return!0;return!1},stats(){return[...o.entries()].map(([u,d])=>({poolKey:u,...d.stats()}))},async drain(u){await Promise.all([...o.values()].map(d=>d.drain({timeoutMs:u})))},async close(){await Promise.all([...o.values()].map(u=>u.close()))}}}function Ia(t){return(0,ie.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS:ie.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:ie.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Bt(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:Ia(t.phase),signal:e})}async function uo(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 Ft(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ho(t,e=At,n,r,o=Dt){let s=new WeakMap,i=new WeakMap,a=new WeakMap,u=new WeakMap,d=new WeakMap,l=p=>{let y=p.session.id;return typeof y=="string"&&y.length>0?y:null},c=p=>{let y=s.get(p);if(!y){let g={waiting:0,gone:new AbortController};d.set(p,g),y=(async()=>{if(await Bt(p.session,g.gone.signal),g.gone.signal.aborted)throw Ft(g.gone.signal);d.get(p)===g&&d.delete(p);let _=await kr(p.session,await e());return Object.assign(_,{sessionId:p.session.id})})(),s.set(p,y),y.catch(()=>{s.get(p)===y&&s.delete(p)}),y.then(()=>{d.get(p)===g&&d.delete(p)},()=>{d.get(p)===g&&d.delete(p)})}return y},m=p=>{let y=u.get(p);return y||(y=(async()=>{let g=await c(p);return{appendInputAudio:_=>g.appendInputAudio(_),onOutputAudio:_=>g.onOutputAudio(_),sessionId:l(p)}})(),u.set(p,y),y.catch(()=>{u.get(p)===y&&u.delete(p)})),y},f=async(p,y,g)=>{if(g?.aborted){let v=d.get(p);throw(s.get(p)===void 0||v!==void 0&&v.waiting===0)&&await uo(p.session),Ft(g)}let _=y(p),h=d.get(p);return h!==void 0&&h.waiting++,g===void 0?_:new Promise((v,E)=>{let b=()=>{h!==void 0&&--h.waiting===0&&d.get(p)===h&&(h.gone.abort(),d.delete(p),s.delete(p),u.delete(p),uo(p.session).catch(()=>{})),E(Ft(g))};g.addEventListener("abort",b,{once:!0});let w=()=>g.removeEventListener("abort",b);_.then(k=>{w(),v(k)},k=>{w(),E(k)})})};return{createResponse:Mr({sessionFor:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>l(p),evict:(p,y)=>{r?r.evict(y):t.evict(p,y)},onAdmissionVerdict:(p,y,g)=>{Ea(g)&&(r?r.evict(y):t.evict(p,y),n?.(p,g.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,y)=>{try{await Bt(p.session);let g=oo(Tn(await p.responses.responses.create(y),p.gone),o);if(!r)return g;let _=p;return(async function*(){try{yield*g}catch(v){throw so(v)&&r.evict(_),v}finally{r.end(_)}})()}catch(g){throw r&&r.end(p),g}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,y)=>t.supportsImages(p,y),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,y)=>{let{entry:g}=await t.sessionFor(p);return await f(g,c,y)},openAudioOn:async(p,y)=>{let{entry:g}=await t.sessionForHandle(p);return await f(g,m,y)},openTurnsOn:async function*(p,y){if(y?.aborted)throw Ft(y);let{entry:g}=await t.sessionForHandle(p);yield*Pr(g.session,y)},openVideo:async p=>{let{entry:y}=await t.sessionFor(p),g=i.get(y);return g||(g=xr(y.session),i.set(y,g)),g},openVideoOut:async p=>{let{entry:y}=await t.sessionFor(p),g=a.get(y);return g||(g=Ar(y.session),a.set(y,g)),g},sessionHandle:async p=>(await t.handleFor(p)).handle,speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:y,entry:g}=await t.sessionForHandle(p);await t.evict(y,g)},createResponseOn:async(p,y)=>{let{entry:g}=await t.sessionForHandle(p);return await Bt(g.session),Tn(await g.responses.responses.create(y),g.gone)},onSessionEnd:async(p,y)=>{let{entry:g}=await t.sessionForHandle(p),_=g.session;if(typeof _.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let h=!1;return _.onPhase(v=>{if(h||!Aa.has(v.name))return;h=!0;let E=_.endsAt??null;y({timeLeftMs:E?Math.max(0,E.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}var wi=require("http");var $o=require("crypto"),Uo=require("ws");var _o="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Oa=1007,wo=1008,_e=1011,Ht=1008,S=class extends Error{constructor(n,r=Oa){super(n);this.closeCode=r}closeCode},j=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,qt=["setup","clientContent","realtimeInput","toolResponse"];function vo(t){let e;try{e=JSON.parse(t)}catch{throw new S("client message is not valid JSON")}let n=j(e);if(!n)throw new S("client message must be a JSON object");let r=qt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!qt.includes(a));if(o.length>0)throw new S(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${qt.join(", ")}`);if(r.length!==1)throw new S(`client message must contain exactly one of ${qt.join(", ")} (got ${r.length})`);let s=r[0],i=j(n[s]);if(!i)throw new S(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function bo(t,e){if(typeof t=="string")return t;let n=j(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new S(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=j(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new S(`${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 S(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new S(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
7
|
+
`)}var Ta={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Pe="urun.videoOut";function So(t){return{framing:Er,codec:t}}function ko(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Pe]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Pa={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ca=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Pe],yo=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Ma(t){let e=j(t);if(!e)throw new S("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new S(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=j(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new S("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new S(`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 S("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(!yo.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${yo.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var La=["temperature","maxOutputTokens","responseModalities"];function xo(t){for(let[c,m]of Object.entries(Pa))if(t[c]!==void 0)throw new S(m);for(let c of Object.keys(t))if(!Ca.includes(c))throw new S(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new S('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=j(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new S("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!La.includes(c))throw new S(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new S("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new S("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 m of c){let f=String(m).toUpperCase();if(f==="AUDIO"){o=!0;continue}if(f!=="TEXT")throw new S(`responseModalities ${JSON.stringify(m)} 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:bo(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new S("setup.tools must be an array");a=[];for(let c of t.tools){let m=j(c);if(!m)throw new S("setup.tools entries must be objects");for(let f of Object.keys(m))if(f!=="functionDeclarations")throw new S(`unsupported tool "${f}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(m.functionDeclarations))throw new S("tool.functionDeclarations must be an array");for(let f of m.functionDeclarations){let p=j(f);if(!p||typeof p.name!="string")throw new S("functionDeclarations entries require a string name");a.push({type:"function",name:p.name,description:p.description,parameters:p.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=j(t.sessionResumption);if(!c)throw new S("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(c))if(m!=="handle")throw new S(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new S("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let d=t.realtimeInputConfig===void 0?Ta:Ma(t.realtimeInputConfig),l=!1;if(t[Pe]!==void 0){if(!j(t[Pe]))throw new S(`setup["${Pe}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:u,videoOut:l}}function Ro(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Eo(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Ao(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new S(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new S("clientContent.turns must be an array");let n=[];for(let r of e){let o=j(r);if(!o)throw new S("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 S(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:bo(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var jt=16e3,Io=24e3,$a=`audio/pcm;rate=${Io}`,Oo=Buffer.alloc(960).toString("base64");function Ua(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 a=0;a<r;a++){let u=a*s,d=Math.floor(u);if(d>=i){o[a]=t[i];continue}let l=u-d;o[a]=Math.round(t[d]+(t[d+1]-t[d])*l)}return o}function Na(t){let e=j(t);if(!e)throw new S("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new S(`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 S("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 S("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Da(t){let e=j(t);if(!e)throw new S("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new S(`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])!==jt)throw new S(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${jt} Hz (audio/pcm;rate=${jt})`);if(typeof e.data!="string"||e.data.length===0)throw new S("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 S(`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=Ua(o,jt,Io);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function To(t){if(t.mediaChunks!==void 0)throw new S('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 S("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=j(t[o]);if(!s||Object.keys(s).length!==0)throw new S(`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 S(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new S(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Da(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Na(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new S("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new S("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Po(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new S(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new S("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=j(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new S("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 Co(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Mo(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:$a,data:t}}]}}}}function Lo(t){let e=j(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let d of n){let l=j(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let c of l.content){let m=j(c);m?.type==="output_text"&&typeof m.text=="string"&&(s+=m.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let l=j(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new S(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,_e);let c=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",m;try{m=JSON.parse(c)}catch{throw new S(`upstream function_call arguments are not valid JSON: ${c}`,_e)}r.push({id:l.call_id,name:l.name,args:m}),o.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=j(e.usage),u={serverContent:{turnComplete:!0}};if(a){let d={};typeof a.input_tokens=="number"&&(d.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(d.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(d.totalTokenCount=a.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return i.push(u),{messages:i,assistantItems:o}}var Fa=256,Pn=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Fa;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ba="local",at=t=>t.slice(0,120),Cn=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 N){this.ws.close(wo,at(e.message));return}if(e instanceof J){this.ws.close(Ht,at(e.message));return}if(e instanceof S){this.ws.close(e.closeCode,at(e.message));return}this.ws.close(_e,at(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=vo(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 S(`"${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}=Ao(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=To(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:Oo);return}this.transcript.push(...Po(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new S("setup may only be sent once, as the first client message");let n=xo(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new S("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",Ht);if(s.model!==n.model)throw new S(`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 S("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 S(`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`,Ht);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(ko(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[Pe]=So(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 S("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new S("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",_e);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Mo(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 S("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new S("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",_e);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 S(`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 S("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 S("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,$o.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Ro(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(Eo(e.timeLeftMs)),this.ws.close(_e,at(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new S(`upstream error: ${JSON.stringify(d)}`,_e);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=Co(d);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new S("upstream produced no response.completed event",_e);let{messages:i,assistantItems:a}=Lo(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ce=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function qa(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Ce(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 Ce(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new Ce(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function No(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 Uo.WebSocketServer({noServer:!0}),o=new Pn;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===_o&&(a.on("error",()=>{}),(async()=>{let l=qa(i,d,n),c;if(e.authenticate)c=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new Ce(401,"invalid local proxy api key");c={clients:e.clients,scope:Ba}}r.handleUpgrade(i,a,u,m=>{new Cn(m,c,o)})})().catch(l=>{let c=502;(l instanceof Ce||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(c=l.status);let m=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",f=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${c} ${m}\r
|
|
8
8
|
Connection: close\r
|
|
9
9
|
\r
|
|
10
10
|
${f}\r
|
|
11
|
-
`),
|
|
12
|
-
`}var qa=256,ja=128;function ne(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,ja)}var Ce=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>=qa?"(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 d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),u+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;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}}}},Ga=256;function Ha(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 Me=class extends Error{},He=class{conversations=new Map;thread(e,n){let r=Ha(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Me(`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<=Ga)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Ho=new WeakMap;function dt(t){let e=Ho.get(t);return e||(e=new He,Ho.set(t,e)),e}function Ve(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function fe(t){return t.find(e=>e.type==="response.completed")?.response??null}function Je(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 xe=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}))}},Va=["<tool_call>","<function="];function Ja(t){return Va.find(e=>t.includes(e))}function Le(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 $e(t,e,n){if(!(!t||e>0))return Ja(n)}function We(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 Wa(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 Mn(t,e){let n=Wa(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ue=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ke(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Me?new ue(n.message,"previous_response_not_found",400,"previous_response_id"):new ue(String(n instanceof Error?n.message:n),"invalid_input")}}function Vo(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function Ln(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ue("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}:{},...Vo(e)!==void 0?{response_format:Vo(e)}:{}},o)}async function lt(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ke(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,d=ne(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,h=await Ln(n,e,s,!0,c?ae(c):void 0);return{responseId:i,events:Xa({events:h,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function Ka(t,e){let n=[...t].sort((a,d)=>a.output_index-d.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?Ya(o[i++],a):a),...za(r,n)]}function za(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let l=d;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!u&&!a.has(o(l)):!0})}function Ya(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*Xa(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:d}=t,l=[],c=T=>T.response&&typeof T.response=="object"?{...T,response:{...T.response,id:r}}:T,h=`item_${r.slice(5)}`,f=!1,p=!1,_=0;function*m(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let y=[],g=(T,U)=>{y.push({output_index:T,item:U})},v=!1,E=0,b="",w=0,k="";function*M(){if(!v)return;v=!1,yield{type:"response.reasoning_text.done",item_id:b,output_index:E,content_index:0,text:k};let T={id:b,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:k}],status:"completed"};yield{type:"response.output_item.done",output_index:E,item:T},g(E,T),k=""}let x=!1,I=0,L="",F=0,Y="",te="";function*de(T){if(!x)return;x=!1,yield{type:"response.output_text.done",item_id:L,output_index:I,content_index:0,text:Y},yield{type:"response.content_part.done",item_id:L,output_index:I,content_index:0,part:{type:"output_text",text:Y}};let U={id:L,type:"message",role:"assistant",status:T,content:[{type:"output_text",text:Y}]};yield{type:"response.output_item.done",output_index:I,item:U},g(I,U),Y=""}let we=new xe,H=null,V=-1;function*Q(T){if(!H)return;let U=H;H=null,yield{type:"response.function_call_arguments.done",item_id:U.fcId,output_index:U.outputIndex,arguments:U.args};let z={id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:U.args,status:T};yield{type:"response.output_item.done",output_index:U.outputIndex,item:z},g(U.outputIndex,z)}let Ae=!1;for await(let T of d.track(e,o,t.turn)){l.push(T);let U=String(T.type??"");if(U==="response.created"||U==="response.in_progress"){f=!0,yield c(T);continue}if(U==="response.output_item.added"){p=!0,yield c(T);continue}if(U==="response.reasoning_text.delta"&&!p){yield*m(),v||(v=!0,E=_++,w+=1,b=w===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${w}`,yield{type:"response.output_item.added",output_index:E,item:{id:b,type:"reasoning",summary:[],content:[],status:"in_progress"}}),k+=String(T.delta??""),yield{type:"response.reasoning_text.delta",item_id:b,output_index:E,content_index:0,delta:T.delta};continue}if(U==="response.output_text.delta"&&!p){yield*m(),yield*M(),x||(x=!0,I=_++,F+=1,L=F===1?h:`${h}_${F}`,yield{type:"response.output_item.added",output_index:I,item:{id:L,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:L,output_index:I,content_index:0,part:{type:"output_text",text:""}}),Y+=String(T.delta??""),te+=String(T.delta??""),yield{type:U,item_id:L,output_index:I,content_index:0,delta:T.delta};continue}let z=p?null:Je(T);if(z){if(yield*m(),yield*M(),yield*de("completed"),we.add(z),z.tool_index!==V){yield*Q("completed"),V=z.tool_index;let ge=_++;H={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:ge,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:ge,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(z.call_id&&(H.callId=z.call_id),z.name&&(H.name=z.name),H.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:z.delta});continue}if(U==="response.completed"&&!p){let ge=Ve(T.response),B=$e(s,we.size+ge.length,te);if(B){Ae=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Le(o,B)}};break}if(yield*M(),yield*de("completed"),yield*Q("completed"),we.size===0)for(let ve of ge){let Fe=_++,St=ve.id??ve.call_id??`fc_${Fe}`,gn=ve.arguments??"",pr={id:St,type:"function_call",call_id:ve.call_id??St,name:ve.name??""};yield{type:"response.output_item.added",output_index:Fe,item:{...pr,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:St,output_index:Fe,delta:gn},yield{type:"response.function_call_arguments.done",item_id:St,output_index:Fe,arguments:gn};let fr={...pr,arguments:gn,status:"completed"};yield{type:"response.output_item.done",output_index:Fe,item:fr},g(Fe,fr)}let Z=Ka(y,T.response);yield Z.length>0?c({...T,response:{...T.response,output:Z}}):c(T);continue}yield c(T)}if(yield*M(),yield*de("incomplete"),yield*Q("incomplete"),i&&!Ae){let T=fe(l);a.remember(r,n,Mn(T,We(l,T)),u)}}var Qa="/v1/responses",Za=64*1024*1024,eu=8*1024*1024,tu=16,Jo=32,Wo=3600*1e3,nu=/^[A-Za-z0-9._-]{1,256}$/;function re(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var ru=re(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 Nn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function ou(t){for(;t.bufferedAmount>eu&&t.readyState===Re.WebSocket.OPEN;){let{promise:e,resolve:n}=Nn();setTimeout(n,5),await e}}var $n=class extends He{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 Me))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)}},Un=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new $n(dt(n)),e.on("message",(i,u)=>this.onMessage(i,u)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(re(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Wo/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Wo).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(re(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(re(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(re(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(re(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(re(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(re(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"||!nu.test(o.stream_id)){this.sendFrame(ru);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Jo){this.sendFrame(re(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Jo}). 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){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await lt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:ut(at())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==Re.WebSocket.OPEN)break;this.send(i,n),await ou(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=ut(at());try{let o=Ke(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof ue)return re(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof N)return re(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof J)return re(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?re(o.status,{type:o.openaiType,message:r},n):re(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=tu;){let{promise:e,resolve:n}=Nn();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!==Re.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!==Re.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Ht(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
11
|
+
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}var Ee=require("ws");var Do=require("crypto"),Fo="Inference-Id";function ut(){return(0,Do.randomUUID)()}function Mn(t){return t==="/v1"||t.startsWith("/v1/")}function Bo(t,e){if(!Mn(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function dt(t){return`resp_${t}`}function qo(t){return`chatcmpl-${t}`}function jo(t){return`msg_${t}`}function ae(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Go(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 Ho(t){return`${JSON.stringify(t)}
|
|
12
|
+
`}var ja=256,Ga=128;function ne(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Ga)}var Me=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>=ja?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Ha=256;function Va(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 Le=class extends Error{},Ve=class{conversations=new Map;thread(e,n){let r=Va(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Le(`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<=Ha)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Vo=new WeakMap;function lt(t){let e=Vo.get(t);return e||(e=new Ve,Vo.set(t,e)),e}function Je(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function fe(t){return t.find(e=>e.type==="response.completed")?.response??null}function We(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 Re=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}))}},Ja=["<tool_call>","<function="];function Wa(t){return Ja.find(e=>t.includes(e))}function $e(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 Ue(t,e,n){if(!(!t||e>0))return Wa(n)}function Ke(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 we(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ka(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 Ln(t,e){let n=Ka(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ue=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function ze(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Le?new ue(n.message,"previous_response_not_found",400,"previous_response_id"):new ue(String(n instanceof Error?n.message:n),"invalid_input")}}function Jo(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function $n(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ue("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}:{},...Jo(e)!==void 0?{response_format:Jo(e)}:{}},o)}async function ct(t){let{body:e,clients:n,store:r,stats:o}=t,s=ze(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=ne(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,m=await $n(n,e,s,!0,c?ae(c):void 0);return{responseId:i,events:Qa({events:m,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function za(t,e){let n=[...t].sort((u,d)=>u.output_index-d.output_index).map(({item:u})=>u),r=Array.isArray(e?.output)?e.output:[],o=r.filter(u=>u!==null&&typeof u=="object"&&u.type==="message"),s=n.filter(u=>u.type==="message").length===o.length,i=0;return[...n.map(u=>u.type==="message"&&s?Xa(o[i++],u):u),...Ya(r,n)]}function Ya(t,e){let n=e.some(d=>d.type==="message"),r=e.some(d=>d.type==="reasoning"),o=d=>String(d.call_id??d.id??""),s=e.filter(d=>d.type==="function_call"),i=t.filter(d=>d!==null&&typeof d=="object"&&d.type==="function_call").length,a=s.length===i,u=new Set(s.map(o));return t.filter(d=>{if(d===null||typeof d!="object")return!0;let l=d;return l.type==="message"?!n:l.type==="reasoning"?!r:l.type==="function_call"?!a&&!u.has(o(l)):!0})}function Xa(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*Qa(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,l=[],c=T=>T.response&&typeof T.response=="object"?{...T,response:{...T.response,id:r}}:T,m=`item_${r.slice(5)}`,f=!1,p=!1,y=0;function*g(){f||(f=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let _=[],h=(T,U)=>{_.push({output_index:T,item:U})},v=!1,E=0,b="",w=0,k="";function*C(){if(!v)return;v=!1,yield{type:"response.reasoning_text.done",item_id:b,output_index:E,content_index:0,text:k};let T={id:b,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:k}],status:"completed"};yield{type:"response.output_item.done",output_index:E,item:T},h(E,T),k=""}let x=!1,A=0,M="",D=0,W="",te="";function*de(T){if(!x)return;x=!1,yield{type:"response.output_text.done",item_id:M,output_index:A,content_index:0,text:W},yield{type:"response.content_part.done",item_id:M,output_index:A,content_index:0,part:{type:"output_text",text:W}};let U={id:M,type:"message",role:"assistant",status:T,content:[{type:"output_text",text:W}]};yield{type:"response.output_item.done",output_index:A,item:U},h(A,U),W=""}let ve=new Re,H=null,V=-1;function*Q(T){if(!H)return;let U=H;H=null,yield{type:"response.function_call_arguments.done",item_id:U.fcId,output_index:U.outputIndex,arguments:U.args};let Y={id:U.fcId,type:"function_call",call_id:U.callId??U.fcId,name:U.name??"",arguments:U.args,status:T};yield{type:"response.output_item.done",output_index:U.outputIndex,item:Y},h(U.outputIndex,Y)}let Ie=!1;for await(let T of d.track(e,o,t.turn)){l.push(T);let U=String(T.type??"");if(U==="response.created"||U==="response.in_progress"){f=!0,yield c(T);continue}if(U==="response.output_item.added"){p=!0,yield c(T);continue}if(U==="response.reasoning_text.delta"&&!p){yield*g(),v||(v=!0,E=y++,w+=1,b=w===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${w}`,yield{type:"response.output_item.added",output_index:E,item:{id:b,type:"reasoning",summary:[],content:[],status:"in_progress"}}),k+=String(T.delta??""),yield{type:"response.reasoning_text.delta",item_id:b,output_index:E,content_index:0,delta:T.delta};continue}if(U==="response.output_text.delta"&&!p){yield*g(),yield*C(),x||(x=!0,A=y++,D+=1,M=D===1?m:`${m}_${D}`,yield{type:"response.output_item.added",output_index:A,item:{id:M,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:M,output_index:A,content_index:0,part:{type:"output_text",text:""}}),W+=String(T.delta??""),te+=String(T.delta??""),yield{type:U,item_id:M,output_index:A,content_index:0,delta:T.delta};continue}let Y=p?null:We(T);if(Y){if(yield*g(),yield*C(),yield*de("completed"),ve.add(Y),Y.tool_index!==V){yield*Q("completed"),V=Y.tool_index;let ge=y++;H={fcId:`fc_${r.slice(5)}_${Y.tool_index}`,outputIndex:ge,callId:Y.call_id,name:Y.name,args:""},yield{type:"response.output_item.added",output_index:ge,item:{id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:"",status:"in_progress"}}}H&&(Y.call_id&&(H.callId=Y.call_id),Y.name&&(H.name=Y.name),H.args+=Y.delta,yield{type:"response.function_call_arguments.delta",item_id:H.fcId,output_index:H.outputIndex,delta:Y.delta});continue}if(U==="response.completed"&&!p){let ge=Je(T.response),B=Ue(s,ve.size+ge.length,te);if(B){Ie=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:$e(o,B)}};break}if(yield*C(),yield*de("completed"),yield*Q("completed"),ve.size===0)for(let be of ge){let Be=y++,kt=be.id??be.call_id??`fc_${Be}`,hn=be.arguments??"",fr={id:kt,type:"function_call",call_id:be.call_id??kt,name:be.name??""};yield{type:"response.output_item.added",output_index:Be,item:{...fr,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:kt,output_index:Be,delta:hn},yield{type:"response.function_call_arguments.done",item_id:kt,output_index:Be,arguments:hn};let mr={...fr,arguments:hn,status:"completed"};yield{type:"response.output_item.done",output_index:Be,item:mr},h(Be,mr)}let Z=za(_,T.response);yield Z.length>0?c({...T,response:{...T.response,output:Z}}):c(T);continue}yield c(T)}if(yield*C(),yield*de("incomplete"),yield*Q("incomplete"),i&&!Ie){let T=fe(l);u.remember(r,n,Ln(T,Ke(l,T)),a)}}var Za="/v1/responses",eu=64*1024*1024,tu=8*1024*1024,nu=16,Wo=32,Ko=3600*1e3,ru=/^[A-Za-z0-9._-]{1,256}$/;function re(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var ou=re(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 Dn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function su(t){for(;t.bufferedAmount>tu&&t.readyState===Ee.WebSocket.OPEN;){let{promise:e,resolve:n}=Dn();setTimeout(n,5),await e}}var Un=class extends Ve{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 Le))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)}},Nn=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Un(lt(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(re(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Ko/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Ko).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(re(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(re(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(re(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(re(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(re(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(re(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"||!ru.test(o.stream_id)){this.sendFrame(ou);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Wo){this.sendFrame(re(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Wo}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await ct({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:dt(ut())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==Ee.WebSocket.OPEN)break;this.send(i,n),await su(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=dt(ut());try{let o=ze(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof ue)return re(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof N)return re(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof J)return re(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?re(o.status,{type:o.openaiType,message:r},n):re(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=nu;){let{promise:e,resolve:n}=Dn();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!==Ee.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!==Ee.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Vt(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
13
13
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
14
14
|
Connection: close\r
|
|
15
15
|
Content-Type: text/plain; charset=utf-8\r
|
|
16
16
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
17
17
|
\r
|
|
18
|
-
${o}`)}function
|
|
19
|
-
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let
|
|
20
|
-
`)}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
|
|
18
|
+
${o}`)}function zo(t,e){let n=new Ee.WebSocketServer({noServer:!0,maxPayload:eu}),r=new Me,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,c,m)=>{let f;try{f=new URL(l.url??"/","http://localhost")}catch{Vt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),f.pathname!==Za){i.add(c);return}s.add(c);let p=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Vt(c,401,"invalid local proxy api key");return}let y;try{y=await a(l)}catch(g){let _=e.statusOf?.(g)??null;Vt(c,_?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(p=!0,n.handleUpgrade(l,c,m,g=>{s.delete(c),o.add(g),g.on("close",()=>o.delete(g));try{new Nn(g,y,r,e.statusOf)}catch{o.delete(g),g.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!p&&!c.destroyed&&Vt(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Dn();if(u)return c(),l;u=!0,t.off("upgrade",d);for(let f of s)f.destroy();s.clear();for(let f of i)f.destroy();i.clear();for(let f of o)f.close(1001,"server shutting down");let m=setTimeout(()=>{for(let f of o)f.readyState!==Ee.WebSocket.CLOSED&&f.terminate()},2e3);return m.unref?.(),n.close(()=>{clearTimeout(m),c()}),l}}}var ks=require("@urun-sh/core");var Yo=require("@urun-sh/core"),iu={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},au={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Fn(t,e){let n=au[t.code];return e?`${n} (${e})`:n}function Jt(t){if(t==null)return null;let e=iu[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 Wt(t){if(t.kind==="create-failed")return Jt(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Yo.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Jt(e?"cold_start_exceeded":"queue_timeout")}var Qo=qe(require("os"),1),Zo=qe(require("path"),1),es=require("url"),ts=require("util");var Xo="0.6.29";var ns=4141,du=Xo,zt={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 jn(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 rs(t,e,n){let r={...t,...jn(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function os(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=n[0]==="exec",u=s.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...d]}function ss(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function is(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function as(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,es.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 us(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 ds(t){if(t[0]!=="--port")return null;let e=us(t[1]);return t.splice(0,2),e}function Gn(t){let e=t.indexOf("--port");if(e===-1)return ns;let n=us(t[e+1]);return t.splice(e,2),n}function ls(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 Bn(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 Ye(t){let e=lu(Bn(t,"URUN_BASE_URL")),n=Bn(t,"URUN_ORG_ID"),r=Bn(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?Kt(s,"URUN_API_URL"):to,a=(t.URUN_JWT??"").trim();if(a)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(t.URUN_API_KEY??"").trim();if(u){let d=(t.URUN_GATEWAY_URL??"").trim(),l=d?Kt(d):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:u,gatewayUrl:l}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function lu(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 Kt(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 Hn(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:du}}function cu(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 pu=250;async function Vn(t,e=pu){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:a,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:o,org:s,fn:i,base_url:a,proxy_version:u}}catch{return null}}var cs=2e3;async function fu(t,e=cs){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 ps(t,e,n=ns,r=cs){if(t!=null)return{mode:"spawn",port:t};let o=await Vn(n);if(o!==null&&cu(o,e)){let s=await fu(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 Jn(t,e=Qo.default.homedir()){return Zo.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var qn=["log","info","warn","error","debug","trace"];function fs(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(a,...u)=>t.write(a,...u);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(qn.map(a=>[a,n[a]]));for(let a of qn)n[a]=(...u)=>{t.write(`${(0,ts.format)(...u)}
|
|
19
|
+
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let a of qn)n[a]=i[a]}}var mu=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ms(t){let e=t?.code;return typeof e=="string"&&mu.has(e)}function le(t,e){try{return t.write(e),!0}catch(n){if(ms(n))return!1;throw n}}function gs(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{ms(i)&&(e[r]=!0);let a=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
20
|
+
`)}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 hs(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}
|
|
21
21
|
`)}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}
|
|
22
22
|
`)}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
|
|
23
|
-
`)}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 hs(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 bs=require("@urun-sh/core");var _s=require("crypto");function R(t){return`${t}_${(0,_s.randomUUID)().replace(/-/g,"").slice(0,24)}`}var zt=4*1024*1024,Jn=8*1024*1024,Yt=512,Xt=20*1024*1024;function G(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Ye(t,e){return{type:"server_error",code:t,message:e}}function D(t){return{type:"error",event_id:R("event"),error:t}}function Wn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var A=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},mu={type:!0,model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},gu={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},hu={format:!0,voice:!0,speed:!0};function ys(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new A(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function ct(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new A("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in mu));if(o.length>0)throw new A(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,u]of Object.entries(r))switch(i){case"type":{if(u!=="realtime"&&u!=="transcription")throw new A(`session.type ${JSON.stringify(u)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==u)throw new A(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(u)}: 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(u==="transcription"&&!n.turns)throw new A('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");s.type=u;break}case"model":if(u!==null&&typeof u!="string")throw new A("model must be a string or null","model");s.model=u??void 0;break;case"instructions":if(u!==null&&typeof u!="string")throw new A("instructions must be a string or null","instructions");s.instructions=u??void 0;break;case"modalities":{if(!Array.isArray(u)||u.length===0)throw new A("modalities must be a non-empty array","modalities");let a=[];for(let d of u){if(d!=="text"&&d!=="audio")throw new A(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new A('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");a.includes(d)||a.push(d)}s.outputModalities=a;break}case"voice":if(u===null){delete s.voice;break}if(typeof u!="string")throw new A("voice must be a string or null","voice");if(!n.voice)throw new A("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=u;break;case"input_audio_format":case"output_audio_format":if(u!=="pcm16")throw new A(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(u!==null&&(typeof u!="number"||!Number.isFinite(u)))throw new A("temperature must be a finite number or null","temperature");s.temperature=u??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(u!==null&&u!=="inf"&&(typeof u!="number"||!Number.isInteger(u)||u<1))throw new A(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=u===null?void 0:u;break;case"tools":if(!Array.isArray(u))throw new A("tools must be an array","tools");s.tools=u;break;case"tool_choice":s.toolChoice=u;break;case"metadata":if(u!==null&&(!u||typeof u!="object"||Array.isArray(u)))throw new A("metadata must be an object or null","metadata");s.metadata=u??null;break;case"turn_detection":{if(u===null){s.turnDetection=null;break}if(!n.turns)throw new A("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 a=u;if(!a||typeof a!="object"||Array.isArray(a))throw new A("turn_detection must be an object or null","turn_detection");let d=String(a.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new A(`turn_detection.type ${JSON.stringify(a.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:a.create_response!==!1,interruptResponse:a.interrupt_response!==!1};break}case"input_audio_transcription":{if(u===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new A("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(!u||typeof u!="object"||Array.isArray(u))throw new A("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(u))if(!["model","language","languages","prompt"].includes(d))throw new A(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let a=u.model;if(a!=null){let d=typeof a=="string"?a:JSON.stringify(a);if(typeof a!="string"||a!==n.model)throw new A(`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")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(u!==null)throw new A("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(u===null)break;let a=u;if(!a||typeof a!="object"||Array.isArray(a))throw new A("audio must be an object or null","audio");if(a.input!==void 0&&a.input!==null){let d=a.input;if(!d||typeof d!="object"||Array.isArray(d))throw new A("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in gu))throw new A(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&ys(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=ct({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=ct({turn_detection:d.turn_detection},s,n);s.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new A("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(a.output!==void 0&&a.output!==null){let d=a.output;if(!d||typeof d!="object"||Array.isArray(d))throw new A("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in hu))throw new A(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&ys(d.format,"audio.output.format"),d.speed!==void 0)throw new A("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new A("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new A("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Qt(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 Kn(t,e){let n=t;if(!n||typeof n!="object")throw new A("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 A("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:R("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new A('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new A("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 A("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 A(`${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 A("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 A("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 A(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:R("item"),type:"message",role:r,content:o}}throw new A(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function zn(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 yu=1001,_u=1011,ws=t=>t.slice(0,120),wu=/^[A-Za-z0-9+/=]*$/,vu=2;function bu(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>vu)return!1;return!0}var pt=class{id=R("conn");ws;binding;onClosed;config=Wn();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:R("event"),session:Qt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(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){!this.closed&&!e.signal.aborted&&this.send(D(Ye("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:e,content_index:0,transcript: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:R("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:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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:R("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.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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=R("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:R("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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:R("event"),item_id:i,content_index:0,transcript:s}),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(G("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>zt){this.fail(G("frame_too_large",`frame exceeds the ${zt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(G("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(G("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(D({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Ye(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=ct(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:R("event"),session:Qt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Kn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(D(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:R("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(D(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:R("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(D(G("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:R("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(D(G("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!wu.test(e.audio)){this.send(D(G("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>Xt){this.send(D(G("buffer_full",`uncommitted input audio exceeds the ${Xt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=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:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(D(G("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;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:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:s}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(D(G("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(D(G("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(D(G("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(D(G("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(D({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(D(G("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(_=>_!=="text"&&_!=="audio")){this.send(D(G("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(D(G("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=R("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:u}=zn(this.items),a=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,h=n.tools!==void 0?n.tools:this.config.tools,f=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,p={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...a!==void 0?{instructions:a}:{},...d!==void 0?{temperature:d}:{},...c!==void 0?{max_output_tokens:c}:{},...h!==void 0?{tools:h}:{},...f!==void 0?{tool_choice:f}:{}};for(let _ of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(_);this.inFlight=(async()=>{let _=[],m=E=>{this.responseFlushed?this.send(E):_.push(E)},y=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:R("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(o,"in_progress")});for(let E of _)this.send(E);_.length=0,this.responseFlushed=!0}},g={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},v=null;try{u&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(p,r)}catch(b){this.upstreamTurnFault(b,o);return}try{for await(let b of E){if(this.cancelled)break;let w=b;if(w.type==="error"){let k=this.upstreamErrorBody(w);this.responseFlushed?this.send(D(k)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(o,k)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){y(),g.messageOpen||(this.beginMessageItem(o,g.nextOutputIndex++),g.messageOpen=!0),m({type:"response.output_text.delta",event_id:R("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:w.delta}),g.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){y();let k=typeof w.delta=="string"?w.delta:"",M=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${o}_fc_${g.nextOutputIndex}`,x=g.tools.get(M);if(!x){let I=typeof w.name=="string"&&w.name.length>0?w.name:void 0;x={outputIndex:g.nextOutputIndex++,name:I,args:""},g.tools.set(M,x),m({type:"response.output_item.added",event_id:R("event"),response_id:o,output_index:x.outputIndex,item:{id:M,object:"realtime.item",type:"function_call",call_id:M,name:I??"",arguments:"",status:"in_progress"}})}typeof w.name=="string"&&w.name.length>0&&(x.name=w.name),x.args+=k,m({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:M,response_id:o,output_index:x.outputIndex,call_id:M,name:x.name??"",delta:k});continue}if(w.type==="response.completed"){v=w.response??null;continue}}}catch(b){this.upstreamTurnFault(b,o);return}if(this.cancelled)return;this.closeOpenItems(o,g,s),y(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(o,s,v)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(bu(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(D({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:R("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:R("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let 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:R("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Ye("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof J){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof bs.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Ye(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(D(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(D(G("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:R("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Yt&&(this.items.shift(),this.send(D({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Yt} 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>Jn){this.ws.close(yu,ws("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(D(e)),this.ws.close(_u,ws(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;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>vs(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),vs(this.id,e)}},Yn=[];function vs(t,e){Yn.push({id:t,reason:e}),Yn.length>256&&Yn.shift()}var Qn="/v1/realtime",Su=t=>t.slice(0,120);function ku(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
23
|
+
`)}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 ys(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 xs=require("ws");var Ss=require("@urun-sh/core");var ws=require("crypto");function R(t){return`${t}_${(0,ws.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Yt=4*1024*1024,Wn=8*1024*1024,Xt=512,Qt=20*1024*1024;function G(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Xe(t,e){return{type:"server_error",code:t,message:e}}function F(t){return{type:"error",event_id:R("event"),error:t}}function Kn(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var I=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},gu={type:!0,model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},hu={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},yu={format:!0,voice:!0,speed:!0};function _s(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new I(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function pt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new I("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in gu));if(o.length>0)throw new I(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"type":{if(a!=="realtime"&&a!=="transcription")throw new I(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new I(`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 I('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");s.type=a;break}case"model":if(a!==null&&typeof a!="string")throw new I("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new I("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new I("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new I(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new I('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new I("voice must be a string or null","voice");if(!n.voice)throw new I("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new I(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new I("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new I(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new I("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new I("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new I("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new I("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new I(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new I("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new I("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new I(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=a.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new I(`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")}s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new I("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new I("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in hu))throw new I(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&_s(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=pt({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=pt({turn_detection:d.turn_detection},s,n);s.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new I("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new I("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in yu))throw new I(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&_s(d.format,"audio.output.format"),d.speed!==void 0)throw new I("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new I("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new I("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Zt(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 zn(t,e){let n=t;if(!n||typeof n!="object")throw new I("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new I("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:R("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new I('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new I("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new I("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new I(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new I("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new I("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new I(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:R("item"),type:"message",role:r,content:o}}throw new I(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function 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 _u=1001,wu=1011,vs=t=>t.slice(0,120),vu=/^[A-Za-z0-9+/=]*$/,bu=2;function Su(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>bu)return!1;return!0}var ft=class{id=R("conn");ws;binding;onClosed;config=Kn();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:R("event"),session:Zt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(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){!this.closed&&!e.signal.aborted&&this.send(F(Xe("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.isTranscriptionSession()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:e,content_index:0,transcript: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:R("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:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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:R("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.isTranscriptionSession()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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=R("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("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:R("event"),item_id:i,content_index:0,transcript:s}),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(G("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Yt){this.fail(G("frame_too_large",`frame exceeds the ${Yt}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(G("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(G("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(F({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Xe(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=pt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model}),this.send({type:"session.updated",event_id:R("event"),session:Zt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=zn(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(F(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:R("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(F(G("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:R("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(F(G("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:R("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(F(G("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!vu.test(e.audio)){this.send(F(G("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioTotalBytes+n>Qt){this.send(F(G("buffer_full",`uncommitted input audio exceeds the ${Qt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}if(this.isTranscriptionSession()){this.binding.audioSession.audio.appendInputAudio(e.audio),this.pendingAudioTotalBytes+=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:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(F(G("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.isTranscriptionSession()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;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:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.isTranscriptionSession())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:n});else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:r,content_index:0,transcript:s}),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;return}case"output_audio_buffer.clear":{this.send(F(G("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(F(G("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(F(G("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(F(G("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(F({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(F(G("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(y=>y!=="text"&&y!=="audio")){this.send(F(G("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send(F(G("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=R("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=Yn(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,m=n.tools!==void 0?n.tools:this.config.tools,f=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,p={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...c!==void 0?{max_output_tokens:c}:{},...m!==void 0?{tools:m}:{},...f!==void 0?{tool_choice:f}:{}};for(let y of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(y);this.inFlight=(async()=>{let y=[],g=E=>{this.responseFlushed?this.send(E):y.push(E)},_=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:R("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(o,"in_progress")});for(let E of y)this.send(E);y.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},v=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(p,r)}catch(b){this.upstreamTurnFault(b,o);return}try{for await(let b of E){if(this.cancelled)break;let w=b;if(w.type==="error"){let k=this.upstreamErrorBody(w);this.responseFlushed?this.send(F(k)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(o,k)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){_(),h.messageOpen||(this.beginMessageItem(o,h.nextOutputIndex++),h.messageOpen=!0),g({type:"response.output_text.delta",event_id:R("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:w.delta}),h.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){_();let k=typeof w.delta=="string"?w.delta:"",C=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${o}_fc_${h.nextOutputIndex}`,x=h.tools.get(C);if(!x){let A=typeof w.name=="string"&&w.name.length>0?w.name:void 0;x={outputIndex:h.nextOutputIndex++,name:A,args:""},h.tools.set(C,x),g({type:"response.output_item.added",event_id:R("event"),response_id:o,output_index:x.outputIndex,item:{id:C,object:"realtime.item",type:"function_call",call_id:C,name:A??"",arguments:"",status:"in_progress"}})}typeof w.name=="string"&&w.name.length>0&&(x.name=w.name),x.args+=k,g({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:C,response_id:o,output_index:x.outputIndex,call_id:C,name:x.name??"",delta:k});continue}if(w.type==="response.completed"){v=w.response??null;continue}}}catch(b){this.upstreamTurnFault(b,o);return}if(this.cancelled)return;this.closeOpenItems(o,h,s),_(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(o,s,v)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Su(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(F({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:R("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:R("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:R("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:R("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:R("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:R("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:R("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}failSessionGone(e){let n=e instanceof Error?e.message:String(e);this.fail(Xe("session_gone",`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`),"session_gone")}upstreamTurnFault(e,n){if(e instanceof J){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Ss.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Xe(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(F(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(F(G("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:R("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Xt&&(this.items.shift(),this.send(F({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Xt} 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>Wn){this.ws.close(_u,vs("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(F(e)),this.ws.close(wu,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;let n=this.turnLaneIterator;if(this.turnLaneIterator=null,n!==null){let r=n.return?.();r&&r.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(r=>bs(this.id,`binding release failed: ${r instanceof Error?r.message:String(r)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),bs(this.id,e)}},Xn=[];function bs(t,e){Xn.push({id:t,reason:e}),Xn.length>256&&Xn.shift()}var Zn="/v1/realtime",ku=t=>t.slice(0,120);function xu(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
24
24
|
Connection: close\r
|
|
25
25
|
Content-Type: text/plain\r
|
|
26
26
|
\r
|
|
27
|
-
${
|
|
28
|
-
`),t.destroy()}function
|
|
29
|
-
`}function Ru(t){le(process.stdout,t)}function Eu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Xn(t){return t.audioSession?.audio.sessionId??void 0}function Zn(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!==Qn)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=R("rtup"),d=Eu(o),l=b=>{(e.log??Ru)(xu(b))};l({stage:"accept",conn:a,model:d}),s.resume();let c=new AbortController,h=null,f=b=>{h??=b,c.abort(new Error(h))},p=()=>f("client socket closed"),_=()=>f("client socket closed (half-close)"),m=b=>f(`client socket error: ${b.message}`);s.once("close",p),s.once("end",_),s.once("error",m);let y=()=>{s.removeListener("close",p),s.removeListener("end",_),s.removeListener("error",m)},g=b=>{l({stage:"close",conn:a,model:d,...b})},v=b=>{let w=b,k=w.session!=null&&typeof w.session.sendResponseCreate=="function",M=w.clients!=null&&typeof w.clients.createResponse=="function";if(!k&&!M)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((x,I)=>{n.handleUpgrade(o,s,i,L=>{try{new pt({ws:L,binding:b,onClosed:(F,Y)=>{g({while:"live",reason:Y.reason})}}),l({stage:"admit",conn:a,model:d,...Xn(b)===void 0?{}:{session:Xn(b)}}),x()}catch(F){I(F)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async b=>{if(c.signal.aborted){y();let w=Xn(b);try{await b.release?.()}catch(k){g({while:"queued",...w===void 0?{}:{session:w},reason:h??"client socket closed",release_failed:k instanceof Error?k.message:String(k)});return}g({while:"queued",...w===void 0?{}:{session:w},reason:h??"client socket closed",released:!0}),s.destroy();return}y(),await v(b)}).catch(b=>{let w=b instanceof Ss.SessionFailedError?Jt(b):null,k=null;if(b!==null&&typeof b=="object"&&"status"in b){let I=b.status;typeof I=="number"&&(k=I)}let M=k??w?.status??502,x=b instanceof Error?b.message:String(b);g({while:"queued",...c.signal.aborted?{reason:h??"client socket closed"}:{reason:x,status:M}}),s.destroyed||ku(s,M,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 ce=(t,e)=>Object.assign(new Error(e),{status:t});function Au(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Ou='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Tu(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 N?ce(404,d.message):d}if(!o)throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw 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 N?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(l){throw l instanceof N?ce(404,l.message):l}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: ${Ou}`);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=await t.sessionHandle(e),u={audio:await t.openAudioOn(i,n)},a={clients:{createResponse:async d=>await t.createResponseOn(i,d)},voice:o,audioSession:u};return s&&(a.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(a.intent="transcription"),e!==void 0&&(a.model=e),a}function xs(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,s=typeof o=="string"?o.trim():"",i=s.startsWith("Bearer ")?s.slice(7).trim():"";if(i===""||i!==e)throw ce(401,"invalid local proxy api key")}return Tu(t,Au(n),r,Iu(n))}}}var X=class extends Error{};async function Zt(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new X(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new X(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function 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 X(`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[d,l]of Object.entries(t.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let c of l)i.append(d,c);let 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 X?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Rs="/v1/images/generations",tn="/v1/images/edits";function Es(t){return t===Rs||t===tn}var As="/v1/images/models";async function Is(t,e,n){if(t){if(t.model=ne({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 $=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Pu=16*1024*1024,Os=64*1024*1024;function Ts(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 ft(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 Ps(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let c of o){if(c.type==="error"){let h=c.error??{};throw new $(502,`image upstream error: ${String(h.message??"upstream reported an error")}`)}if(c.type==="response.completed"){s=c.response??null;break}}if(s===null)throw new $(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new $(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let u=[],a=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(a,"base64");if(Ts(d)===null)throw new $(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return u.push(a),{images:u}}function Cs(t){return t instanceof $?t:t instanceof N?new $(404,t.message):new $(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ms(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 ft(r,new $(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 Ls(t,e){t&&(t.outputUnits=e.images.length)}function $s(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 Cu={model:!0,prompt:!0,response_format:!0,n:!0};async function Us(t,e,n){let r=n.maxBodyBytes??Os;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${Rs}`);let o;try{o=JSON.parse((await Zt(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof X?new $(413,c.message):new $(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new $(400,"request body must be a JSON object");let s=o;for(let c of Object.keys(s))if(!Cu[c])throw new $(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string","prompt");let u=s.model===void 0?void 0:s.model;if(u!==void 0&&typeof u!="string")throw new $(400,"model must be a string","model");await Is(n.turn,n.clients,u);let a=s.n??1;if(a!==1)throw new $(400,`n=${JSON.stringify(a)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new $(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await Ms(n.imageModels,u,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await Ps(n.clients,u,l,n.turn?ae(n.turn):void 0);Ls(n.turn,c),$s(e,c)}catch(c){throw Cs(c)}}catch(o){if(o instanceof X){ft(e,new $(413,o.message));return}if(o instanceof $){ft(e,o);return}throw o}}var Mu={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ns(t,e,n){let r=n.maxBodyBytes??Os,o=n.maxImagePartBytes??Pu;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${tn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new $(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await en(t,r)}catch(f){throw f instanceof X?new $(413,f.message):new $(400,String(f instanceof Error?f.message:f))}let u=i.get("prompt");if(typeof u!="string"||u.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string field","prompt");let a=i.get("model");if(a!==null&&typeof a!="string")throw new $(400,"model must be a string field","model");let d=a===null?void 0:a;await Is(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new $(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of i.keys())if(!Mu[f])throw new $(400,`form field "${f}" 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[]).`,f);let c=[];for(let f of["image","image[]"])for(let p of i.getAll(f)){if(!(p instanceof File))throw new $(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(p.size>o)throw new $(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let _=new Uint8Array(await p.arrayBuffer()),m=Ts(_);if(m===null)throw new $(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);c.push({bytes:_,mime:m})}if(c.length===0)throw new $(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",u.length,u.length),!await Ms(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:u}];for(let{bytes:f,mime:p}of c)h.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Ps(n.clients,d,h,n.turn?ae(n.turn):void 0);Ls(n.turn,f),$s(e,f)}catch(f){throw Cs(f)}}catch(s){if(s instanceof X){ft(e,new $(413,s.message));return}if(s instanceof $){ft(e,s);return}throw s}}var mt="/v1/audio/speech";function Js(t){return t===mt}var Ds=4096,Fs=18e4,Bs=5e3,Lu=64*1024*1024,qs=8,js=5,Gs=1024*1024,Xe="voice_applied",rn="X-Urun-Voice-Applied",P=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function er(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 on=class extends P{constructor(e){super(502,e)}};function Ws(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 Ks(t){return new P(502,`the runtime's ${Xe} receipt ${JSON.stringify(t)} cannot be relayed as the ${rn} 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 $u(t,e,n){if(t){if(t.model=ne({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 zs(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Uu=2;function Nu(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Uu)return!1;return!0}function Du(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 Hs=new WeakMap,nn=new WeakMap;function Fu(t,e){let n=nn.get(t)??0;if(n>=qs)throw new P(503,`this model's speech queue is full \u2014 ${qs} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${js}s`,void 0,js);nn.set(t,n+1);let r=Hs.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Hs.set(t,s),(async()=>{await r;try{return await e()}finally{nn.set(t,(nn.get(t)??1)-1),o()}})()}async function Bu(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new P(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 Ue(t){return t instanceof P?t:t instanceof N?new P(404,t.message):new P(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Vs(t,e,n,r,o,s,i,u){let a=u??(()=>{});return Fu(e,async()=>{if(i?.()===!0)return null;let d=!1,l=!1,c=!1,h,f=new Promise(b=>{h=b}),p=[],_=()=>{l&&!c&&p.length>=o.quietRunFrames&&(c=!0,h())},m=e.onOutputAudio(b=>{let w=Buffer.from(b,"base64");if(w.byteLength===0)return;let k=Nu(w);if(!d){if(k)return;d=!0}if(k){p.push(w),_();return}for(let M of p)a(M);p.length=0,a(w),_()}),y=null,g,v,E;try{E=(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 w=new Promise(x=>{v=setTimeout(x,s.capMs)}),k=!1;for(;;){let x=E.next(),I=await Promise.race([x,w]);if(I===void 0){k=!0,x.catch(()=>{});break}if(I.done)break;let L=I.value;if(L.type==="error"){let F=L.error??{};throw await E.return?.(),new P(502,`speech upstream error: ${String(F.message??"upstream reported an error")}`)}if(L.type==="response.completed"){y=L.response??null,l=!0,_(),await E.return?.();break}}if(clearTimeout(v),k)throw new P(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 P(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let M=!1;if(await Promise.race([f,new Promise(x=>{g=setTimeout(()=>{M=!0,x()},o.capMs)})]),g!==void 0&&clearTimeout(g),r.voice!==void 0){let x=y[Xe];if(typeof x!="string"||x!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof x=="string"?`${Xe} ${JSON.stringify(x)}`:`no ${Xe} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new on(I):new P(502,I)}}if(!d)throw new P(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(M&&!c&&p.length<1)throw new P(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(b){throw b instanceof on||await Bu(t,n,E,s.returnBoundMs),b}finally{g!==void 0&&clearTimeout(g),v!==void 0&&clearTimeout(v),m()}})}function qu(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",rn)),t.write(u,a=>{a||(s+=u.byteLength,zs(e,s))}),t.writableLength>Gs&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Gs} 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[Xe];if(typeof a=="string"){if(!Ws(a))throw Ks(a);t.addTrailers({[rn]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function ju(t,e,n){let r;try{r=await t(e)}catch(o){throw Ue(o)}return r?!0:(er(n,new P(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 Gu={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Hu="wav, pcm";async function Ys(t,e,n){let r=n.maxBodyBytes??Lu,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new P(405,`${String(t.method)} is not supported on ${mt}`);let i;try{i=JSON.parse((await Zt(t,r)).toString("utf8")||"{}")}catch(v){throw v instanceof X?new P(413,v.message):new P(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new P(400,"request body must be a JSON object");let u=i;for(let v of Object.keys(u))if(!Gu[v])throw new P(400,`request field "${v}" 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.`,v);let a=u.input;if(typeof a!="string"||a.trim().length===0)throw new P(400,"input is required and must be a non-empty string","input");if(a.length>Ds)throw new P(400,`input is ${a.length} chars \u2014 over the ${Ds}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=u.model===void 0?void 0:u.model;if(d!==void 0&&typeof d!="string")throw new P(400,"model must be a string","model");let l=u.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new P(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new P(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 ${mt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(d)}catch(v){throw Ue(v)}if(c.defect!==null)throw new P(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof l=="string"?l:void 0;if(h!==void 0&&c.published.length>0&&!c.published.includes(h))throw new P(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let f=u.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new P(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Hu} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(u.stream_format!==void 0&&typeof u.stream_format!="string")throw new P(400,"stream_format, when present, must be a string","stream_format");let p=u.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new P(400,"speed, when present, must be a number","speed");if(p!==1)throw new P(400,`speed=${JSON.stringify(p)} 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 _=u.instructions;if(_!==void 0){if(typeof _!="string")throw new P(400,"instructions, when present, must be a string","instructions");if(_.trim().length>0)throw new P(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 $u(n.turn,n.clients,d);let m=Buffer.byteLength(JSON.stringify(u));if(n.stats?.request("audio_speech",m,m),!await ju(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new P(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 P(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 P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let y;try{y=await n.clients.speechSessionHandle(d)}catch(v){throw Ue(v)}let g;try{g=await n.clients.openAudioOn(y)}catch(v){throw Ue(v)}n.turn&&(n.turn.sessionId=g.sessionId);try{if(f==="wav"){let v=[],E=await Vs(n.clients,g,y,{model:d,text:a,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fs,returnBoundMs:n.turnReturnBoundMs??Bs},s,w=>v.push(w));if(E===null||s())return;let b=Buffer.concat(v);if(h===void 0){let w=E[Xe];if(typeof w=="string"){if(!Ws(w))throw Ks(w);e.setHeader(rn,w)}}zs(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Du(b.byteLength),b]))}else{let v=qu(e,n.turn,s,h===void 0),E;try{E=await Vs(n.clients,g,y,{model:d,text:a,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fs,returnBoundMs:n.turnReturnBoundMs??Bs},s,v.sink)}catch(b){let w=Ue(b);if(!v.started())throw w;n.turn&&(n.turn.streamError=!0),v.fail(w);return}if(E===null)return;try{await v.finish(E)}catch(b){let w=Ue(b);n.turn&&(n.turn.streamError=!0),v.fail(w);return}}}catch(v){throw Ue(v)}}catch(i){if(i instanceof X){er(e,new P(413,i.message));return}if(i instanceof P){er(e,i);return}throw i}}var sn="/v1/audio/transcriptions";function Xs(t){return t===sn}var Qs="/v1/audio/models",Vu=16*1024*1024,Ju=64*1024*1024,q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function tr(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 Zs(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 Wu(t){if(!Zs(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,d=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,l=t[u+14]|t[u+15]<<8;n={sampleRate:d,channels:a,bitsPerSample:l}}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 Ku(t,e,n){if(t){if(t.model=ne({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 zu(t,e){t&&(t.outputUnits=e.seconds)}async function Yu(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],u=null;for await(let a of s){if(i.push(a),a.type==="error"){let d=a.error??{},l=typeof d.type=="string"?d.type:"upstream_error",c=String(d.message??"upstream reported an error");throw new q(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(a.type==="response.completed"){u=a.response??null;break}}if(u===null)throw new q(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return We(i,u)}function ei(t){return t instanceof q?t:t instanceof N?new q(404,t.message):new q(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Xu(t,e,n){let r;try{r=await t(e)}catch(o){throw ei(o)}return r?!0:(tr(n,new q(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 Qu=new Set(["file","model","language","response_format"]);async function ti(t,e,n){let r=n.maxBodyBytes??Ju,o=n.maxAudioPartBytes??Vu;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${sn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new q(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await en(t,r)}catch(y){throw y instanceof X?new q(413,y.message):new q(400,String(y instanceof Error?y.message:y))}let u=new Map;for(let y of i.keys()){if(!Qu.has(y))throw new q(400,`form field "${y}" 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.`,y);u.set(y,(u.get(y)??0)+1)}for(let[y,g]of u)if(g>1)throw new q(400,`form field "${y}" appears ${g} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,y);let a=i.get("model");if(a!==null&&typeof a!="string")throw new q(400,"model must be a string field","model");let d=a===null?void 0:a,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new q(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,h=i.get("response_format")??"json";if(h!=="json")throw new q(400,`response_format ${JSON.stringify(h)} 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 f=i.get("file");if(!(f instanceof File))throw new q(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>o)throw new q(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await f.arrayBuffer());if(!Zs(p))throw new q(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 _=Wu(p);if(_===null)throw new q(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 Ku(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",p.length,p.length),!await Xu(n.transcriptionModels,d,e))return;let m=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let y=await Yu(n.clients,d,m,c,n.turn?ae(n.turn):void 0);zu(n.turn,_),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw ei(y)}}catch(s){if(s instanceof X){tr(e,new q(413,s.message));return}if(s instanceof q){tr(e,s);return}throw s}}var ri="/v1/usage/requests",ni=1e4,Zu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ee=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Qe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var oi=1024*1024;function nr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ee(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ee(`"${e}" must be an array of uuid strings`);if(n.length>ni)throw new Ee(`"${e}" carries ${n.length} ids; at most ${ni} 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"||!Zu.test(s))throw new Ee(`"${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 si(t){return nr(t,"inference_ids")}function an(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 Qe(`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 Qe(`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 pn=require("@urun-sh/core");var rr="/partners/huggingface/v1/billing/requests";function ed(t){return nr(t,"requestIds")}function td(t){return t>=200&&t<=399}function nd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&td(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ii(t,e){let n=ed(t),r=await e(n);return an(r,n),nd(r)}var rd={"/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 od(t){return rd[t]??null}var li=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function sd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function id(t){return t==="surface"}function ad(t){let e=t?.ledgerFailureReason;return li.includes(e)?e:"unknown"}var ud=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ai=["priced","unpriced"],dd={written:ai,already_written:ai,skipped:ud,failed:li},Dp=Object.entries(dd).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function ld(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function cd(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 pd=256,ui=4096,ht=12e4,fd=250,md=8e3,yt=[],di=new Set,_t=0,gt=!1;var gd=new Set;function hd(){return _t===0&&yt.length===0}function yd(){if(hd()){gt=!1;for(let t of[...gd])t()}}function ci(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
30
|
-
`}function _d(t){le(process.stdout,t)}function pi(t,e){try{t(e)}catch{}}function fi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??_d,o=od(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,c)=>{s({outcome:"skipped",reason:l}),pi(r,ci("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let 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 d={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:cd(e),completed_at:e.ts,billable_outcome:ld(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(yt.length>=ui){i("queue_full",`${yt.length} ledger writes are already waiting (capacity ${ui}, ${_t} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}yt.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),_t<pd&&(_t+=1,wd())}async function wd(){try{for(;;){let t=vd();if(t===void 0)return;di.add(t);try{await bd(t)}finally{di.delete(t)}}}finally{_t-=1,yd()}}function vd(){let t=Date.now();for(;;){let e=yt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<ht)return e;Ze(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 ${ht}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 bd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Ze(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=sd(o);if(s!==null){Ze(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=ad(o),u=Date.now()-t.queuedAt;if(gt){Ze(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(id(i)&&u<ht){if(await kd(Sd(t.attempts)),gt||Date.now()-t.queuedAt>=ht){let a=Date.now()-t.queuedAt;Ze(t,{outcome:"failed",reason:gt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:gt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${ht}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}Ze(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 Sd(t){return Math.min(md,fd*2**Math.max(0,t-1))}function kd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ze(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;pi(t.report,ci(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var sr="x-urun-profile",wt="voice";var oe=class extends Error{status=400},xd=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Rd=/\s/;function Ed(t){return xd.test(t)}function or(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new oe(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function mi(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 oe(`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 oe(`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 oe(`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 gi(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 oe(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let d=n.trim();if(d==="")throw new oe(`the ${sr} header is empty \u2014 the only profile this lane accepts is "${wt}" (omit the header for the ordinary lane)`);if(d!==wt)throw new oe(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${wt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==wt)throw new oe(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${wt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new oe("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 oe("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:mi(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:mi(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 un=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&&Ed(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(Rd.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)}};function ur(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Ad(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 ee(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function K(t,e,n,r="invalid_request_error",o){ee(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function dr(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);ee(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function me(t,e,n,r){ee(t,e,{type:"error",error:{type:n,message:r}})}function et(t,e,n){if(e==="anthropic"){ee(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ee(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Id=64*1024*1024,vt=class extends Error{};async function hi(t,e=Id){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new vt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ne(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 dn(t){let e=wi(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function yi(t){let e=dn(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 Od(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 Td(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let d=n[a];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d: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 Pd(t,e){let n=Td(e);n&&(t.timing=n)}function De(t,e){Od(t,e),Pd(t,e)}async function fn(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 vi(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 Cd(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 ln=class extends Error{};function Md(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 ln(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Ld(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:Md(n.role,n.content)})}return e}function ir(t){return Ve(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 $d(t,e,n,r,o,s){let i=ut(s.id),u=t.stream===!0;if(s.model=ne(t),s.stream=u,await fn(s,e,typeof t.model=="string"?t.model:void 0),u){let y;try{y=await lt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(g){if(g instanceof N){et(r,"openai",g);return}if(g instanceof ue){K(r,g.status,g.message);return}throw g}ur(r);for await(let g of y.events)g.type==="error"&&(s.streamError=!0),g.type==="response.completed"&&De(s,g.response),r.write(`event: ${String(g.type??"message")}
|
|
31
|
-
data: ${JSON.stringify(
|
|
27
|
+
${ku(n)}\r
|
|
28
|
+
`),t.destroy()}function Ru(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
29
|
+
`}function Eu(t){le(process.stdout,t)}function Au(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Qn(t){return t.audioSession?.audio.sessionId??void 0}function er(t,e){let n=new xs.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Zn)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=R("rtup"),d=Au(o),l=b=>{(e.log??Eu)(Ru(b))};l({stage:"accept",conn:u,model:d}),s.resume();let c=new AbortController,m=null,f=b=>{m??=b,c.abort(new Error(m))},p=()=>f("client socket closed"),y=()=>f("client socket closed (half-close)"),g=b=>f(`client socket error: ${b.message}`);s.once("close",p),s.once("end",y),s.once("error",g);let _=()=>{s.removeListener("close",p),s.removeListener("end",y),s.removeListener("error",g)},h=b=>{l({stage:"close",conn:u,model:d,...b})},v=b=>{let w=b,k=w.session!=null&&typeof w.session.sendResponseCreate=="function",C=w.clients!=null&&typeof w.clients.createResponse=="function";if(!k&&!C)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((x,A)=>{n.handleUpgrade(o,s,i,M=>{try{new ft({ws:M,binding:b,onClosed:(D,W)=>{h({while:"live",reason:W.reason})}}),l({stage:"admit",conn:u,model:d,...Qn(b)===void 0?{}:{session:Qn(b)}}),x()}catch(D){A(D)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal).then(async b=>{if(c.signal.aborted){_();let w=Qn(b);try{await b.release?.()}catch(k){h({while:"queued",...w===void 0?{}:{session:w},reason:m??"client socket closed",release_failed:k instanceof Error?k.message:String(k)});return}h({while:"queued",...w===void 0?{}:{session:w},reason:m??"client socket closed",released:!0}),s.destroy();return}_(),await v(b)}).catch(b=>{let w=b instanceof ks.SessionFailedError?Wt(b):null,k=null;if(b!==null&&typeof b=="object"&&"status"in b){let A=b.status;typeof A=="number"&&(k=A)}let C=k??w?.status??502,x=b instanceof Error?b.message:String(b);h({while:"queued",...c.signal.aborted?{reason:m??"client socket closed"}:{reason:x,status:C}}),s.destroyed||xu(s,C,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 ce=(t,e)=>Object.assign(new Error(e),{status:t});function Iu(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Ou(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Tu='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Pu(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 N?ce(404,d.message):d}if(!o)throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudioOn)throw 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 N?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(l){throw l instanceof N?ce(404,l.message):l}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: ${Tu}`);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=await t.sessionHandle(e),a={audio:await t.openAudioOn(i,n)},u={clients:{createResponse:async d=>await t.createResponseOn(i,d)},voice:o,audioSession:a};return s&&(u.turns=d=>t.openTurnsOn(i,d)),r==="transcription"&&(u.intent="transcription"),e!==void 0&&(u.model=e),u}function Rs(t,e){return{resolve:async(n,r)=>{if(e!==void 0){let o=n.headers.authorization,s=typeof o=="string"?o.trim():"",i=s.startsWith("Bearer ")?s.slice(7).trim():"";if(i===""||i!==e)throw ce(401,"invalid local proxy api key")}return Pu(t,Iu(n),r,Ou(n))}}}var X=class extends Error{};async function en(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new X(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new X(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function tn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new X(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[d,l]of Object.entries(t.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let c of l)i.append(d,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof X?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Es="/v1/images/generations",nn="/v1/images/edits";function As(t){return t===Es||t===nn}var Is="/v1/images/models";async function Os(t,e,n){if(t){if(t.model=ne({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 $=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Cu=16*1024*1024,Ts=64*1024*1024;function Ps(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 Cs(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),i=null;for await(let m of s){if(m.type==="error"){let f=m.error??{};throw new $(502,`image upstream error: ${String(f.message??"upstream reported an error")}`)}if(m.type==="response.completed"){i=m.response??null;break}}if(i===null)throw new $(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=we(i));let a=i.images;if(!Array.isArray(a)||a.length!==1||typeof a[0]!="string"||a[0].length===0)throw new $(502,`image upstream returned ${Array.isArray(a)?a.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 u=[],d=a[0].startsWith("data:")?a[0].slice(a[0].indexOf(";base64,")+8):a[0],l=Buffer.from(d,"base64");if(Ps(l)===null)throw new $(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${l.length} bytes) \u2014 refusing to pass it through`);return u.push(d),{images:u}}function Ms(t){return t instanceof $?t:t instanceof N?new $(404,t.message):new $(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Ls(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 $(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 $s(t,e){t&&(t.outputUnits=e.images.length)}function Us(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 Mu={model:!0,prompt:!0,response_format:!0,n:!0};async function Ns(t,e,n){let r=n.maxBodyBytes??Ts;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${Es}`);let o;try{o=JSON.parse((await en(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof X?new $(413,c.message):new $(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new $(400,"request body must be a JSON object");let s=o;for(let c of Object.keys(s))if(!Mu[c])throw new $(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new $(400,"model must be a string","model");await Os(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new $(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new $(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await Ls(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await Cs(n.clients,a,l,n.turn?ae(n.turn):void 0,n.turn);$s(n.turn,c),Us(e,c)}catch(c){throw Ms(c)}}catch(o){if(o instanceof X){mt(e,new $(413,o.message));return}if(o instanceof $){mt(e,o);return}throw o}}var Lu={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ds(t,e,n){let r=n.maxBodyBytes??Ts,o=n.maxImagePartBytes??Cu;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${nn}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new $(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await tn(t,r)}catch(f){throw f instanceof X?new $(413,f.message):new $(400,String(f instanceof Error?f.message:f))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new $(400,"model must be a string field","model");let d=u===null?void 0:u;await Os(n.turn,n.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new $(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of i.keys())if(!Lu[f])throw new $(400,`form field "${f}" 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[]).`,f);let c=[];for(let f of["image","image[]"])for(let p of i.getAll(f)){if(!(p instanceof File))throw new $(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(p.size>o)throw new $(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let y=new Uint8Array(await p.arrayBuffer()),g=Ps(y);if(g===null)throw new $(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);c.push({bytes:y,mime:g})}if(c.length===0)throw new $(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Ls(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:f,mime:p}of c)m.push({type:"input_image",image_url:`data:${p};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Cs(n.clients,d,m,n.turn?ae(n.turn):void 0,n.turn);$s(n.turn,f),Us(e,f)}catch(f){throw Ms(f)}}catch(s){if(s instanceof X){mt(e,new $(413,s.message));return}if(s instanceof $){mt(e,s);return}throw s}}var gt="/v1/audio/speech";function Ws(t){return t===gt}var Fs=4096,Bs=18e4,qs=5e3,$u=64*1024*1024,js=8,Gs=5,Hs=1024*1024,Qe="voice_applied",on="X-Urun-Voice-Applied",P=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function tr(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 sn=class extends P{constructor(e){super(502,e)}};function Ks(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 zs(t){return new P(502,`the runtime's ${Qe} 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 Uu(t,e,n){if(t){if(t.model=ne({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 Ys(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var Nu=2;function Du(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Nu)return!1;return!0}function Fu(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 Vs=new WeakMap,rn=new WeakMap;function Bu(t,e){let n=rn.get(t)??0;if(n>=js)throw new P(503,`this model's speech queue is full \u2014 ${js} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Gs}s`,void 0,Gs);rn.set(t,n+1);let r=Vs.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Vs.set(t,s),(async()=>{await r;try{return await e()}finally{rn.set(t,(rn.get(t)??1)-1),o()}})()}async function qu(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new P(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 Ne(t){return t instanceof P?t:t instanceof N?new P(404,t.message):new P(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Js(t,e,n,r,o,s,i,a,u){let d=a??(()=>{});return Bu(e,async()=>{if(i?.()===!0)return null;let l=!1,c=!1,m=!1,f,p=new Promise(w=>{f=w}),y=[],g=()=>{c&&!m&&y.length>=o.quietRunFrames&&(m=!0,f())},_=e.onOutputAudio(w=>{let k=Buffer.from(w,"base64");if(k.byteLength===0)return;let C=Du(k);if(!l){if(C)return;l=!0}if(C){y.push(k),g();return}for(let x of y)d(x);y.length=0,d(k),g()}),h=null,v,E,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 k=new Promise(A=>{E=setTimeout(A,s.capMs)}),C=!1;for(;;){let A=b.next(),M=await Promise.race([A,k]);if(M===void 0){C=!0,A.catch(()=>{});break}if(M.done)break;let D=M.value;if(D.type==="error"){let W=D.error??{};throw await b.return?.(),new P(502,`speech upstream error: ${String(W.message??"upstream reported an error")}`)}if(D.type==="response.completed"){h=D.response??null,c=!0,u?.(h),g(),await b.return?.();break}}if(clearTimeout(E),C)throw new P(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 P(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let x=!1;if(await Promise.race([p,new Promise(A=>{v=setTimeout(()=>{x=!0,A()},o.capMs)})]),v!==void 0&&clearTimeout(v),r.voice!==void 0){let A=h[Qe];if(typeof A!="string"||A!==r.voice){let M=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof A=="string"?`${Qe} ${JSON.stringify(A)}`:`no ${Qe} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new sn(M):new P(502,M)}}if(!l)throw new P(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(x&&!m&&y.length<1)throw new P(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(w){throw w instanceof sn||await qu(t,n,b,s.returnBoundMs),w}finally{v!==void 0&&clearTimeout(v),E!==void 0&&clearTimeout(E),_()}})}function ju(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",on)),t.write(a,u=>{u||(s+=a.byteLength,Ys(e,s))}),t.writableLength>Hs&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Hs} 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(a){if(!n()){if(r){let u=a[Qe];if(typeof u=="string"){if(!Ks(u))throw zs(u);t.addTrailers({[on]:u})}}await new Promise(u=>{t.end(()=>u())})}},fail:i}}async function Gu(t,e,n){let r;try{r=await t(e)}catch(o){throw Ne(o)}return r?!0:(tr(n,new P(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 Hu={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Vu="wav, pcm";async function Xs(t,e,n){let r=n.maxBodyBytes??$u,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new P(405,`${String(t.method)} is not supported on ${gt}`);let i;try{i=JSON.parse((await en(t,r)).toString("utf8")||"{}")}catch(v){throw v instanceof X?new P(413,v.message):new P(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new P(400,"request body must be a JSON object");let a=i;for(let v of Object.keys(a))if(!Hu[v])throw new P(400,`request field "${v}" 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.`,v);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new P(400,"input is required and must be a non-empty string","input");if(u.length>Fs)throw new P(400,`input is ${u.length} chars \u2014 over the ${Fs}-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 P(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new P(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new P(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 ${gt} against a stale copy of the list`);let c;try{c=await n.clients.speechVoices(d)}catch(v){throw Ne(v)}if(c.defect!==null)throw new P(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof l=="string"?l:void 0;if(m!==void 0&&c.published.length>0&&!c.published.includes(m))throw new P(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let f=a.response_format??"wav";if(f!=="wav"&&f!=="pcm")throw new P(400,`response_format ${JSON.stringify(f)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Vu} \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 P(400,"stream_format, when present, must be a string","stream_format");let p=a.speed;if(p!==void 0){if(typeof p!="number"||!Number.isFinite(p))throw new P(400,"speed, when present, must be a number","speed");if(p!==1)throw new P(400,`speed=${JSON.stringify(p)} 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 y=a.instructions;if(y!==void 0){if(typeof y!="string")throw new P(400,"instructions, when present, must be a string","instructions");if(y.trim().length>0)throw new P(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 Uu(n.turn,n.clients,d);let g=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",g,g),!await Gu(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new P(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 P(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 P(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(s())return;let _;try{_=await n.clients.speechSessionHandle(d)}catch(v){throw Ne(v)}let h;try{h=await n.clients.openAudioOn(_)}catch(v){throw Ne(v)}n.turn&&(n.turn.sessionId=h.sessionId);try{if(f==="wav"){let v=[],E=await Js(n.clients,h,_,{model:d,text:u,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Bs,returnBoundMs:n.turnReturnBoundMs??qs},s,w=>v.push(w),w=>{n.turn&&(n.turn.outputSeconds=we(w))});if(E===null||s())return;let b=Buffer.concat(v);if(m===void 0){let w=E[Qe];if(typeof w=="string"){if(!Ks(w))throw zs(w);e.setHeader(on,w)}}Ys(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Fu(b.byteLength),b]))}else{let v=ju(e,n.turn,s,m===void 0),E;try{E=await Js(n.clients,h,_,{model:d,text:u,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Bs,returnBoundMs:n.turnReturnBoundMs??qs},s,v.sink,b=>{n.turn&&(n.turn.outputSeconds=we(b))})}catch(b){let w=Ne(b);if(!v.started())throw w;n.turn&&(n.turn.streamError=!0),v.fail(w);return}if(E===null)return;try{await v.finish(E)}catch(b){let w=Ne(b);n.turn&&(n.turn.streamError=!0),v.fail(w);return}}}catch(v){throw Ne(v)}}catch(i){if(i instanceof X){tr(e,new P(413,i.message));return}if(i instanceof P){tr(e,i);return}throw i}}var an="/v1/audio/transcriptions";function Qs(t){return t===an}var Zs="/v1/audio/models",Ju=16*1024*1024,Wu=64*1024*1024,q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function nr(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 ei(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 Ku(t){if(!ei(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let u=t[a+2]|t[a+3]<<8,d=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,l=t[a+14]|t[a+15]<<8;n={sampleRate:d,channels:u,bitsPerSample:l}}else if(s==="data"){let u=t.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function zu(t,e,n){if(t){if(t.model=ne({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 Yu(t,e){t&&(t.outputUnits=e.seconds)}async function Xu(t,e,n,r,o,s){let i=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),a=[],u=null;for await(let d of i){if(a.push(d),d.type==="error"){let l=d.error??{},c=typeof l.type=="string"?l.type:"upstream_error",m=String(l.message??"upstream reported an error");throw new q(c==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(d.type==="response.completed"){u=d.response??null;break}}if(u===null)throw new q(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=we(u)),Ke(a,u)}function ti(t){return t instanceof q?t:t instanceof N?new q(404,t.message):new q(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Qu(t,e,n){let r;try{r=await t(e)}catch(o){throw ti(o)}return r?!0:(nr(n,new q(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 Zu=new Set(["file","model","language","response_format"]);async function ni(t,e,n){let r=n.maxBodyBytes??Wu,o=n.maxAudioPartBytes??Ju;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${an}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new q(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await tn(t,r)}catch(_){throw _ instanceof X?new q(413,_.message):new q(400,String(_ instanceof Error?_.message:_))}let a=new Map;for(let _ of i.keys()){if(!Zu.has(_))throw new q(400,`form field "${_}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,_);a.set(_,(a.get(_)??0)+1)}for(let[_,h]of a)if(h>1)throw new q(400,`form field "${_}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,_);let u=i.get("model");if(u!==null&&typeof u!="string")throw new q(400,"model must be a string field","model");let d=u===null?void 0:u,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new q(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,m=i.get("response_format")??"json";if(m!=="json")throw new q(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let f=i.get("file");if(!(f instanceof File))throw new q(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(f.size>o)throw new q(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let p=new Uint8Array(await f.arrayBuffer());if(!ei(p))throw new q(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 y=Ku(p);if(y===null)throw new q(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 zu(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",p.length,p.length),!await Qu(n.transcriptionModels,d,e))return;let g=[{type:"input_audio",input_audio:{data:Buffer.from(p).toString("base64"),format:"wav"}}];try{let _=await Xu(n.clients,d,g,c,n.turn?ae(n.turn):void 0,n.turn);Yu(n.turn,y),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:_}))}catch(_){throw ti(_)}}catch(s){if(s instanceof X){nr(e,new q(413,s.message));return}if(s instanceof q){nr(e,s);return}throw s}}var oi="/v1/usage/requests",ri=1e4,ed=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ae=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Ze=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var si=1024*1024;function rr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ae(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ae(`"${e}" must be an array of uuid strings`);if(n.length>ri)throw new Ae(`"${e}" carries ${n.length} ids; at most ${ri} 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"||!ed.test(s))throw new Ae(`"${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 ii(t){return rr(t,"inference_ids")}function un(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 Ze(`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 Ze(`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 fn=require("@urun-sh/core");var or="/partners/huggingface/v1/billing/requests";function td(t){return rr(t,"requestIds")}function nd(t){return t>=200&&t<=399}function rd(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&nd(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ai(t,e){let n=td(t),r=await e(n);return un(r,n),rd(r)}var od={"/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 sd(t){return od[t]??null}var ci=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function id(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ad(t){return t==="surface"}function ud(t){let e=t?.ledgerFailureReason;return ci.includes(e)?e:"unknown"}var dd=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ui=["priced","unpriced"],ld={written:ui,already_written:ui,skipped:dd,failed:ci},Fp=Object.entries(ld).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function cd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function pd(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 fd=256,di=4096,yt=12e4,md=250,gd=8e3,_t=[],li=new Set,wt=0,ht=!1;var hd=new Set;function yd(){return wt===0&&_t.length===0}function _d(){if(yd()){ht=!1;for(let t of[...hd])t()}}function pi(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
30
|
+
`}function wd(t){le(process.stdout,t)}function fi(t,e){try{t(e)}catch{}}function mi(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??wd,o=sd(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,c)=>{s({outcome:"skipped",reason:l}),fi(r,pi("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:pd(e),completed_at:e.ts,billable_outcome:cd(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(_t.length>=di){i("queue_full",`${_t.length} ledger writes are already waiting (capacity ${di}, ${wt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}_t.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),wt<fd&&(wt+=1,vd())}async function vd(){try{for(;;){let t=bd();if(t===void 0)return;li.add(t);try{await Sd(t)}finally{li.delete(t)}}}finally{wt-=1,_d()}}function bd(){let t=Date.now();for(;;){let e=_t.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<yt)return e;et(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${yt}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function Sd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);et(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=id(o);if(s!==null){et(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=ud(o),a=Date.now()-t.queuedAt;if(ht){et(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(ad(i)&&a<yt){if(await xd(kd(t.attempts)),ht||Date.now()-t.queuedAt>=yt){let u=Date.now()-t.queuedAt;et(t,{outcome:"failed",reason:ht?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:ht?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${yt}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}et(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function kd(t){return Math.min(gd,md*2**Math.max(0,t-1))}function xd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function et(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;fi(t.report,pi(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var ir="x-urun-profile",vt="voice";var oe=class extends Error{status=400},Rd=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Ed=/\s/;function Ad(t){return Rd.test(t)}function sr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new oe(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function gi(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 oe(`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 oe(`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 oe(`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 hi(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 oe(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let d=n.trim();if(d==="")throw new oe(`the ${ir} header is empty \u2014 the only profile this lane accepts is "${vt}" (omit the header for the ordinary lane)`);if(d!==vt)throw new oe(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${vt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==vt)throw new oe(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${vt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new oe("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new oe("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:gi(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:gi(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:sr(u,"sentence_flush",!0),includeReasoning:sr(u,"include_reasoning",!1),metadata:sr(u,"metadata",!1)}}var dn=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&&Ad(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(Ed.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)}};function dr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Id(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 ee(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){ee(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function lr(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);ee(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function me(t,e,n,r){ee(t,e,{type:"error",error:{type:n,message:r}})}function tt(t,e,n){if(e==="anthropic"){ee(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ee(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Od=64*1024*1024,bt=class extends Error{};async function yi(t,e=Od){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new bt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function De(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 vi(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function ln(t){let e=vi(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function _i(t){let e=ln(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 Td(t,e){let n=vi(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Pd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function Cd(t,e){let n=Pd(e);n&&(t.timing=n),t.outputSeconds=we(e)}function Fe(t,e){Td(t,e),Cd(t,e)}async function mn(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 bi(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 Md(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 cn=class extends Error{};function Ld(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 cn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function $d(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:Ld(n.role,n.content)})}return e}function ar(t){return Je(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 Ud(t,e,n,r,o,s){let i=dt(s.id),a=t.stream===!0;if(s.model=ne(t),s.stream=a,await mn(s,e,typeof t.model=="string"?t.model:void 0),a){let _;try{_=await ct({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(h){if(h instanceof N){tt(r,"openai",h);return}if(h instanceof ue){z(r,h.status,h.message);return}throw h}dr(r);for await(let h of _.events)h.type==="error"&&(s.streamError=!0),h.type==="response.completed"&&Fe(s,h.response),r.write(`event: ${String(h.type??"message")}
|
|
31
|
+
data: ${JSON.stringify(h)}
|
|
32
32
|
|
|
33
33
|
`);r.write(`data: [DONE]
|
|
34
34
|
|
|
35
|
-
`),r.end();return}let
|
|
35
|
+
`),r.end();return}let u;try{u=ze(n,t)}catch(_){if(_ instanceof ue){z(r,_.status,_.message);return}throw _}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,l=ne(t);o.model(l);let c=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await $n(e,t,u,!1,ae(s))}catch(_){if(_ instanceof N){tt(r,"openai",_);return}if(_ instanceof ue){z(r,_.status,_.message);return}throw _}let f=[],p=null;for await(let _ of o.track(m,l,s)){if(f.push(_),_.type==="error"){lr(r,_);return}_.type==="response.completed"&&(p=_.response)}if(p==null){z(r,502,"upstream produced no response.completed event","upstream_error");return}Fe(s,p);let y=Ke(f,p),g=Ue(c,Je(p).length,y);if(g){z(r,502,$e(l,g),"upstream_error");return}d&&n.remember(i,u,Ln(p,y),d),ee(r,200,{...p,id:i})}async function Nd(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){z(n,400,"chat/completions requires a messages array");return}let a;try{a=hi(s,t)}catch(x){if(x instanceof oe){z(n,x.status,x.message);return}throw x}let u=String(t.model??"urun"),d=qo(o.id),l;try{l=$d(i)}catch(x){if(x instanceof cn){z(n,400,x.message);return}throw x}let c=ne(t);r.model(c),o.model=c,o.stream=t.stream===!0,await mn(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await e.createResponse({model:t.model,input:l,stream:!0,tools:Md(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}:{}},ae(o))}catch(x){if(x instanceof N){tt(n,"openai",x);return}throw x}if(t.stream===!0){a?Id(n):dr(n);let x=[],A=new Re,M="",D=a?new dn(a,te=>{n.write(`data: ${JSON.stringify(De(d,u,{content:te},null))}
|
|
36
36
|
|
|
37
|
-
`)}):null,
|
|
37
|
+
`)}):null,W=te=>{D?.flush(),n.write(te),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
|
|
38
38
|
|
|
39
|
-
`),n.write(`data: ${JSON.stringify(
|
|
39
|
+
`),n.write(`data: ${JSON.stringify(De(d,u,{role:"assistant"},null))}
|
|
40
40
|
|
|
41
|
-
`);for await(let V of r.track(f,c,o)){x.push(V);let Q=
|
|
41
|
+
`);for await(let V of r.track(f,c,o)){x.push(V);let Q=We(V);if(V.type==="response.output_text.delta"&&typeof V.delta=="string")M+=V.delta,D?D.push(V.delta):n.write(`data: ${JSON.stringify(De(d,u,{content:V.delta},null))}
|
|
42
42
|
|
|
43
|
-
`);else if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")(!
|
|
43
|
+
`);else if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(De(d,u,{reasoning_content:V.delta},null))}
|
|
44
44
|
|
|
45
|
-
`);else if(Q){
|
|
45
|
+
`);else if(Q){D?.flush();let{call:Ie,isNew:T}=A.add(Q),U=T?{index:Q.tool_index,id:Ie.id??`call_${Q.tool_index}`,type:"function",function:{name:Ie.name??"",arguments:Q.delta}}:{index:Q.tool_index,function:{arguments:Q.delta}};n.write(`data: ${JSON.stringify(De(d,u,{tool_calls:[U]},null))}
|
|
46
46
|
|
|
47
|
-
`)}else if(V.type==="error"){o.streamError=!0,
|
|
47
|
+
`)}else if(V.type==="error"){o.streamError=!0,W(`data: ${JSON.stringify({error:V})}
|
|
48
48
|
|
|
49
|
-
`);return}}let te=
|
|
49
|
+
`);return}}let te=ar(fe(x)),de=Ue(m,A.size+te.length,M);if(de){o.streamError=!0,W(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:$e(c,de)}})}
|
|
50
50
|
|
|
51
|
-
`);return}
|
|
51
|
+
`);return}D?.flush(),A.size===0&&te.length>0&&n.write(`data: ${JSON.stringify(De(d,u,{tool_calls:te},null))}
|
|
52
52
|
|
|
53
|
-
`);let
|
|
53
|
+
`);let ve=A.size>0||te.length>0;n.write(`data: ${JSON.stringify(De(d,u,{},ve?"tool_calls":"stop"))}
|
|
54
54
|
|
|
55
|
-
`);let H=
|
|
55
|
+
`);let H=ln(fe(x));Fe(o,fe(x)),H&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:_i(fe(x))})}
|
|
56
56
|
|
|
57
57
|
`),n.write(`data: [DONE]
|
|
58
58
|
|
|
59
|
-
`),n.end();return}finally{
|
|
60
|
-
data: ${JSON.stringify({type:k,...
|
|
59
|
+
`),n.end();return}finally{D?.flush(),D?.dispose()}}let p="",y="",g=[],_=new Re;for await(let x of r.track(f,c,o)){g.push(x),x.type==="response.output_text.delta"&&typeof x.delta=="string"&&(p+=x.delta),x.type==="response.reasoning_text.delta"&&typeof x.delta=="string"&&(y+=x.delta);let A=We(x);if(A&&_.add(A),x.type==="error"){lr(n,x);return}}let h=fe(g);Fe(o,h);let v=ar(h),E=v.length>0?v:ar({output:_.items()}),b=Ue(m,E.length,p);if(b){z(n,502,$e(c,b),"upstream_error");return}let w=E.map(({index:x,...A})=>A),k={role:"assistant",content:p||null},C=y||bi(h);C&&(k.reasoning_content=C),w.length>0&&(k.tool_calls=w),ee(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:k,finish_reason:w.length>0?"tool_calls":"stop"}],usage:_i(h)})}var Dd="sense-latest";async function Fd(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){z(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:Dd,i=ne({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){z(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){z(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){z(n,400,"systemone media, when present, must be an array");return}let u={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};o.decision=u;let d=performance.now();r.model(i),await mn(o,e,s),u.resolve_ms=Math.round(performance.now()-d);let l,c=performance.now();try{l=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},ae(o))}catch(_){if(_ instanceof N){tt(n,"openai",_);return}if(_ instanceof Te){n.setHeader("retry-after","2"),z(n,503,_.message,"capacity_error");return}throw _}u.dial_ms=Math.round(performance.now()-c);let m=[],f=null;try{for await(let _ of r.track(l,i,o))if(f===null&&(f=performance.now(),u.first_event_ms=Math.round(f-c)),m.push(_),_.type==="error"){lr(n,_);return}}catch(_){if(_ instanceof N){f!==null&&(u.stream_ms=Math.round(performance.now()-f)),tt(n,"openai",_);return}if(_ instanceof Te){f!==null&&(u.stream_ms=Math.round(performance.now()-f)),n.setHeader("retry-after","2"),z(n,503,_.message,"capacity_error");return}throw f!==null&&(u.stream_ms=Math.round(performance.now()-f)),_}f!==null&&(u.stream_ms=Math.round(performance.now()-f));let p=fe(m);if(p==null){z(n,502,"upstream produced no response.completed event","upstream_error");return}Fe(o,p);let y=Ke(m,p),g;try{g=JSON.parse(y)}catch{z(n,502,"systemone answer was not valid JSON","upstream_error");return}if(g===null||typeof g!="object"||Array.isArray(g)){z(n,502,"systemone answer was not a JSON object","upstream_error");return}if(typeof g=="object"&&g!==null&&!Array.isArray(g)&&"timing"in g){let _=g.timing;if(typeof _=="object"&&_!==null&&!Array.isArray(_)&&"question_fwd_ms"in _&&"head_ms"in _){let h=v=>typeof v=="number"&&Number.isFinite(v)&&v>=0?Math.round(v):null;u.question_fwd_ms=h(_.question_fwd_ms),u.head_ms=h(_.head_ms)}}ee(n,200,g)}function Bd(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var St=class extends Error{};function pn(t){return new St(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function qd(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 St(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Gd(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw pn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw pn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Hd(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 pn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:Gd(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw pn(a)}}return s(),r}function ur(t){return Je(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 Vd(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){me(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){me(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){me(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(k=>typeof k!="string"))){me(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=jo(o.id),u=[],d;try{t.system&&u.push({role:"system",content:Bd(t.system)});for(let k of s)u.push(...Hd(k));d=jd(t.tool_choice)}catch(k){if(k instanceof St){me(n,400,"invalid_request_error",k.message);return}throw k}let l=ne(t);r.model(l),o.model=l,o.stream=t.stream===!0,await mn(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:u,stream:!0,tools:qd(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ae(o))}catch(k){if(k instanceof N){tt(n,"anthropic",k);return}throw k}let f=(k,C)=>{n.destroyed||n.write(`event: ${k}
|
|
60
|
+
data: ${JSON.stringify({type:k,...C})}
|
|
61
61
|
|
|
62
|
-
`)};if(t.stream===!0){let k=r.track(
|
|
62
|
+
`)};if(t.stream===!0){let k=r.track(m,l,o);dr(n),f("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let C=0,x="",A=0,M="none",D=()=>M,W=-1,te=-1,de=new Re,ve=[],H=()=>{M!=="none"&&(M="none",f("content_block_stop",{index:W}))},V=(B,Z)=>{H(),M=B,W=A++,f("content_block_start",{index:W,content_block:Z})};for await(let B of k){if(n.destroyed)break;ve.push(B);let Z=We(B);if(B.type==="response.reasoning_text.delta"&&typeof B.delta=="string")D()!=="thinking"&&V("thinking",{type:"thinking",thinking:""}),f("content_block_delta",{index:W,delta:{type:"thinking_delta",thinking:B.delta}});else if(B.type==="response.output_text.delta"&&typeof B.delta=="string")D()!=="text"&&V("text",{type:"text",text:""}),C+=1,x+=B.delta,f("content_block_delta",{index:W,delta:{type:"text_delta",text:B.delta}});else if(Z){let{call:be}=de.add(Z);(D()!=="tool"||Z.tool_index!==te)&&(te=Z.tool_index,V("tool",{type:"tool_use",id:be.id??`call_${Z.tool_index}`,name:be.name??"",input:{}})),Z.delta&&f("content_block_delta",{index:W,delta:{type:"input_json_delta",partial_json:Z.delta}})}else if(B.type==="error"){o.streamError=!0,f("error",{error:{type:"api_error",message:JSON.stringify(B)}}),n.end();return}}if(n.destroyed)return;let Q=fe(ve),Ie=Je(Q),T=Ue(c,de.size+Ie.length,x);if(T){o.streamError=!0,f("error",{error:{type:"api_error",message:$e(l,T)}}),n.end();return}H();let U=[];if(de.size===0)try{U=ur(Q)}catch(B){o.streamError=!0,f("error",{error:{type:"api_error",message:String(B instanceof Error?B.message:B)}}),n.end();return}A===0&&U.length===0&&(V("text",{type:"text",text:""}),H()),U.forEach(B=>{let Z=A++;f("content_block_start",{index:Z,content_block:{...B,input:{}}}),f("content_block_delta",{index:Z,delta:{type:"input_json_delta",partial_json:JSON.stringify(B.input??{})}}),f("content_block_stop",{index:Z})});let Y=de.size>0||U.length>0,ge=ln(Q);Fe(o,Q),f("message_delta",{delta:{stop_reason:Y?"tool_use":"end_turn"},usage:ge?{input_tokens:ge.input_tokens,output_tokens:ge.output_tokens}:{output_tokens:C}}),f("message_stop",{}),n.end();return}let p="",y="",g=[],_=new Re;for await(let k of r.track(m,l,o)){g.push(k),k.type==="response.output_text.delta"&&typeof k.delta=="string"&&(p+=k.delta),k.type==="response.reasoning_text.delta"&&typeof k.delta=="string"&&(y+=k.delta);let C=We(k);if(C&&_.add(C),k.type==="error"){let x=k.error,A=x?.type==="invalid_request_error";me(n,A?400:502,A?"invalid_request_error":"api_error",x?.message??JSON.stringify(k));return}if(n.destroyed)break}if(n.destroyed)return;let h=fe(g);Fe(o,h);let v;try{v=ur(h),v.length===0&&_.size>0&&(v=ur({output:_.items()}))}catch(k){me(n,502,"api_error",String(k instanceof Error?k.message:k));return}let E=Ue(c,v.length,p);if(E){me(n,502,"api_error",$e(l,E));return}let b=[],w=y||bi(h);w&&b.push({type:"thinking",thinking:w}),(p||v.length===0)&&b.push({type:"text",text:p}),b.push(...v),ee(n,200,{id:a,type:"message",role:"assistant",content:b,model:i,stop_reason:v.length>0?"tool_use":"end_turn",usage:ln(h)??{input_tokens:0,output_tokens:0}})}function Jd(t){le(process.stdout,t)}function Wd(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??Jd,a=t.observe,u=new Me;return(d,l)=>{let c=new URL(d.url??"/","http://localhost"),m=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),f=(h,v,E,b,w)=>m?me(l,h,b,v):z(l,h,v,E,w),p=Mn(c.pathname),y=c.pathname.startsWith("/partners/"),g=p||y?{id:ut(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;g&&(l.setHeader(Fo,g.id),l.once("close",()=>{let h=Go({turn:g,method:d.method??"",path:c.pathname,res:l});i(Ho(h)),a?.(h),mi({record:h,ledger:t.ledger??null,req:d})}));let _=()=>Bo(c.pathname,g);(async()=>{if(d.method==="GET"&&c.pathname==="/healthz"){ee(l,200,{ok:!0});return}if(d.method==="GET"&&c.pathname==="/stats"){ee(l,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){f(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=c.pathname===oi?"canonical":c.pathname===or?"huggingface":null;if(h){if(d.method!=="POST"){f(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let w=t.usage;if(!w){f(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let k=w.authorize(d),C;try{C=await yi(d,si)}catch(M){if(M instanceof bt){f(413,M.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let x=M=>w.lookup(k,M),A;try{if(h==="canonical"){let M=ii(C),D=await x(M);un(D,M),A={requests:D}}else A=await ai(C,x)}catch(M){if(M instanceof Ae){f(M.status,M.message,"invalid_request_error","invalid_request_error");return}throw M}ee(l,200,A);return}if(d.method==="GET"&&c.pathname===st){let w=await s(d);if(g&&(g.org=w.tenant??null),!w.openRouterModels){f(501,`GET ${st} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ee(l,200,await w.openRouterModels());return}if(c.pathname.startsWith("/partners/")){f(404,`no partner adapter for ${d.method} ${c.pathname} \u2014 the partner surface currently carries ${or} and GET ${st}`,"invalid_request_error","not_found_error");return}let v=await s(d);if(g&&(g.org=v.tenant??null),d.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){l.writeHead(308,{location:st}),l.end();return}ee(l,200,await v.listModels());return}if(d.method==="GET"&&c.pathname===Is){if(!v.listImageModels){f(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ee(l,200,await v.listImageModels());return}if(As(c.pathname)){if(!v.supportsImages){f(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let w={clients:v,imageModels:v.supportsImages,stats:u,turn:_()};c.pathname===nn?await Ds(d,l,w):await Ns(d,l,w);return}if(d.method==="GET"&&c.pathname===Zs){if(!v.listSpeechToTextModels){f(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ee(l,200,await v.listSpeechToTextModels());return}if(Qs(c.pathname)){if(!v.supportsTranscription){f(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${an}`,"not_implemented","not_implemented_error");return}let w={clients:v,transcriptionModels:v.supportsTranscription,stats:u,turn:_()};await ni(d,l,w);return}if(Ws(c.pathname)){if(!v.supportsSpeech){f(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${gt}`,"not_implemented","not_implemented_error");return}let w={clients:v,speechModels:v.supportsSpeech,stats:u,turn:_()};await Xs(d,l,w);return}if(d.method!=="POST"){f(404,`no route for ${d.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let E;try{E=await yi(d)}catch(w){if(w instanceof bt){f(413,w.message,"request_too_large","request_too_large");return}f(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=Buffer.byteLength(JSON.stringify(E));if(c.pathname==="/v1/responses"){u.request("responses",b,b),await Ud(E,v,lt(v),l,u,_());return}if(c.pathname==="/v1/chat/completions"){u.request("chat_completions",b,b),await Nd(E,v,l,u,_(),d.headers[ir]);return}if(c.pathname==="/v1/systemone"){u.request("systemone",b,b),await Fd(E,v,l,u,_());return}if(c.pathname==="/v1/messages"){u.request("messages",b,b),await Vd(E,v,l,u,_());return}if(c.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",b,b),me(l,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}f(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let v=String(h instanceof Error?h.message:h);if(!l.headersSent){let b=o?.(h)??null;if(b){f(b.status,v,b.openaiType,b.anthropicType);return}if(h instanceof fn.SessionAllocationError){let w=Jt(h.code);if(w){let k=h.retryAfterSeconds??(w.status===429?30:void 0);k!==void 0&&l.setHeader("Retry-After",String(k)),f(w.status,Fn(w,h.code??void 0),w.openaiType,w.anthropicType,w.code);return}}if(h instanceof fn.SessionFailedError){let w=Wt(h);if(w){let k=w.status===429?30:void 0;k!==void 0&&l.setHeader("Retry-After",String(k)),f(w.status,Fn(w,h.status.sessionId?`session ${h.status.sessionId}`:void 0),w.openaiType,w.anthropicType,w.code);return}}if(h instanceof Ze){f(502,v,"upstream_error","api_error");return}if(h instanceof ye){h.retryable&&l.setHeader("Retry-After","1"),f(502,v,"upstream_error","api_error",h.code);return}if(h instanceof He){l.setHeader("Retry-After",String(h.retryAfterSeconds)),f(h.status,v,h.status===429?"capacity_error":"upstream_error",h.status===429?"rate_limit_error":"overloaded_error",h.code);return}f(500,v,"proxy_error","api_error","proxy_error");return}g&&(g.streamError=!0);let E=h instanceof ye?h.code:null;l.destroyed||(m?l.write(`event: error
|
|
63
63
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:v}})}
|
|
64
64
|
|
|
65
65
|
`):l.write(`data: ${JSON.stringify({error:{message:v,type:"upstream_error",code:E}})}
|
|
66
66
|
|
|
67
|
-
`)),l.end()})}}function
|
|
68
|
-
`),null):{catalogUrl:r,anonKey:o}}function
|
|
69
|
-
`),o(127)})})}function
|
|
70
|
-
`)}async function
|
|
71
|
-
`)),setInterval(()=>s.reap(),5e3).unref());let i=null,
|
|
72
|
-
`),
|
|
73
|
-
`),0):(
|
|
74
|
-
`),1)}if(n==="proxy"){let o=e??
|
|
75
|
-
`):
|
|
76
|
-
`);let l=null,c=null,
|
|
77
|
-
`)}),
|
|
78
|
-
`),l=
|
|
79
|
-
`),
|
|
80
|
-
`),
|
|
81
|
-
`),
|
|
67
|
+
`)),l.end()})}}function Si(t){let{clients:e,apiKey:n}=t,r=(0,wi.createServer)(Wd(t)),o=zo(r,{clients:e,apiKey:n,statusOf:t.statusOf}),s=er(r,{resolver:Rs(e,n)}),i=r.close.bind(r);return r.close=(a=>(o.close(),s(),i(a))),No(r,{clients:e,apiKey:n}),r}var gn=require("@urun-sh/core/internal");var Kd={ensureWebRTC:gn.ensureNodeWebRTC,webrtcUnavailableReason:gn.nodeWebRTCUnavailableReason,audioBackend:At};async function ki(t=Kd){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 Yd(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?Kt(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
|
|
68
|
+
`),null):{catalogUrl:r,anonKey:o}}function Xd(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:Yd(L.default.env,r=>L.default.stderr.write(r)),decisionPool:co(L.default.env,L.default.env.HOSTNAME)??void 0},n=mo(e);return{router:n,decision:e.decisionPool?go(e,n):null}}async function xi(t,e,n){let r=(0,cr.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{L.default.stderr.write(`failed to launch ${t}: ${String(s)}
|
|
69
|
+
`),o(127)})})}function Ri(){return as(L.default.env,O,pe.existsSync)}function Ai(t){for(let[e,n]of Object.entries(jn(t)))L.default.stdout.write(`export ${e}=${n}
|
|
70
|
+
`)}async function Ei(t,e){let n=Ye(L.default.env),r=e?Hn(n):void 0,{router:o,decision:s}=Xd(n);s&&(s.boot().then(()=>s.reap()).catch(c=>L.default.stderr.write(`[decision-pool] boot FAILED: ${String(c instanceof Error?c.message:c)}
|
|
71
|
+
`)),setInterval(()=>s.reap(),5e3).unref());let i=null,a=l=>{if(i===null){let c=u.address();if(c===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");i=Jn(c.port),(0,pe.mkdirSync)(pr.default.dirname(i),{recursive:!0})}(0,pe.appendFileSync)(i,l)},u=Si({clients:ho(o,void 0,void 0,s??void 0,po(L.default.env)),identity:r,...e?{requestLog:a}:{}});try{await new Promise((l,c)=>{u.once("error",c),u.listen(t,"127.0.0.1",l)})}catch(l){throw await o.closeAll().catch(()=>{}),s&&await s.close().catch(()=>{}),l.code==="EADDRINUSE"?new Error(ys(t,await Vn(t))):l}let d=u.address().port;return e&&(L.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${d}/v1
|
|
72
|
+
`),Ai(d)),{port:d,close:async()=>{s&&await s.drain(5e3).catch(()=>{});let l=new Promise(c=>u.close(()=>c()));u.closeAllConnections(),await l,await o.closeAll(),s&&await s.close()}}}async function Qd(){let t=L.default.argv.slice(2),e=ds(t),n=t.shift()??"proxy";if(n==="env")return Ai(ls(e??Gn(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await ki();return o?(L.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
|
|
73
|
+
`),0):(L.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
|
|
74
|
+
`),1)}if(n==="proxy"){let o=e??Gn(t),s=await Ei(o,!0);return await new Promise(i=>{L.default.once("SIGINT",i),L.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(zt).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let h=Ye(L.default.env);return xi("pi",["-e",Ri(),...ss(h.appId,t)],L.default.env)}if(r==="omp"){let h=Ye(L.default.env);return xi("omp",["-e",Ri(),...is(h.appId,t)],L.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 h=zt[r];if(!h)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(zt).join(" | ")} \u2014 or \`-- <cmd>\``);o=h.bin,s=[...h.args??[],...t],i=h.env}let a=await ps(e,Hn(Ye(L.default.env))),u=null,d=a.port;a.mode==="reuse"?L.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${d} (app ${a.identity.app}, fn ${a.identity.fn}, v${a.identity.proxy_version})
|
|
75
|
+
`):a.reason&&L.default.stderr.write(`urun compat: ${a.reason}
|
|
76
|
+
`);let l=null,c=null,m=null,f=null;a.mode!=="reuse"&&(u=await Ei(a.port,!1),d=u.port,f=Jn(d),(0,pe.mkdirSync)(pr.default.dirname(f),{recursive:!0}),m=(0,pe.createWriteStream)(f,{flags:"a"}),c=gs({streams:L.default,note:h=>(0,pe.appendFileSync)(f,h)}).uninstall,m.on("error",h=>{l?.(),l=null,le(L.default.stderr,`urun compat: proxy log ${f} failed: ${String(h)} \u2014 proxy output continues on the terminal
|
|
77
|
+
`)}),L.default.stdout.write(`urun openai proxy on http://127.0.0.1:${d}/v1 \u2014 proxy logs: ${f}
|
|
78
|
+
`),l=fs(m)),r==="codex"&&(s=os(d,Ye(L.default.env).appId,s));let p=(0,cr.spawn)(o,s,{stdio:"inherit",env:rs(L.default.env,d,i)}),y=f!==null?hs({logPath:f,appendSync:pe.appendFileSync,restore:()=>{l?.(),l=null},writeStderr:h=>L.default.stderr.write(h),killChild:()=>p.kill("SIGTERM"),exit:h=>L.default.exit(h),proc:L.default}):null,g=await new Promise(h=>{p.once("exit",v=>h(v??1)),p.once("error",v=>{l?.(),l=null,le(L.default.stderr,`failed to launch ${o}: ${String(v)}
|
|
79
|
+
`),h(127)})});y?.();let _=null;try{u&&await u.close()}catch(h){_=h}finally{l?.(),l=null,c?.(),c=null,m?.end()}return _!==null&&le(L.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${g} preserved): ${String(_ instanceof Error?_.message:_)}
|
|
80
|
+
`),g}}Qd().then(t=>L.default.exit(t),t=>{L.default.stderr.write(`${String(t instanceof Error?t.message:t)}
|
|
81
|
+
`),L.default.exit(1)});
|