@urun-sh/openai 0.6.0 → 0.6.2
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-YXK42SKC.js → chunk-76BZLCGT.js} +1 -1
- package/dist/chunk-7V2JKPIG.js +1 -0
- package/dist/chunk-CT2GQG5R.js +7 -0
- package/dist/chunk-TMQJY56F.js +4 -0
- package/dist/chunk-URMOBMSP.js +58 -0
- package/dist/chunk-X3GLH2HQ.js +1 -0
- package/dist/gemini-live.cjs +1 -1
- package/dist/gemini-live.d.cts +11 -0
- package/dist/gemini-live.d.ts +3 -0
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +36 -36
- 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/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +6 -6
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +52 -52
- package/dist/proxy/cli.cjs +46 -46
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +26 -26
- package/dist/proxy/index.d.cts +94 -15
- package/dist/proxy/index.d.ts +7 -3
- package/dist/proxy/index.js +1 -1
- package/dist/{responses-turn-CdhIre_a.d.ts → responses-turn-EwxfRJJg.d.ts} +15 -1
- package/dist/{responses-turn-BfdBbey8.d.cts → responses-turn-vMefRdgJ.d.cts} +112 -15
- package/package.json +2 -2
- package/dist/chunk-45FJ5GTP.js +0 -7
- package/dist/chunk-QTVTCMJU.js +0 -1
- package/dist/chunk-TDRZZGUK.js +0 -1
- package/dist/chunk-TPH77ZOW.js +0 -58
- package/dist/chunk-WCMX5VOF.js +0 -4
package/dist/proxy/cli.cjs
CHANGED
|
@@ -1,76 +1,76 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ls=Object.create;var Hn=Object.defineProperty;var Us=Object.getOwnPropertyDescriptor;var Ms=Object.getOwnPropertyNames;var Ns=Object.getPrototypeOf,Ds=Object.prototype.hasOwnProperty;var Fs=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ms(e))!Ds.call(t,o)&&o!==n&&Hn(t,o,{get:()=>e[o],enumerable:!(r=Us(e,o))||r.enumerable});return t};var ve=(t,e,n)=>(n=t!=null?Ls(Ns(t)):{},Fs(e||!t||!t.__esModule?Hn(n,"default",{value:t,enumerable:!0}):n,t));var Bs=()=>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,T=Bs();var qn=require("child_process"),re=require("fs"),jn=ve(require("path"),1),U=ve(require("process"),1);var Ve=require("@urun-sh/core");function Vn(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 Jn(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),r}function Wn(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 qs="llm-resp";async function*zt(t,e){let n=`${qs}:${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 Wn(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var ct=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=Jn(e,n,this.consumerId);return this.write(r),zt(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Vn(e,n,r,this.consumerId);return this.write(o),zt(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 Kn=0;function js(){return Kn+=1,`req_${Date.now().toString(36)}_${Kn.toString(36)}`}var pt=class{transport;constructor(e){this.transport=new ct(e)}responses={create:async e=>{let n=js(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var Xn="audio",Yt=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 Qn(t,e,n=1e4){let r=new Yt(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(Xn).attach(o);let s=await Gs(t,n);return await r.startInbound(s),r}function Gs(t,e){let n=t.stream(Xn);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 zn="rt-video-in",Yn=256e3;function Zn(t){let e=t.stream(zn),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${zn}') 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>Yn)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${Yn}-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 Hs=24e3,Fe=480,Vs=111;async function Js(){let t=await import("opusscript"),e=t.default??t;return new e(Hs,1,2048)}async function ft(){let t=await import("werift"),e=await Js();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>=Fe;){let c=u.subarray(d,d+Fe);d+=Fe;let l=Buffer.from(c.buffer,c.byteOffset,c.byteLength),f=e.encode(l,Fe);o=o+1&65535,s=s+Fe>>>0;let p=new t.RtpHeader({version:2,payloadType:Vs,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(p,f);n.writeRtp(h)}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 er(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 mt=require("@urun-sh/core"),Xt="rt-video-out";var Ws="h264";function Ks(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 zs(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;Ks(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 tr="urun.videoOut.v2-ws";function nr(t){let e=t.stream(Xt);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Xt}') 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: "${Xt}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=zs(u)}catch(c){s(c instanceof Error?c:new Error(String(c)));continue}for(let c of n)c(d)}for(let u of o)u()};return{codec:Ws,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 rr=require("@urun-sh/core"),Qt=2;function Ys(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Xs(t){let e=t?.type;return e==="response.completed"||e==="error"}function or(t){return async function(n,r){return(async function*(){for(let s=1;s<=Qt;s++){let{app:i,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let d=!1,c=!1;try{let l=await t.createStream(a,n);for await(let f of l){if(Xs(f)&&(d=!0),Ys(f)){if(s>1)continue}else c=!0;yield f}}catch(l){if(l instanceof rr.SessionFailedError&&(l.kind==="never-live"||l.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,l)}catch{}throw l}if(s<Qt&&!c){await t.evict(i,a);continue}throw l}if(d)return;if(s<Qt&&!c){await t.evict(i,a);continue}return}})()}}var Z=class extends Error{name="ModelPriceError"},Zt="per_million_input_tokens",en="per_million_output_tokens",ir="model_id,variant,unit,price_usd,effective_at,expires_at",sr={per_request:!0,per_minute:!0,per_output_unit:!0},Qs=5e3;function Zs(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Z(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function ar(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Z(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function ei(t,e,n){return t===null?null:ar(t,e,n)}function ti(t,e){if(t===Zt)return"input";if(t===en)return"output";if(typeof t=="string"&&Object.hasOwn(sr,t))return null;throw new Z(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Zt} | ${en}) nor a known GPU-time unit (${Object.keys(sr).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 ni(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 tn(t,e){return`${t}\0${e}`}function ri(t){if(!Array.isArray(t))throw new Z(`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 Z(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of ir.split(","))if(!Object.hasOwn(s,d))throw new Z(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=ti(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Z(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new Z(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:Zs(s.price_usd,o),effective_at:ar(s.effective_at,o,"effective_at"),expires_at:ei(s.expires_at,o,"expires_at")})}return e}function ur(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 c=u.variant??"",l=d.get(c);l||(l={input:[],output:[]},d.set(c,l),o.get(u.model_id).set(c,u.variant)),l[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,d]of r){let c=d.get(""),l=(f,p,h)=>{let k=f&&f.length>0?f:c?.[p];if(!k||k.length===0)return null;let m=ni(k,p);return"reason"in m?m:m.rate.usd===0?p==="output"&&h!==null&&n?.has(tn(u,h))?m.rate:{reason:`the ${p} 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[f,p]of o.get(u)){let h=d.get(f),k=l(h?.input,"input",p),m=l(h?.output,"output",p);if(k!==null&&"reason"in k){i.push({model_id:u,variant:p,reason:k.reason});continue}if(m!==null&&"reason"in m){i.push({model_id:u,variant:p,reason:m.reason});continue}k===null||m===null||s.push({model_id:u,variant:p,pricing:{input:k.usd,output:m.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 Be(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 gt={prices:[],refusals:[]};async function dr(t){let e=t.fetchImpl??fetch,n=`${Zt},${en}`,r=await e(`${t.catalogUrl}/model_prices?select=${ir}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Qs)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return ri(await r.json())}var G=class extends Error{},oi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function si(t){if(typeof t!="string")return!1;let e=oi.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 ii(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new G(`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 G(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new G(`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 G(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let d=a;for(let l of["model_id","variant","app_slug","function"])if(typeof d[l]!="string"||d[l].length===0)throw new G(`catalog shared endpoints[${u}] (${JSON.stringify(d)}) has no valid "${l}"`);let c=(l,f)=>{if(d[l]!==void 0&&d[l]!==null&&!f)throw new G(`catalog shared endpoints[${u}] (${d.model_id}:${d.variant}) carries a malformed "${l}": ${JSON.stringify(d[l])}`)};c("ready",typeof d.ready=="boolean"),c("ready_runtimes",typeof d.ready_runtimes=="number"&&Number.isInteger(d.ready_runtimes)&&d.ready_runtimes>=0),c("ready_since",si(d.ready_since));for(let l of["model_id","variant"]){let f=d[l];if(f.includes(":"))throw new G(`catalog shared endpoints[${u}] has "${l}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return c("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 G(`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 G(`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 G(`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 qe(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function lr(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(c=>c.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 G(`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 cr(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 G(`catalog read failed: GET ${n} \u2192 ${r.status}`);return ii(await r.json())}function le(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var ai={chat:!0,code:!0,agent:!0,vl:!0},pr={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function ui(t){let e=t.toLowerCase();return Object.hasOwn(pr,e)?pr[e]:null}var fr={"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 di(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(fr,o)?fr[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 mr={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 li(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(mr,s))return mr[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 ci=["context_length","max_model_len"];function pi(t){let e=ci.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 yt(t){let e=t.map(pi),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function fi(t,e){let n=e.filter(o=>le(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return ht(n);let r=e.filter(o=>le(o.model_id)===t);return r.length>0?ht(r):null}function ht(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:mi(t),matches:t}:null}function mi(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){let e=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(e)?Math.floor(e/1e3):0}function nn(t,e,n){let r=fi(t,e);if(!r)return{id:t,object:"model",created:0,owned_by:"urun"};let{row:o,matches:s}=r,i=yt(s),a=Be(o.model_id,o.variant,n),u=_r(o,s);return{id:t,object:"model",created:wr(o),owned_by:"urun",name:`${o.model_id}:${o.variant}`,...o.description?{description:o.description}:{},...o.task?{task:o.task}:{},...o.engine?{engine:o.engine}:{},...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{}}}var gi=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function _r(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:[...gi],defect:o}:{published:[],defect:o}}function rn(t){let e=t.length>0?ht(t):null;return e===null?{published:[],defect:null}:_r(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 yr(t){return{input:[{type:"prompt",unit:"token",cost_usd:hr(t.input)}],output:[{type:"completion",unit:"token",cost_usd:hr(t.output)}]}}function hi(t,e,n,r){if(e.length===0)return null;let o=ht(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||ai[s.task]!==!0)return null;let a=yt(i),u=Be(s.model_id,s.variant,n),d=li(s.hf_repo),c={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return a!==null&&(c.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:ui(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:yr(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:c,...u?{pricing:yr(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function vr(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?qe(t):[];if(s.length>0){let d=s.filter(c=>c.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 c=d.map(l=>`${l.model_id}:${l.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${c} carry no ready field and are declared not ready`)}}let i={datacenters:di(t?.regions,o),compliance:t?.compliance??null},a=[],u=new Set;for(let d of s){let c=`${d.model_id}:${d.variant}`;if(u.has(c))continue;u.add(c);let l=hi(d,e.filter(f=>f.model_id===d.model_id&&f.variant===d.variant),n,i);l&&a.push(l)}return{data:a}}var Er="https://api.urun.sh/v1",M=class extends Error{},K=class extends Error{},on="urs1.";function br(t,e){return on+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function yi(t){if(!t.startsWith(on))return null;try{let e=JSON.parse(Buffer.from(t.slice(on.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 Ar(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 kr(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=_i(t);return e===null?[]:[e]}function Sr(t,e,n,r,o){if(!o)throw new G(`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 G(`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 G(`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 G(`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 Or="shared:",vt="speech:";function Ge(t){return t.sharedApp?Or+t.appSlug:t.appSlug}function He(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 je(t,e){let n=e.filter(s=>le(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>le(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function wi(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function _i(t){let e=t.map(wi),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Rr={stt:"stt",tts:"tts"};function wt(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Rr[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Rr[e]:null}var _t=6e4,bt=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??_t;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??_t;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??_t;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??_t;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 Z)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 u=(n?qe(n):[]).map(d=>{let c={id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",name:`${d.model_id}:${d.variant}`};d.gpu_spec&&(c.gpu_spec=d.gpu_spec),typeof d.warm=="number"&&(c.warm=d.warm);let l=s.filter(k=>k.model_id===d.model_id&&k.variant===d.variant),f=yt(l);f!==null&&(c.context_length=f);let p=Be(d.model_id,d.variant,i);p!==null&&(c.pricing=p);let h=rn(l);return h.published.length>0&&(c.voices=[...h.published]),c});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(d=>nn(d,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return vr(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=Sr(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return xr(`${r.modelId}:${r.variant}`,s).includes(n)}return kr(je(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?wt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:wt(je(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?wt(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":wt(je(n.appSlug,r))==="tts"}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):je(n.appSlug,r);return rn(o)}async imageModelList(){let e=await this.catalogRows(),n=gt,r=[];for(let s of await this.availableIds()){let i=kr(je(s,e));i.length!==0&&r.push({...nn(s,e,n),image_modes:i})}let o=await this.sharedBlock();if(o)for(let s of qe(o)){let i=Sr(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=xr(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`,image_modes:a};s.gpu_spec&&(u.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(u.warm=s.warm),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 vi=3,bi="llm",ki=new Set(["paused","error"]);function Ir(t,e){let n=t.doc(bi),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=c=>{if(!s){s=c;for(let l of[...a])l(c);a.clear()}};return r&&u.push(n.onConnectionState(c=>{i&&(c.consecutiveFailures<vi||d(new K(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(c=>{if(c.name==="live"){i=!0;return}i&&ki.has(c.name)&&d(new K(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(c){return s?(c(s),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of u.splice(0))c()}}}async function*sn(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)}}function Tr(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 Si(t,e,n){let{baseUrl:r,orgId:o,auth:s}=t,i=typeof t.subject=="function"?t.subject():t.subject,a=n.startsWith(vt)&&i!==void 0?`${i}:speech`:i,u=e.fnName??t.fnName,d=t.sessionStartOptions?.(n),c=e.sharedApp?{sharedApp:!0,...d}:d,l=k=>({session:k,responses:new pt(k),gone:Ir(k,n)});if(s.lane==="jwt"){let k=(0,Ve.App)(e.appSlug,{baseUrl:r,orgId:o,jwt:s.jwt});return l(Tr(k,e.appSlug,u,c))}let{apiKey:f,gatewayUrl:p}=s,h=(0,Ve.App)(e.appSlug,{baseUrl:r,orgId:o,getAccessToken:async()=>(await(0,Ve.createClientToken)(f,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],...a===void 0?{}:{subject:a},...e.sharedApp?{sharedApp:!0}:{}})).token});return l(Tr(h,e.appSlug,u,c))}function xi(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 Ri(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 Ei=new Set(["error","paused"]);function $r(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=Si(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 bt({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"?()=>Ar({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>er(n):null,listPrices:n?()=>dr(n):null,shared:e.lane==="api-key"?()=>cr({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:xi});return r=s,t.defaultApp!==null&&t.statelessDirect!==!0&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ge({appSlug:t.defaultApp}))),s}async function an(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,e===void 0?void 0:{signal:e})}async function Pr(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 Cr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Lr(t,e=ft,n,r){let o=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,u=l=>{let f=l.session.id;return typeof f=="string"&&f.length>0?f:null},d=(l,f)=>{let p=o.get(l);return p||(p=(async()=>{await an(l.session,f);let h=await Qn(l.session,await e());return Object.assign(h,{sessionId:l.session.id})})(),o.set(l,p),p.catch(()=>o.delete(l))),p},c=l=>{let f=a.get(l);return f||(f=(async()=>{let p=await d(l);return{appendInputAudio:h=>p.appendInputAudio(h),onOutputAudio:h=>p.onOutputAudio(h),sessionId:u(l)}})(),a.set(l,f),f.catch(()=>a.delete(l))),f};return{createResponse:or({sessionFor:l=>t.sessionFor(l),sessionIdOf:l=>u(l),evict:(l,f)=>t.evict(l,f),onAdmissionVerdict:(l,f,p)=>{Ri(p)&&(t.evict(l,f),n?.(l,p.kind==="never-live"?"never-live":"create-failed"))},createStream:async(l,f)=>(await an(l.session),sn(await l.responses.responses.create(f),l.gone))}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(l,f)=>t.supportsImages(l,f),listImageModels:()=>t.imageModelList(),catalogIdentity:l=>t.catalogIdentityFor(l),servingAppSlug:async l=>await t.servingAppSlugFor(l),supportsAudio:l=>t.supportsAudio(l),supportsSpeech:l=>t.supportsSpeech(l),speechVoices:l=>t.speechVoices(l),openAudio:async(l,f)=>{let{entry:p}=await t.sessionFor(l);if(f?.aborted)throw await Pr(p.session),Cr(f);let h=d(p,f);return f===void 0?h:new Promise((k,m)=>{let _=()=>{Pr(p.session).catch(()=>{}),m(Cr(f))};f.addEventListener("abort",_,{once:!0});let g=()=>f.removeEventListener("abort",_);h.then(y=>{g(),k(y)},y=>{g(),m(y)})})},openAudioOn:async l=>c((await t.sessionForHandle(l)).entry),openVideo:async l=>{let{entry:f}=await t.sessionFor(l),p=s.get(f);return p||(p=Zn(f.session),s.set(f,p)),p},openVideoOut:async l=>{let{entry:f}=await t.sessionFor(l),p=i.get(f);return p||(p=nr(f.session),i.set(f,p)),p},sessionHandle:async l=>(await t.handleFor(l)).handle,speechSessionHandle:async l=>(await t.speechHandleFor(l)).handle,evictSpeechSession:async l=>{let{app:f,entry:p}=await t.sessionForHandle(l);await t.evict(f,p)},createResponseOn:async(l,f)=>{let{entry:p}=await t.sessionForHandle(l);return await an(p.session),sn(await p.responses.responses.create(f),p.gone)},onSessionEnd:async(l,f)=>{let{entry:p}=await t.sessionForHandle(l),h=p.session;if(typeof h.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let k=!1;return h.onPhase(m=>{if(k||!Ei.has(m.name))return;k=!0;let _=h.endsAt??null;f({timeLeftMs:_?Math.max(0,_.getTime()-Date.now()):null,reason:m.reason??`session ${m.name}`})})},...r?{stateless:r}:{}}}var xs=require("http");var Zr=require("crypto"),eo=require("ws");var Mr="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Ai=1007,Nr=1008,ce=1011,Rt=1008,b=class extends Error{constructor(n,r=Ai){super(n);this.closeCode=r}closeCode},F=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,kt=["setup","clientContent","realtimeInput","toolResponse"];function Dr(t){let e;try{e=JSON.parse(t)}catch{throw new b("client message is not valid JSON")}let n=F(e);if(!n)throw new b("client message must be a JSON object");let r=kt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!kt.includes(a));if(o.length>0)throw new b(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${kt.join(", ")}`);if(r.length!==1)throw new b(`client message must contain exactly one of ${kt.join(", ")} (got ${r.length})`);let s=r[0],i=F(n[s]);if(!i)throw new b(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Fr(t,e){if(typeof t=="string")return t;let n=F(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new b(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=F(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new b(`${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 b(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new b(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
6
|
-
`)}var Oi={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},be="urun.videoOut";function Br(t){return{framing:tr,codec:t}}function qr(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[be]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Ii={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ti=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",be],Ur=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Pi(t){let e=F(t);if(!e)throw new b("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new b(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=F(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new b("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new b(`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 b("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(!Ur.includes(e.activityHandling))throw new b(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Ur.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Ci=["temperature","maxOutputTokens","responseModalities"];function jr(t){for(let[l,f]of Object.entries(Ii))if(t[l]!==void 0)throw new b(f);for(let l of Object.keys(t))if(!Ti.includes(l))throw new b(`unsupported setup field "${l}"`);if(typeof t.model!="string"||t.model.length===0)throw new b('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=F(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new b("setup.generationConfig must be an object");if(s){for(let l of Object.keys(s))if(!Ci.includes(l))throw new b(`unsupported generationConfig field "${l}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new b("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new b("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let l=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let f of l){let p=String(f).toUpperCase();if(p==="AUDIO"){o=!0;continue}if(p!=="TEXT")throw new b(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Fr(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new b("setup.tools must be an array");a=[];for(let l of t.tools){let f=F(l);if(!f)throw new b("setup.tools entries must be objects");for(let p of Object.keys(f))if(p!=="functionDeclarations")throw new b(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new b("tool.functionDeclarations must be an array");for(let p of f.functionDeclarations){let h=F(p);if(!h||typeof h.name!="string")throw new b("functionDeclarations entries require a string name");a.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let l=F(t.sessionResumption);if(!l)throw new b("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(l))if(f!=="handle")throw new b(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(l.handle!==void 0&&(typeof l.handle!="string"||l.handle.length===0))throw new b("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof l.handle=="string"?l.handle:null}}let d=t.realtimeInputConfig===void 0?Oi:Pi(t.realtimeInputConfig),c=!1;if(t[be]!==void 0){if(!F(t[be]))throw new b(`setup["${be}"] must be an object (the v1 opt-in is {})`);c=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:u,videoOut:c}}function Gr(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Hr(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Vr(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new b(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new b("clientContent.turns must be an array");let n=[];for(let r of e){let o=F(r);if(!o)throw new b("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 b(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Fr(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var St=16e3,Jr=24e3,$i=`audio/pcm;rate=${Jr}`,Wr=Buffer.alloc(960).toString("base64");function Li(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 c=u-d;o[a]=Math.round(t[d]+(t[d+1]-t[d])*c)}return o}function Ui(t){let e=F(t);if(!e)throw new b("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new b(`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 b("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 b("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Mi(t){let e=F(t);if(!e)throw new b("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new b(`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])!==St)throw new b(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${St} Hz (audio/pcm;rate=${St})`);if(typeof e.data!="string"||e.data.length===0)throw new b("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 b(`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=Li(o,St,Jr);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Kr(t){if(t.mediaChunks!==void 0)throw new b('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 b("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=F(t[o]);if(!s||Object.keys(s).length!==0)throw new b(`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 b(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new b(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Mi(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Ui(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new b("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new b("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function zr(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new b(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new b("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=F(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new b("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 Yr(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Xr(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:$i,data:t}}]}}}}function Qr(t){let e=F(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 c=F(d);if(!(c?.type!=="message"||!Array.isArray(c.content)))for(let l of c.content){let f=F(l);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let c=F(d);if(c?.type!=="function_call")continue;if(typeof c.call_id!="string"||typeof c.name!="string")throw new b(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,ce);let l=typeof c.arguments=="string"&&c.arguments.length>0?c.arguments:"{}",f;try{f=JSON.parse(l)}catch{throw new b(`upstream function_call arguments are not valid JSON: ${l}`,ce)}r.push({id:c.call_id,name:c.name,args:f}),o.push({type:"function_call",call_id:c.call_id,name:c.name,arguments:l})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=F(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 Ni=256,un=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Ni;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Di="local",Je=t=>t.slice(0,120),dn=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 M){this.ws.close(Nr,Je(e.message));return}if(e instanceof K){this.ws.close(Rt,Je(e.message));return}if(e instanceof b){this.ws.close(e.closeCode,Je(e.message));return}this.ws.close(ce,Je(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Dr(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 b(`"${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}=Vr(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Kr(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:Wr);return}this.transcript.push(...zr(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new b("setup may only be sent once, as the first client message");let n=jr(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new b("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",Rt);if(s.model!==n.model)throw new b(`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 b("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 b(`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`,Rt);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(qr(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[be]=Br(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 b("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new b("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",ce);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Xr(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 b("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new b("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",ce);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 b(`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 b("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 b("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,Zr.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Gr(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(Hr(e.timeLeftMs)),this.ws.close(ce,Je(`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 b(`upstream error: ${JSON.stringify(d)}`,ce);if(d.type==="response.completed"){o=d.response,s=!0;continue}let c=Yr(d);c&&this.send(c)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new b("upstream produced no response.completed event",ce);let{messages:i,assistantItems:a}=Qr(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},ke=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Fi(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 ke(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new ke(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new ke(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function to(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 eo.WebSocketServer({noServer:!0}),o=new un;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===Mr&&(a.on("error",()=>{}),(async()=>{let c=Fi(i,d,n),l;if(e.authenticate)l=await e.authenticate(c,i);else{if(e.apiKey!==void 0&&c!==e.apiKey)throw new ke(401,"invalid local proxy api key");l={clients:e.clients,scope:Di}}r.handleUpgrade(i,a,u,f=>{new dn(f,l,o)})})().catch(c=>{let l=502;(c instanceof ke||typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number")&&(l=c.status);let f=l===401?"Unauthorized":l===403?"Forbidden":l===502?"Bad Gateway":"Internal Server Error",p=c instanceof Error?c.message:String(c);a.destroyed||(a.write(`HTTP/1.1 ${l} ${f}\r
|
|
2
|
+
"use strict";var Ys=Object.create;var nr=Object.defineProperty;var Xs=Object.getOwnPropertyDescriptor;var Qs=Object.getOwnPropertyNames;var Zs=Object.getPrototypeOf,ei=Object.prototype.hasOwnProperty;var ti=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qs(e))!ei.call(t,o)&&o!==n&&nr(t,o,{get:()=>e[o],enumerable:!(r=Xs(e,o))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?Ys(Zs(t)):{},ti(e||!t||!t.__esModule?nr(n,"default",{value:t,enumerable:!0}):n,t));var ni=()=>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,I=ni();var Qn=require("child_process"),ae=require("fs"),Zn=xe(require("path"),1),M=xe(require("process"),1);var Ye=require("@urun-sh/core");function rr(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 or(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 sr(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 ri="llm-resp";async function*rn(t,e){let n=`${ri}:${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 sr(i);return}}}finally{try{t.doc("llm").set({requests:{[e]:null}})}catch{}}}var yt=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=or(e,n,this.consumerId);return this.write(r),rn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=rr(e,n,r,this.consumerId);return this.write(o),rn(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 ir=0;function oi(){return ir+=1,`req_${Date.now().toString(36)}_${ir.toString(36)}`}var wt=class{transport;constructor(e){this.transport=new yt(e)}responses={create:async e=>{let n=oi(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var dr="audio",on=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 lr(t,e,n=1e4){let r=new on(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(dr).attach(o);let s=await si(t,n);return await r.startInbound(s),r}function si(t,e){let n=t.stream(dr);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 ar="rt-video-in",ur=256e3;function cr(t){let e=t.stream(ar),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${ar}') 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>ur)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${ur}-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 ii=24e3,Ve=480,ai=111;async function ui(){let t=await import("opusscript"),e=t.default??t;return new e(ii,1,2048)}async function _t(){let t=await import("werift"),e=await ui();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>=Ve;){let l=u.subarray(d,d+Ve);d+=Ve;let p=Buffer.from(l.buffer,l.byteOffset,l.byteLength),m=e.encode(p,Ve);o=o+1&65535,s=s+Ve>>>0;let c=new t.RtpHeader({version:2,payloadType:ai,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),f=new t.RtpPacket(c,m);n.writeRtp(f)}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 pr(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 vt=require("@urun-sh/core"),sn="rt-video-out";var di="h264";function li(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 ci(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;li(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 fr="urun.videoOut.v2-ws";function mr(t){let e=t.stream(sn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${sn}') 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: "${sn}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=ci(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:di,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 gr=require("@urun-sh/core"),an=2;function pi(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function fi(t){let e=t?.type;return e==="response.completed"||e==="error"}function hr(t){return async function(n,r){return(async function*(){for(let s=1;s<=an;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 p=await t.createStream(a,n);for await(let m of p){if(fi(m)&&(d=!0),pi(m)){if(s>1)continue}else l=!0;yield m}}catch(p){if(p instanceof gr.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(i,a,p)}catch{}throw p}if(s<an&&!l){await t.evict(i,a);continue}throw p}if(d)return;if(s<an&&!l){await t.evict(i,a);continue}return}})()}}var re=class extends Error{name="ModelPriceError"},un="per_million_input_tokens",dn="per_million_output_tokens",wr="model_id,variant,unit,price_usd,effective_at,expires_at",yr={per_request:!0,per_minute:!0,per_output_unit:!0},mi=5e3;function gi(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new re(`${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 re(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function hi(t,e,n){return t===null?null:_r(t,e,n)}function yi(t,e){if(t===un)return"input";if(t===dn)return"output";if(typeof t=="string"&&Object.hasOwn(yr,t))return null;throw new re(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${un} | ${dn}) nor a known GPU-time unit (${Object.keys(yr).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 wi(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 ln(t,e){return`${t}\0${e}`}function _i(t){if(!Array.isArray(t))throw new re(`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 re(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of wr.split(","))if(!Object.hasOwn(s,d))throw new re(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=yi(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new re(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new re(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:gi(s.price_usd,o),effective_at:_r(s.effective_at,o,"effective_at"),expires_at:hi(s.expires_at,o,"expires_at")})}return e}function vr(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??"",p=d.get(l);p||(p={input:[],output:[]},d.set(l,p),o.get(u.model_id).set(l,u.variant)),p[u.side].push({effective_at:u.effective_at,usd:u.usd})}let s=[],i=[];for(let[u,d]of r){let l=d.get(""),p=(m,c,f)=>{let g=m&&m.length>0?m:l?.[c];if(!g||g.length===0)return null;let _=wi(g,c);return"reason"in _?_:_.rate.usd===0?c==="output"&&f!==null&&n?.has(ln(u,f))?_.rate:{reason:`the ${c} 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`}:_.rate};for(let[m,c]of o.get(u)){let f=d.get(m),g=p(f?.input,"input",c),_=p(f?.output,"output",c);if(g!==null&&"reason"in g){i.push({model_id:u,variant:c,reason:g.reason});continue}if(_!==null&&"reason"in _){i.push({model_id:u,variant:c,reason:_.reason});continue}g===null||_===null||s.push({model_id:u,variant:c,pricing:{input:g.usd,output:_.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 We(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 Je={prices:[],refusals:[]};async function br(t){let e=t.fetchImpl??fetch,n=`${un},${dn}`,r=await e(`${t.catalogUrl}/model_prices?select=${wr}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(mi)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return _i(await r.json())}var V=class extends Error{},vi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function bi(t){if(typeof t!="string")return!1;let e=vi.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 ki(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new V(`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 V(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new V(`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 V(`catalog shared endpoints[${u}] is not an object: ${JSON.stringify(a)}`);let d=a;for(let p of["model_id","variant","app_slug","function"])if(typeof d[p]!="string"||d[p].length===0)throw new V(`catalog shared endpoints[${u}] (${JSON.stringify(d)}) has no valid "${p}"`);let l=(p,m)=>{if(d[p]!==void 0&&d[p]!==null&&!m)throw new V(`catalog shared endpoints[${u}] (${d.model_id}:${d.variant}) carries a malformed "${p}": ${JSON.stringify(d[p])}`)};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",bi(d.ready_since));for(let p of["model_id","variant"]){let m=d[p];if(m.includes(":"))throw new V(`catalog shared endpoints[${u}] has "${p}" 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 V(`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 V(`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 V(`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 Le(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function kr(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 V(`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 Sr(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 V(`catalog read failed: GET ${n} \u2192 ${r.status}`);return ki(await r.json())}function ge(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Si={chat:!0,code:!0,agent:!0,vl:!0},xr={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function xi(t){let e=t.toLowerCase();return Object.hasOwn(xr,e)?xr[e]:null}var Rr={"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 Ri(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Rr,o)?Rr[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 Er={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ar={2:"Llama2",3:"Llama3"};function Ei(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(Er,s))return Er[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ar,i))return Ar[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Ai=["context_length","max_model_len"];function Oi(t){let e=Ai.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 kt(t){let e=t.map(Oi),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Ii(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function cn(t){if(t.length===0)return null;let e=t.map(Ii),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Ti(t,e){let n=e.filter(o=>ge(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return bt(n);let r=e.filter(o=>ge(o.model_id)===t);return r.length>0?bt(r):null}function bt(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Pi(t),matches:t}:null}function Pi(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 Tr(t){let e=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(e)?Math.floor(e/1e3):0}function St(t,e,n){let r=Ti(t,e);if(!r)return{id:t,object:"model",created:0,owned_by:"urun"};let{row:o,matches:s}=r,i=kt(s),a=We(o.model_id,o.variant,n),u=Pr(o,s),d=cn(s);return{id:t,object:"model",created:Tr(o),owned_by:"urun",name:`${o.model_id}:${o.variant}`,...o.description?{description:o.description}:{},...o.task?{task:o.task}:{},...o.engine?{engine:o.engine}:{},...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}}}var Ci=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Pr(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:[...Ci],defect:o}:{published:[],defect:o}}function pn(t){let e=t.length>0?bt(t):null;return e===null?{published:[],defect:null}:Pr(e.row,e.matches)}function Or(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 Ir(t){return{input:[{type:"prompt",unit:"token",cost_usd:Or(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Or(t.output)}]}}function $i(t,e,n,r){if(e.length===0)return null;let o=bt(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Si[s.task]!==!0)return null;let a=kt(i),u=We(s.model_id,s.variant,n),d=Ei(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:Tr(s),quantization:xi(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:Ir(u).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:l,...u?{pricing:Ir(u).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Cr(t,e,n,r){let o=r??(d=>console.warn(d.trimEnd())),s=t?Le(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(p=>`${p.model_id}:${p.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:Ri(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 p=$i(d,e.filter(m=>m.model_id===d.model_id&&m.variant===d.variant),n,i);p&&a.push(p)}return{data:a}}var Nr="https://api.urun.sh/v1",U=class extends Error{},Y=class extends Error{},mn="urs1.";function $r(t,e){return mn+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Li(t){if(!t.startsWith(mn))return null;try{let e=JSON.parse(Buffer.from(t.slice(mn.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 Dr(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 Lr(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Ui(t);return e===null?[]:[e]}function fn(t,e,n,r,o){if(!o)throw new V(`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 V(`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 V(`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 Mr(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 V(`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 Br="shared:",Rt="speech:";function Ke(t){return t.sharedApp?Br+t.appSlug:t.appSlug}function ze(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 Re(t,e){let n=e.filter(s=>ge(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>ge(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Mi(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Ui(t){let e=t.map(Mi),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Ur={stt:"stt",tts:"tts"};function ve(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||Ur[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?Ur[e]:null}var xt=6e4,Et=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??xt;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??xt;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??xt;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??xt;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof re)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
|
+
`),Je}let r=vr(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(ln(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(Br)||o.startsWith(Rt)||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 U(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=ge(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 U(`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 U(`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=kr(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===ge(a.model_id)||o===ge(`${a.model_id}-${a.variant}`));if(i)throw new U(`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=ze(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 targetFor(e){return this.resolveTarget(e)}async resolveApp(e){return Ke(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ke(n))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Rt+Ke(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:ze(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:$r(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:$r(n,this.keyOf(r))}}async sessionForHandle(e){let n=Li(e);if(!n)throw new Y(`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 Y(`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 Y(`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:Je;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?Le(n):[]).map(d=>{let l={id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",name:`${d.model_id}:${d.variant}`};d.gpu_spec&&(l.gpu_spec=d.gpu_spec),typeof d.warm=="number"&&(l.warm=d.warm);let p=s.filter(_=>_.model_id===d.model_id&&_.variant===d.variant),m=kt(p);m!==null&&(l.context_length=m);let c=cn(p);c!==null&&(l.capabilities={reasoning:c});let f=We(d.model_id,d.variant,i);f!==null&&(l.pricing=f);let g=pn(p);return g.published.length>0&&(l.voices=[...g.published]),l});return{object:"list",data:this.opts.sharedOnlyListing?u:[...e.map(d=>St(d,s,i)),...u]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Cr(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=fn(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Mr(`${r.modelId}:${r.variant}`,s).includes(n)}return Lr(Re(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ve(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:ve(Re(n.appSlug,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ve(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":ve(Re(n.appSlug,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?ve(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":ve(Re(n.appSlug,r))==="stt"}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):Re(n.appSlug,r);return pn(o)}async imageModelList(){let e=await this.catalogRows(),n=Je,r=[];for(let s of await this.availableIds()){let i=Lr(Re(s,e));i.length!==0&&r.push({...St(s,e,n),image_modes:i})}let o=await this.sharedBlock();if(o)for(let s of Le(o)){let i=fn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Mr(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`,image_modes:a};s.gpu_spec&&(u.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(u.warm=s.warm),r.push(u)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Je,r=[];for(let s of await this.availableIds())ve(Re(s,e))==="stt"&&r.push(St(s,e,n));let o=await this.sharedBlock();if(o)for(let s of Le(o)){let i=fn(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(ve(i)!=="stt")continue;let a={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`};s.gpu_spec&&(a.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(a.warm=s.warm),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 Ni=3,Di="llm",Bi=new Set(["paused","error"]);function Fr(t,e){let n=t.doc(Di),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 p of[...a])p(l);a.clear()}};return r&&u.push(n.onConnectionState(l=>{i&&(l.consecutiveFailures<Ni||d(new Y(`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&&Bi.has(l.name)&&d(new Y(`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*gn(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)}}function jr(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 Fi(t,e,n){let{baseUrl:r,orgId:o,auth:s}=t,i=typeof t.subject=="function"?t.subject():t.subject,a=n.startsWith(Rt)&&i!==void 0?`${i}:speech`:i,u=e.fnName??t.fnName,d=t.sessionStartOptions?.(n),l=e.sharedApp?{sharedApp:!0,...d}:d,p=g=>({session:g,responses:new wt(g),gone:Fr(g,n)});if(s.lane==="jwt"){let g=(0,Ye.App)(e.appSlug,{baseUrl:r,orgId:o,jwt:s.jwt});return p(jr(g,e.appSlug,u,l))}let{apiKey:m,gatewayUrl:c}=s,f=(0,Ye.App)(e.appSlug,{baseUrl:r,orgId:o,getAccessToken:async()=>(await(0,Ye.createClientToken)(m,{baseUrl:c,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],...a===void 0?{}:{subject:a},...e.sharedApp?{sharedApp:!0}:{}})).token});return p(jr(f,e.appSlug,u,l))}function ji(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 qi(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 Gi=new Set(["error","paused"]);function Gr(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let u=Fi(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 Et({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"?()=>Dr({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>pr(n):null,listPrices:n?()=>br(n):null,shared:e.lane==="api-key"?()=>Sr({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:ji});return r=s,t.defaultApp!==null&&t.statelessDirect!==!0&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ke({appSlug:t.defaultApp}))),s}async function hn(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,e===void 0?void 0:{signal:e})}async function qr(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 yn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Hr(t,e=_t,n,r){let o=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,u=new WeakMap,d=c=>{let f=c.session.id;return typeof f=="string"&&f.length>0?f:null},l=c=>{let f=o.get(c);if(!f){let g={waiting:0,gone:new AbortController};u.set(c,g),f=(async()=>{if(await hn(c.session,g.gone.signal),g.gone.signal.aborted)throw yn(g.gone.signal);u.get(c)===g&&u.delete(c);let _=await lr(c.session,await e());return Object.assign(_,{sessionId:c.session.id})})(),o.set(c,f),f.catch(()=>{o.get(c)===f&&o.delete(c)}),f.then(()=>{u.get(c)===g&&u.delete(c)},()=>{u.get(c)===g&&u.delete(c)})}return f},p=c=>{let f=a.get(c);return f||(f=(async()=>{let g=await l(c);return{appendInputAudio:_=>g.appendInputAudio(_),onOutputAudio:_=>g.onOutputAudio(_),sessionId:d(c)}})(),a.set(c,f),f.catch(()=>{a.get(c)===f&&a.delete(c)})),f},m=async(c,f,g)=>{if(g?.aborted){let h=u.get(c);throw(o.get(c)===void 0||h!==void 0&&h.waiting===0)&&await qr(c.session),yn(g)}let _=f(c),y=u.get(c);return y!==void 0&&y.waiting++,g===void 0?_:new Promise((h,w)=>{let E=()=>{y!==void 0&&--y.waiting===0&&u.get(c)===y&&(y.gone.abort(),u.delete(c),o.delete(c),a.delete(c),qr(c.session).catch(()=>{})),w(yn(g))};g.addEventListener("abort",E,{once:!0});let b=()=>g.removeEventListener("abort",E);_.then(k=>{b(),h(k)},k=>{b(),w(k)})})};return{createResponse:hr({sessionFor:c=>t.sessionFor(c),sessionIdOf:c=>d(c),evict:(c,f)=>t.evict(c,f),onAdmissionVerdict:(c,f,g)=>{qi(g)&&(t.evict(c,f),n?.(c,g.kind==="never-live"?"never-live":"create-failed"))},createStream:async(c,f)=>(await hn(c.session),gn(await c.responses.responses.create(f),c.gone))}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(c,f)=>t.supportsImages(c,f),listImageModels:()=>t.imageModelList(),catalogIdentity:c=>t.catalogIdentityFor(c),servingAppSlug:async c=>await t.servingAppSlugFor(c),supportsAudio:c=>t.supportsAudio(c),supportsSpeech:c=>t.supportsSpeech(c),speechVoices:c=>t.speechVoices(c),supportsTranscription:c=>t.supportsTranscription(c),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(c,f)=>{let{entry:g}=await t.sessionFor(c);return await m(g,l,f)},openAudioOn:async(c,f)=>{let{entry:g}=await t.sessionForHandle(c);return await m(g,p,f)},openVideo:async c=>{let{entry:f}=await t.sessionFor(c),g=s.get(f);return g||(g=cr(f.session),s.set(f,g)),g},openVideoOut:async c=>{let{entry:f}=await t.sessionFor(c),g=i.get(f);return g||(g=mr(f.session),i.set(f,g)),g},sessionHandle:async c=>(await t.handleFor(c)).handle,speechSessionHandle:async c=>(await t.speechHandleFor(c)).handle,evictSpeechSession:async c=>{let{app:f,entry:g}=await t.sessionForHandle(c);await t.evict(f,g)},createResponseOn:async(c,f)=>{let{entry:g}=await t.sessionForHandle(c);return await hn(g.session),gn(await g.responses.responses.create(f),g.gone)},onSessionEnd:async(c,f)=>{let{entry:g}=await t.sessionForHandle(c),_=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 y=!1;return _.onPhase(h=>{if(y||!Gi.has(h.name))return;y=!0;let w=_.endsAt??null;f({timeLeftMs:w?Math.max(0,w.getTime()-Date.now()):null,reason:h.reason??`session ${h.name}`})})},...r?{stateless:r}:{}}}var Fs=require("http");var lo=require("crypto"),co=require("ws");var Wr="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Hi=1007,Jr=1008,he=1011,Tt=1008,S=class extends Error{constructor(n,r=Hi){super(n);this.closeCode=r}closeCode},j=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,At=["setup","clientContent","realtimeInput","toolResponse"];function Kr(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=At.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!At.includes(a));if(o.length>0)throw new S(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${At.join(", ")}`);if(r.length!==1)throw new S(`client message must contain exactly one of ${At.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 zr(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(`
|
|
6
|
+
`)}var Vi={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Ee="urun.videoOut";function Yr(t){return{framing:fr,codec:t}}function Xr(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Ee]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Wi={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Ji=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Ee],Vr=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function Ki(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(!Vr.includes(e.activityHandling))throw new S(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Vr.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var zi=["temperature","maxOutputTokens","responseModalities"];function Qr(t){for(let[p,m]of Object.entries(Wi))if(t[p]!==void 0)throw new S(m);for(let p of Object.keys(t))if(!Ji.includes(p))throw new S(`unsupported setup field "${p}"`);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 p of Object.keys(s))if(!zi.includes(p))throw new S(`unsupported generationConfig field "${p}"`);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 p=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let m of p){let c=String(m).toUpperCase();if(c==="AUDIO"){o=!0;continue}if(c!=="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:zr(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 p of t.tools){let m=j(p);if(!m)throw new S("setup.tools entries must be objects");for(let c of Object.keys(m))if(c!=="functionDeclarations")throw new S(`unsupported tool "${c}" \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 c of m.functionDeclarations){let f=j(c);if(!f||typeof f.name!="string")throw new S("functionDeclarations entries require a string name");a.push({type:"function",name:f.name,description:f.description,parameters:f.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let p=j(t.sessionResumption);if(!p)throw new S("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(p))if(m!=="handle")throw new S(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(p.handle!==void 0&&(typeof p.handle!="string"||p.handle.length===0))throw new S("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof p.handle=="string"?p.handle:null}}let d=t.realtimeInputConfig===void 0?Vi:Ki(t.realtimeInputConfig),l=!1;if(t[Ee]!==void 0){if(!j(t[Ee]))throw new S(`setup["${Ee}"] 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 Zr(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 to(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:zr(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var Ot=16e3,no=24e3,Yi=`audio/pcm;rate=${no}`,ro=Buffer.alloc(960).toString("base64");function Xi(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 Qi(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 Zi(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])!==Ot)throw new S(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${Ot} Hz (audio/pcm;rate=${Ot})`);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=Xi(o,Ot,no);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:Zi(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Qi(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 so(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 io(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function ao(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Yi,data:t}}]}}}}function uo(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 p of l.content){let m=j(p);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)}`,he);let p=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",m;try{m=JSON.parse(p)}catch{throw new S(`upstream function_call arguments are not valid JSON: ${p}`,he)}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:p})}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 ea=256,wn=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>ea;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},ta="local",Xe=t=>t.slice(0,120),_n=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 U){this.ws.close(Jr,Xe(e.message));return}if(e instanceof Y){this.ws.close(Tt,Xe(e.message));return}if(e instanceof S){this.ws.close(e.closeCode,Xe(e.message));return}this.ws.close(he,Xe(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Kr(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}=to(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:ro);return}this.transcript.push(...so(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=Qr(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",Tt);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`,Tt);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(Xr(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[Ee]=Yr(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)",he);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(ao(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)",he);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(Zr(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(he,Xe(`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)}`,he);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=io(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",he);let{messages:i,assistantItems:a}=uo(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ae=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function na(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 Ae(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 Ae(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 Ae(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function po(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 co.WebSocketServer({noServer:!0}),o=new wn;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===Wr&&(a.on("error",()=>{}),(async()=>{let l=na(i,d,n),p;if(e.authenticate)p=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new Ae(401,"invalid local proxy api key");p={clients:e.clients,scope:ta}}r.handleUpgrade(i,a,u,m=>{new _n(m,p,o)})})().catch(l=>{let p=502;(l instanceof Ae||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(p=l.status);let m=p===401?"Unauthorized":p===403?"Forbidden":p===502?"Bad Gateway":"Internal Server Error",c=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${p} ${m}\r
|
|
7
7
|
Connection: close\r
|
|
8
8
|
\r
|
|
9
|
-
${
|
|
10
|
-
`),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
|
|
11
|
-
`}var Bi=256,qi=128;function te(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,qi)}var Se=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>=Bi?"(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}}}},ji=256;function Gi(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 xe=class extends Error{},Ie=class{conversations=new Map;thread(e,n){let r=Gi(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new xe(`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<=ji)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},lo=new WeakMap;function ze(t){let e=lo.get(t);return e||(e=new Ie,lo.set(t,e)),e}function Te(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function se(t){return t.find(e=>e.type==="response.completed")?.response??null}function Pe(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 ge=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}))}},Hi=["<tool_call>","<function="];function Vi(t){return Hi.find(e=>t.includes(e))}function Re(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Ee(t,e,n){if(!(!t||e>0))return Vi(n)}function Et(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 Ji(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 cn(t,e){let n=Ji(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ee=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Ce(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof xe?new ee(n.message,"previous_response_not_found",400,"previous_response_id"):new ee(String(n instanceof Error?n.message:n),"invalid_input")}}function co(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function pn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ee("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}:{},...co(e)!==void 0?{response_format:co(e)}:{}},o)}async function Ye(t){let{body:e,clients:n,store:r,stats:o}=t,s=Ce(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=te(e);o.model(d);let c=Array.isArray(e.tools)&&e.tools.length>0,l=t.turn,f=await pn(n,e,s,!0,l?oe(l):void 0);return{responseId:i,events:Wi({events:f,conversation:s,responseId:i,modelKey:d,requestHadTools:c,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}async function*Wi(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,c=[],l=P=>P.response&&typeof P.response=="object"?{...P,response:{...P.response,id:r}}:P,f=`item_${r.slice(5)}`,p=`rs_${r.slice(5)}`,h=!1,k=!1,m=0;function*_(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let g=!1,y=0,E="";function*v(){g&&(g=!1,yield{type:"response.reasoning_text.done",item_id:p,output_index:y,content_index:0,text:E},yield{type:"response.output_item.done",output_index:y,item:{id:p,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:E}],status:"completed"}})}let S=!1,w=0,x="";function*I(P){S&&(S=!1,yield{type:"response.output_text.done",item_id:f,output_index:w,content_index:0,text:x},yield{type:"response.content_part.done",item_id:f,output_index:w,content_index:0,part:{type:"output_text",text:x}},yield{type:"response.output_item.done",output_index:w,item:{id:f,type:"message",role:"assistant",status:P,content:[{type:"output_text",text:x}]}})}let L=new ge,O=null,W=-1;function*z(P){if(!O)return;let D=O;O=null,yield{type:"response.function_call_arguments.done",item_id:D.fcId,output_index:D.outputIndex,arguments:D.args},yield{type:"response.output_item.done",output_index:D.outputIndex,item:{id:D.fcId,type:"function_call",call_id:D.callId??D.fcId,name:D.name??"",arguments:D.args,status:P}}}let J=!1;for await(let P of d.track(e,o,t.turn)){c.push(P);let D=String(P.type??"");if(D==="response.created"||D==="response.in_progress"){h=!0,yield l(P);continue}if(D==="response.output_item.added"){k=!0,yield l(P);continue}if(D==="response.reasoning_text.delta"&&!k){yield*_(),g||(g=!0,y=m++,yield{type:"response.output_item.added",output_index:y,item:{id:p,type:"reasoning",summary:[],content:[],status:"in_progress"}}),E+=String(P.delta??""),yield{type:"response.reasoning_text.delta",item_id:p,output_index:y,content_index:0,delta:P.delta};continue}if(D==="response.output_text.delta"&&!k){yield*_(),yield*v(),S||(S=!0,w=m++,yield{type:"response.output_item.added",output_index:w,item:{id:f,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:f,output_index:w,content_index:0,part:{type:"output_text",text:""}}),x+=String(P.delta??""),yield{type:D,item_id:f,output_index:w,content_index:0,delta:P.delta};continue}let j=k?null:Pe(P);if(j){if(yield*_(),yield*v(),yield*I("completed"),L.add(j),j.tool_index!==W){yield*z("completed"),W=j.tool_index;let Q=m++;O={fcId:`fc_${r.slice(5)}_${j.tool_index}`,outputIndex:Q,callId:j.call_id,name:j.name,args:""},yield{type:"response.output_item.added",output_index:Q,item:{id:O.fcId,type:"function_call",call_id:O.callId??O.fcId,name:O.name??"",arguments:"",status:"in_progress"}}}O&&(j.call_id&&(O.callId=j.call_id),j.name&&(O.name=j.name),O.args+=j.delta,yield{type:"response.function_call_arguments.delta",item_id:O.fcId,output_index:O.outputIndex,delta:j.delta});continue}if(D==="response.completed"&&!k){let Q=Te(P.response),we=Ee(s,L.size+Q.length,x);if(we){J=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Re(o,we)}};break}if(yield*v(),yield*I("completed"),yield*z("completed"),L.size===0)for(let _e of Q){let me=m++,de=_e.id??_e.call_id??`fc_${me}`,De=_e.arguments??"",Oe={id:de,type:"function_call",call_id:_e.call_id??de,name:_e.name??""};yield{type:"response.output_item.added",output_index:me,item:{...Oe,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:de,output_index:me,delta:De},yield{type:"response.function_call_arguments.done",item_id:de,output_index:me,arguments:De},yield{type:"response.output_item.done",output_index:me,item:{...Oe,arguments:De,status:"completed"}}}yield l(P);continue}yield l(P)}if(yield*v(),yield*I("incomplete"),yield*z("incomplete"),i&&!J){let P=se(c);u.remember(r,n,cn(P,Et(c,P)),a)}}var Ki="/v1/responses",zi=64*1024*1024,Yi=8*1024*1024,Xi=16,po=32,fo=3600*1e3,Qi=/^[A-Za-z0-9._-]{1,256}$/;function Y(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Zi=Y(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 gn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function ea(t){for(;t.bufferedAmount>Yi&&t.readyState===he.WebSocket.OPEN;){let{promise:e,resolve:n}=gn();setTimeout(n,5),await e}}var fn=class extends Ie{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 xe))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)}},mn=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new fn(ze(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(Y(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${fo/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},fo).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(Y(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(Y(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(Y(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(Y(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(Y(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(Y(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"||!Qi.test(o.stream_id)){this.sendFrame(Zi);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=po){this.sendFrame(Y(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${po}). 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 Ye({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ke(We())})}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!==he.WebSocket.OPEN)break;this.send(i,n),await ea(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=Ke(We());try{let o=Ce(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 ee)return Y(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof M)return Y(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof K)return Y(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?Y(o.status,{type:o.openaiType,message:r},n):Y(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Xi;){let{promise:e,resolve:n}=gn();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!==he.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!==he.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function At(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
9
|
+
${c}\r
|
|
10
|
+
`),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 ke=require("ws");var fo=require("crypto"),mo="Inference-Id";function Qe(){return(0,fo.randomUUID)()}function vn(t){return t==="/v1"||t.startsWith("/v1/")}function go(t,e){if(!vn(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 Ze(t){return`resp_${t}`}function ho(t){return`chatcmpl-${t}`}function yo(t){return`msg_${t}`}function oe(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function wo(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,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function _o(t){return`${JSON.stringify(t)}
|
|
11
|
+
`}var ra=256,oa=128;function te(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,oa)}var Oe=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>=ra?"(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}}}},sa=256;function ia(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 Ie=class extends Error{},Me=class{conversations=new Map;thread(e,n){let r=ia(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ie(`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<=sa)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},vo=new WeakMap;function et(t){let e=vo.get(t);return e||(e=new Me,vo.set(t,e)),e}function Ue(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ue(t){return t.find(e=>e.type==="response.completed")?.response??null}function Ne(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var be=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},aa=["<tool_call>","<function="];function ua(t){return aa.find(e=>t.includes(e))}function Te(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 Pe(t,e,n){if(!(!t||e>0))return ua(n)}function De(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 da(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 bn(t,e){let n=da(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var se=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Be(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ie?new se(n.message,"previous_response_not_found",400,"previous_response_id"):new se(String(n instanceof Error?n.message:n),"invalid_input")}}function bo(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function kn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new se("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...bo(e)!==void 0?{response_format:bo(e)}:{}},o)}async function tt(t){let{body:e,clients:n,store:r,stats:o}=t,s=Be(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=te(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,p=t.turn,m=await kn(n,e,s,!0,p?oe(p):void 0);return{responseId:i,events:fa({events:m,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}function la(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?pa(o[i++],u):u),...ca(r,n)]}function ca(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 pa(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*fa(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,l=[],p=C=>C.response&&typeof C.response=="object"?{...C,response:{...C.response,id:r}}:C,m=`item_${r.slice(5)}`,c=!1,f=!1,g=0;function*_(){c||(c=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let y=[],h=(C,N)=>{y.push({output_index:C,item:N})},w=!1,E=0,b="",k=0,v="";function*x(){if(!w)return;w=!1,yield{type:"response.reasoning_text.done",item_id:b,output_index:E,content_index:0,text:v};let C={id:b,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:v}],status:"completed"};yield{type:"response.output_item.done",output_index:E,item:C},h(E,C),v=""}let O=!1,T=0,$="",K=0,Q="",z="";function*Z(C){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:$,output_index:T,content_index:0,text:Q},yield{type:"response.content_part.done",item_id:$,output_index:T,content_index:0,part:{type:"output_text",text:Q}};let N={id:$,type:"message",role:"assistant",status:C,content:[{type:"output_text",text:Q}]};yield{type:"response.output_item.done",output_index:T,item:N},h(T,N),Q=""}let pe=new be,q=null,fe=-1;function*we(C){if(!q)return;let N=q;q=null,yield{type:"response.function_call_arguments.done",item_id:N.fcId,output_index:N.outputIndex,arguments:N.args};let W={id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:N.args,status:C};yield{type:"response.output_item.done",output_index:N.outputIndex,item:W},h(N.outputIndex,W)}let mt=!1;for await(let C of d.track(e,o,t.turn)){l.push(C);let N=String(C.type??"");if(N==="response.created"||N==="response.in_progress"){c=!0,yield p(C);continue}if(N==="response.output_item.added"){f=!0,yield p(C);continue}if(N==="response.reasoning_text.delta"&&!f){yield*_(),w||(w=!0,E=g++,k+=1,b=k===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${k}`,yield{type:"response.output_item.added",output_index:E,item:{id:b,type:"reasoning",summary:[],content:[],status:"in_progress"}}),v+=String(C.delta??""),yield{type:"response.reasoning_text.delta",item_id:b,output_index:E,content_index:0,delta:C.delta};continue}if(N==="response.output_text.delta"&&!f){yield*_(),yield*x(),O||(O=!0,T=g++,K+=1,$=K===1?m:`${m}_${K}`,yield{type:"response.output_item.added",output_index:T,item:{id:$,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:$,output_index:T,content_index:0,part:{type:"output_text",text:""}}),Q+=String(C.delta??""),z+=String(C.delta??""),yield{type:N,item_id:$,output_index:T,content_index:0,delta:C.delta};continue}let W=f?null:Ne(C);if(W){if(yield*_(),yield*x(),yield*Z("completed"),pe.add(W),W.tool_index!==fe){yield*we("completed"),fe=W.tool_index;let me=g++;q={fcId:`fc_${r.slice(5)}_${W.tool_index}`,outputIndex:me,callId:W.call_id,name:W.name,args:""},yield{type:"response.output_item.added",output_index:me,item:{id:q.fcId,type:"function_call",call_id:q.callId??q.fcId,name:q.name??"",arguments:"",status:"in_progress"}}}q&&(W.call_id&&(q.callId=W.call_id),W.name&&(q.name=W.name),q.args+=W.delta,yield{type:"response.function_call_arguments.delta",item_id:q.fcId,output_index:q.outputIndex,delta:W.delta});continue}if(N==="response.completed"&&!f){let me=Ue(C.response),B=Pe(s,pe.size+me.length,z);if(B){mt=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Te(o,B)}};break}if(yield*x(),yield*Z("completed"),yield*we("completed"),pe.size===0)for(let _e of me){let $e=g++,gt=_e.id??_e.call_id??`fc_${$e}`,nn=_e.arguments??"",er={id:gt,type:"function_call",call_id:_e.call_id??gt,name:_e.name??""};yield{type:"response.output_item.added",output_index:$e,item:{...er,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:gt,output_index:$e,delta:nn},yield{type:"response.function_call_arguments.done",item_id:gt,output_index:$e,arguments:nn};let tr={...er,arguments:nn,status:"completed"};yield{type:"response.output_item.done",output_index:$e,item:tr},h($e,tr)}let ee=la(y,C.response);yield ee.length>0?p({...C,response:{...C.response,output:ee}}):p(C);continue}yield p(C)}if(yield*x(),yield*Z("incomplete"),yield*we("incomplete"),i&&!mt){let C=ue(l);u.remember(r,n,bn(C,De(l,C)),a)}}var ma="/v1/responses",ga=64*1024*1024,ha=8*1024*1024,ya=16,ko=32,So=3600*1e3,wa=/^[A-Za-z0-9._-]{1,256}$/;function ne(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var _a=ne(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function Rn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function va(t){for(;t.bufferedAmount>ha&&t.readyState===ke.WebSocket.OPEN;){let{promise:e,resolve:n}=Rn();setTimeout(n,5),await e}}var Sn=class extends Me{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 Ie))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)}},xn=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new Sn(et(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ne(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${So/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},So).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(ne(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(ne(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(ne(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(ne(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(ne(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(ne(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!wa.test(o.stream_id)){this.sendFrame(_a);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=ko){this.sendFrame(ne(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${ko}). 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 tt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ze(Qe())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==ke.WebSocket.OPEN)break;this.send(i,n),await va(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=Ze(Qe());try{let o=Be(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof se)return ne(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof U)return ne(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof Y)return ne(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?ne(o.status,{type:o.openaiType,message:r},n):ne(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=ya;){let{promise:e,resolve:n}=Rn();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==ke.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!==ke.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Pt(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
12
12
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
13
13
|
Connection: close\r
|
|
14
14
|
Content-Type: text/plain; charset=utf-8\r
|
|
15
15
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
16
16
|
\r
|
|
17
|
-
${o}`)}function
|
|
18
|
-
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let a of
|
|
19
|
-
`)}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
|
|
17
|
+
${o}`)}function xo(t,e){let n=new ke.WebSocketServer({noServer:!0,maxPayload:ga}),r=new Oe,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,p,m)=>{let c;try{c=new URL(l.url??"/","http://localhost")}catch{Pt(p,400,"malformed upgrade URL");return}if(p.on("error",()=>p.destroy()),p.on("close",()=>i.delete(p)),c.pathname!==ma){i.add(p);return}s.add(p);let f=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){Pt(p,401,"invalid local proxy api key");return}let g;try{g=await a(l)}catch(_){let y=e.statusOf?.(_)??null;Pt(p,y?.status??500,"upstream resolver rejected the connection");return}u||p.destroyed||(f=!0,n.handleUpgrade(l,p,m,_=>{s.delete(p),o.add(_),_.on("close",()=>o.delete(_));try{new xn(_,g,r,e.statusOf)}catch{o.delete(_),_.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!f&&!p.destroyed&&Pt(p,500,"responses websocket upgrade failed")}).finally(()=>s.delete(p))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:p}=Rn();if(u)return p(),l;u=!0,t.off("upgrade",d);for(let c of s)c.destroy();s.clear();for(let c of i)c.destroy();i.clear();for(let c of o)c.close(1001,"server shutting down");let m=setTimeout(()=>{for(let c of o)c.readyState!==ke.WebSocket.CLOSED&&c.terminate()},2e3);return m.unref?.(),n.close(()=>{clearTimeout(m),p()}),l}}}var Qo=require("@urun-sh/core");var Ro=require("@urun-sh/core"),ba={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},ka={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform will cold-wake it on request; retry",queue_timeout:"the session was admitted but never became live within the cold-wake fence \u2014 the backend is busy or wedged; retry",cold_start_exceeded:"the cold boot exceeded its budget without serving \u2014 the platform keeps pursuing the wake; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"admission is momentarily contended (lock convoy) \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session"};function En(t,e){let n=ka[t.code];return e?`${n} (${e})`:n}function Ct(t){if(t==null)return null;let e=ba[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function $t(t){if(t.kind==="create-failed")return Ct(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Ro.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Ct(e?"cold_start_exceeded":"queue_timeout")}var Ao=xe(require("os"),1),Oo=xe(require("path"),1),Io=require("url"),To=require("util");var Eo="0.6.2";var Po=4141,xa=Eo,Mt={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 In(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 Co(t,e,n){let r={...t,...In(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,delete r.URUN_SESSION_TOKEN_SECRET,r}function $o(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 Lo(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function Mo(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function Uo(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,Io.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 No(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 Do(t){if(t[0]!=="--port")return null;let e=No(t[1]);return t.splice(0,2),e}function Tn(t){let e=t.indexOf("--port");if(e===-1)return Po;let n=No(t[e+1]);return t.splice(e,2),n}function Bo(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 An(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 Fe(t){let e=Ra(An(t,"URUN_BASE_URL")),n=An(t,"URUN_ORG_ID"),r=An(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?Lt(s,"URUN_API_URL"):Nr,a=(t.URUN_SESSION_TOKEN_SECRET??"").trim(),u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"jwt",jwt:u}};let d=(t.URUN_API_KEY??"").trim();if(d){let l=(t.URUN_GATEWAY_URL??"").trim(),p=l?Lt(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,decisionSecret:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:p}}}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 Ra(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 Lt(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 Pn(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:xa}}function Ea(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 Aa=250;async function Cn(t,e=Aa){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 Fo=2e3;async function Oa(t,e=Fo){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 jo(t,e,n=Po,r=Fo){if(t!=null)return{mode:"spawn",port:t};let o=await Cn(n);if(o!==null&&Ea(o,e)){let s=await Oa(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 $n(t,e=Ao.default.homedir()){return Oo.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var On=["log","info","warn","error","debug","trace"];function qo(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(On.map(a=>[a,n[a]]));for(let a of On)n[a]=(...u)=>{t.write(`${(0,To.format)(...u)}
|
|
18
|
+
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let a of On)n[a]=i[a]}}var Ia=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Go(t){let e=t?.code;return typeof e=="string"&&Ia.has(e)}function ie(t,e){try{return t.write(e),!0}catch(n){if(Go(n))return!1;throw n}}function Ho(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{Go(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
|
|
19
|
+
`)}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 Vo(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
20
20
|
`)}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}
|
|
21
21
|
`)}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
|
|
22
|
-
`)}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 Mo(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 jo=require("ws");var Do=require("crypto");function R(t){return`${t}_${(0,Do.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Ct=4*1024*1024,xn=8*1024*1024,$t=512,Lt=20*1024*1024;function q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Qe(t,e){return{type:"server_error",code:t,message:e}}function N(t){return{type:"error",event_id:R("event"),error:t}}function Rn(){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},la={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},ca={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},pa={format:!0,voice:!0,speed:!0};function No(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 Xe(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 la));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,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new A("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new A("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 A("modalities must be a non-empty array","modalities");let u=[];for(let d of a){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");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 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=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new A(`${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 A("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 A(`${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 A("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 A("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 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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new A("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new A(`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 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(!a||typeof a!="object"||Array.isArray(a))throw new A("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new A(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new 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(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new A("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 A("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in ca))throw new A(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&No(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Xe({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let c=Xe({turn_detection:d.turn_detection},s,n);s.turnDetection=c.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(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new A("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in pa))throw new A(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&No(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 Ut(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function En(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 An(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 fa=1001,ma=1011,Fo=t=>t.slice(0,120),ga=/^[A-Za-z0-9+/=]*$/,ha=2;function ya(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>ha)return!1;return!0}var Ze=class{id=R("conn");ws;binding;onClosed;config=Rn();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:R("event"),session:Ut(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(N(Qe("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:R("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=R("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Ct){this.fail(q("frame_too_large",`frame exceeds the ${Ct}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(q("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(q("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(N({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(Qe(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=Xe(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:R("event"),session:Ut(this.config,this.sessionId)});return;case"conversation.item.create":{let n=En(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(N(q("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(N(q("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(N(q("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(N(q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!ga.test(e.audio)){this.send(N(q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>Lt){this.send(N(q("buffer_full",`uncommitted input audio exceeds the ${Lt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(N(q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(N(q("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(N(q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(N(q("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(N({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(N(q("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(k=>k!=="text"&&k!=="audio")){this.send(N(q("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(N(q("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}=An(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,c=n.max_output_tokens??this.config.maxOutputTokens,l=c==="inf"||c===void 0?void 0:c,f=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,h={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...l!==void 0?{max_output_tokens:l}:{},...f!==void 0?{tools:f}:{},...p!==void 0?{tool_choice:p}:{}};for(let k of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(k);this.inFlight=(async()=>{let k=[],m=E=>{this.responseFlushed?this.send(E):k.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 k)this.send(E);k.length=0,this.responseFlushed=!0}},g={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},y=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(h,r)}catch(v){this.emitUpstreamFault(v,o);return}try{for await(let v of E){if(this.cancelled)break;let S=v;if(S.type==="error"){let w=this.upstreamErrorBody(S);this.responseFlushed?this.send(N(w)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(o,w)});return}if(S.type==="response.output_text.delta"&&typeof S.delta=="string"){_(),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:S.delta}),g.messageText+=S.delta;continue}if(S.type==="response.function_call_arguments.delta"){_();let w=typeof S.delta=="string"?S.delta:"",x=typeof S.call_id=="string"&&S.call_id.length>0?S.call_id:`${o}_fc_${g.nextOutputIndex}`,I=g.tools.get(x);if(!I){let L=typeof S.name=="string"&&S.name.length>0?S.name:void 0;I={outputIndex:g.nextOutputIndex++,name:L,args:""},g.tools.set(x,I),m({type:"response.output_item.added",event_id:R("event"),response_id:o,output_index:I.outputIndex,item:{id:x,object:"realtime.item",type:"function_call",call_id:x,name:L??"",arguments:"",status:"in_progress"}})}typeof S.name=="string"&&S.name.length>0&&(I.name=S.name),I.args+=w,m({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:x,response_id:o,output_index:I.outputIndex,call_id:x,name:I.name??"",delta:w});continue}if(S.type==="response.completed"){y=S.response??null;continue}}}catch(v){this.emitUpstreamFault(v,o);return}if(this.cancelled)return;this.closeOpenItems(o,g,s),_(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(o,s,y)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(ya(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(N({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}}emitUpstreamFault(e,n){if(this.cancelled)return;let r=Qe(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send(N(r)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(N(q("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>$t&&(this.items.shift(),this.send(N({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${$t} 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>xn){this.ws.close(fa,Fo("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send(N(e)),this.ws.close(ma,Fo(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>Bo(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Bo(this.id,e)}}},On=[];function Bo(t,e){On.push({id:t,reason:e}),On.length>256&&On.shift()}var Tn="/v1/realtime",wa=t=>t.slice(0,120);function _a(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
22
|
+
`)}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 Wo(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 Zo=require("ws");var Xo=require("@urun-sh/core");var Ko=require("crypto");function R(t){return`${t}_${(0,Ko.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Ut=4*1024*1024,Ln=8*1024*1024,Nt=512,Dt=20*1024*1024;function G(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function je(t,e){return{type:"server_error",code:t,message:e}}function D(t){return{type:"error",event_id:R("event"),error:t}}function Mn(){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},Ta={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},Pa={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ca={format:!0,voice:!0,speed:!0};function Jo(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 nt(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 Ta));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,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new A("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new A("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 A("modalities must be a non-empty array","modalities");let u=[];for(let d of a){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");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 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=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new A(`${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 A("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 A(`${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 A("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 A("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 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 u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new A("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new A(`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 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(!a||typeof a!="object"||Array.isArray(a))throw new A("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new A(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new 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(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new A("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 A("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in Pa))throw new A(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&Jo(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=nt({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=nt({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(u.output!==void 0&&u.output!==null){let d=u.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 Ca))throw new A(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&Jo(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 Bt(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Un(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 Nn(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 $a=1001,La=1011,zo=t=>t.slice(0,120),Ma=/^[A-Za-z0-9+/=]*$/,Ua=2;function Na(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Ua)return!1;return!0}var rt=class{id=R("conn");ws;binding;onClosed;config=Mn();sessionId=R("sess");conversationId=R("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:R("event"),session:Bt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:R("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send(D(je("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:R("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:R("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=R("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:R("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:R("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(G("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Ut){this.fail(G("frame_too_large",`frame exceeds the ${Ut}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(G("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(G("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(D({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(je(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=nt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:R("event"),session:Bt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=Un(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(!Ma.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.pendingAudioBytes.length+n>Dt){this.send(D(G("buffer_full",`uncommitted input audio exceeds the ${Dt}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:R("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(D(G("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=R("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:R("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:R("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send(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":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,...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(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(g=>g!=="text"&&g!=="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:a}=Nn(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,p=l==="inf"||l===void 0?void 0:l,m=n.tools!==void 0?n.tools:this.config.tools,c=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,f={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...p!==void 0?{max_output_tokens:p}:{},...m!==void 0?{tools:m}:{},...c!==void 0?{tool_choice:c}:{}};for(let g of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(g);this.inFlight=(async()=>{let g=[],_=E=>{this.responseFlushed?this.send(E):g.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 g)this.send(E);g.length=0,this.responseFlushed=!0}},h={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},w=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let E;try{E=await this.upstreamStream(f,r)}catch(b){this.upstreamTurnFault(b,o);return}try{for await(let b of E){if(this.cancelled)break;let k=b;if(k.type==="error"){let v=this.upstreamErrorBody(k);this.responseFlushed?this.send(D(v)):this.send({type:"response.failed",event_id:R("event"),response:this.failedResponse(o,v)});return}if(k.type==="response.output_text.delta"&&typeof k.delta=="string"){y(),h.messageOpen||(this.beginMessageItem(o,h.nextOutputIndex++),h.messageOpen=!0),_({type:"response.output_text.delta",event_id:R("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:k.delta}),h.messageText+=k.delta;continue}if(k.type==="response.function_call_arguments.delta"){y();let v=typeof k.delta=="string"?k.delta:"",x=typeof k.call_id=="string"&&k.call_id.length>0?k.call_id:`${o}_fc_${h.nextOutputIndex}`,O=h.tools.get(x);if(!O){let T=typeof k.name=="string"&&k.name.length>0?k.name:void 0;O={outputIndex:h.nextOutputIndex++,name:T,args:""},h.tools.set(x,O),_({type:"response.output_item.added",event_id:R("event"),response_id:o,output_index:O.outputIndex,item:{id:x,object:"realtime.item",type:"function_call",call_id:x,name:T??"",arguments:"",status:"in_progress"}})}typeof k.name=="string"&&k.name.length>0&&(O.name=k.name),O.args+=v,_({type:"response.function_call_arguments.delta",event_id:R("event"),item_id:x,response_id:o,output_index:O.outputIndex,call_id:x,name:O.name??"",delta:v});continue}if(k.type==="response.completed"){w=k.response??null;continue}}}catch(b){this.upstreamTurnFault(b,o);return}if(this.cancelled)return;this.closeOpenItems(o,h,s),y(),this.send({type:"response.done",event_id:R("event"),response:this.doneResponse(o,s,w)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Na(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 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(je("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 Y){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof Xo.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=je(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>Nt&&(this.items.shift(),this.send(D({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Nt} 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>Ln){this.ws.close($a,zo("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(La,zo(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>Yo(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Yo(this.id,e)}}},Dn=[];function Yo(t,e){Dn.push({id:t,reason:e}),Dn.length>256&&Dn.shift()}var Fn="/v1/realtime",Da=t=>t.slice(0,120);function Ba(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
23
|
Connection: close\r
|
|
24
24
|
Content-Type: text/plain\r
|
|
25
25
|
\r
|
|
26
|
-
${
|
|
27
|
-
`),t.destroy()}function
|
|
28
|
-
`}function ba(t){ne(process.stdout,t)}function ka(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function In(t){return t.audioSession?.audio.sessionId??void 0}function Pn(t,e){let n=new jo.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Tn)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=R("rtup"),d=ka(o),c=v=>{(e.log??ba)(va(v))};c({stage:"accept",conn:u,model:d}),s.resume();let l=new AbortController,f=null,p=v=>{f??=v,l.abort(new Error(f))},h=()=>p("client socket closed"),k=()=>p("client socket closed (half-close)"),m=v=>p(`client socket error: ${v.message}`);s.once("close",h),s.once("end",k),s.once("error",m);let _=()=>{s.removeListener("close",h),s.removeListener("end",k),s.removeListener("error",m)},g=v=>{c({stage:"close",conn:u,model:d,...v})},y=v=>{let S=v,w=S.session!=null&&typeof S.session.sendResponseCreate=="function",x=S.clients!=null&&typeof S.clients.createResponse=="function";if(!w&&!x)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((I,L)=>{n.handleUpgrade(o,s,i,O=>{try{new Ze({ws:O,binding:v,onClosed:(W,z)=>{g({while:"live",reason:z.reason})}}),c({stage:"admit",conn:u,model:d,...In(v)===void 0?{}:{session:In(v)}}),I()}catch(W){L(W)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,l.signal).then(async v=>{if(l.signal.aborted){_();let S=In(v);try{await v.release?.()}catch(w){g({while:"queued",...S===void 0?{}:{session:S},reason:f??"client socket closed",release_failed:w instanceof Error?w.message:String(w)});return}g({while:"queued",...S===void 0?{}:{session:S},reason:f??"client socket closed",released:!0}),s.destroy();return}_(),await y(v)}).catch(v=>{let S=v instanceof qo.SessionFailedError?It(v):null,w=null;if(v!==null&&typeof v=="object"&&"status"in v){let L=v.status;typeof L=="number"&&(w=L)}let x=w??S?.status??502,I=v instanceof Error?v.message:String(v);g({while:"queued",...l.signal.aborted?{reason:f??"client socket closed"}:{reason:I,status:x}}),s.destroyed||_a(s,x,I)}).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 et=(t,e)=>Object.assign(new Error(e),{status:t});function Sa(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function xa(t,e,n){if(!t.supportsAudio)throw et(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let r;try{r=await t.supportsAudio(e)}catch(i){throw i instanceof M?et(404,i.message):i}if(!r)throw et(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.openAudio)throw et(501,"an audio-capable model needs a router-backed client (openAudio) to open its native session audio bridge \u2014 refusing loudly rather than binding a voiceless session");let o={audio:await t.openAudio(e,n)},s={clients:t,voice:r,audioSession:o};return e!==void 0&&(s.model=e),s}function Go(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 et(401,"invalid local proxy api key")}return xa(t,Sa(n),r)}}}var Ho="/v1/images/generations",Mt="/v1/images/edits";function Vo(t){return t===Ho||t===Mt}var Jo="/v1/images/models";async function Wo(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var $=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Ra=16*1024*1024,Ko=64*1024*1024;function zo(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 tt(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}:{}}}))}var pe=class extends Error{};async function Ea(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new pe(`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 pe(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Yo(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let l of o){if(l.type==="error"){let f=l.error??{};throw new $(502,`image upstream error: ${String(f.message??"upstream reported an error")}`)}if(l.type==="response.completed"){s=l.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 a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(zo(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 a.push(u),{images:a}}function Xo(t){return t instanceof $?t:t instanceof M?new $(404,t.message):new $(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Qo(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 tt(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 Zo(t,e){t&&(t.outputUnits=e.images.length)}function es(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 Aa={model:!0,prompt:!0,response_format:!0,n:!0};async function ts(t,e,n){let r=n.maxBodyBytes??Ko;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${Ho}`);let o;try{o=JSON.parse((await Ea(t,r)).toString("utf8")||"{}")}catch(l){throw l instanceof pe?new $(413,l.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 l of Object.keys(s))if(!Aa[l])throw new $(400,`request field "${l}" 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.`,l);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 Wo(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 Qo(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:i}];try{let l=await Yo(n.clients,a,c,n.turn?oe(n.turn):void 0);Zo(n.turn,l),es(e,l)}catch(l){throw Xo(l)}}catch(o){if(o instanceof pe){tt(e,new $(413,o.message));return}if(o instanceof $){tt(e,o);return}throw o}}var Oa={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function ns(t,e,n){let r=n.maxBodyBytes??Ko,o=n.maxImagePartBytes??Ra;try{if(t.method!=="POST")throw new $(405,`${String(t.method)} is not supported on ${Mt}`);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=t[Symbol.asyncIterator](),a=0,u=new ReadableStream({async pull(m){try{let _=await i.next();if(_.done){m.close();return}if(a+=_.value.length,a>r){m.error(new pe(`request body exceeds the ${r}-byte limit`));return}m.enqueue(_.value)}catch(_){m.error(_)}},cancel(){i.return?.()}}),d;try{let m=new Headers;for(let[y,E]of Object.entries(t.headers))if(typeof E=="string")m.set(y,E);else if(Array.isArray(E))for(let v of E)m.append(y,v);let _={method:"POST",headers:m,body:u,duplex:"half"};d=await new Request(`https://proxy.internal${t.url??"/"}`,_).formData()}catch(m){throw m instanceof pe?new $(413,m.message):new $(400,`malformed multipart body: ${String(m instanceof Error?m.message:m)}`)}let c=d.get("prompt");if(typeof c!="string"||c.trim().length===0)throw new $(400,"prompt is required and must be a non-empty string field","prompt");let l=d.get("model");if(l!==null&&typeof l!="string")throw new $(400,"model must be a string field","model");let f=l===null?void 0:l;await Wo(n.turn,n.clients,f);let p=d.get("response_format")??"b64_json";if(p!=="b64_json")throw new $(400,`response_format ${JSON.stringify(p)} 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 m of d.keys())if(!Oa[m])throw new $(400,`form field "${m}" 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[]).`,m);let h=[];for(let m of["image","image[]"])for(let _ of d.getAll(m)){if(!(_ 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",m);if(_.size>o)throw new $(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let g=new Uint8Array(await _.arrayBuffer()),y=zo(g);if(y===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)",m);h.push({bytes:g,mime:y})}if(h.length===0)throw new $(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",c.length,c.length),!await Qo(n.imageModels,f,"edit",e))return;let k=[{type:"input_text",text:c}];for(let{bytes:m,mime:_}of h)k.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Yo(n.clients,f,k,n.turn?oe(n.turn):void 0);Zo(n.turn,m),es(e,m)}catch(m){throw Xo(m)}}catch(s){if(s instanceof pe){tt(e,new $(413,s.message));return}if(s instanceof $){tt(e,s);return}throw s}}var rt="/v1/audio/speech";function as(t){return t===rt}var rs=4096,Ia=18e4,Ta=5e3,Pa=64*1024*1024,os=8,ss=5,Dt="voice_applied",Ca="X-Urun-Voice-Applied",C=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Cn(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 Le=class extends Error{},Ft=class extends C{constructor(e){super(502,e)}};async function $a(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new Le(`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 Le(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function La(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Ua(t,e){t&&(t.outputUnits=e/(24e3*2))}var Ma=2;function Na(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>Ma)return!1;return!0}function Da(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 is=new WeakMap,Nt=new WeakMap;function Fa(t,e){let n=Nt.get(t)??0;if(n>=os)throw new C(503,`this model's speech queue is full \u2014 ${os} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ss}s`,void 0,ss);Nt.set(t,n+1);let r=is.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return is.set(t,s),(async()=>{await r;try{return await e()}finally{Nt.set(t,(Nt.get(t)??1)-1),o()}})()}async function Ba(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new C(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 K))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 nt(t){return t instanceof C?t:t instanceof M?new C(404,t.message):new C(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function qa(t,e,n,r,o,s,i){return Fa(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,c=!1,l=!1,f,p=new Promise(E=>{f=E}),h=()=>{c&&!l&&d>=o.quietRunFrames&&(l=!0,f())},k=e.onOutputAudio(E=>{let v=Buffer.from(E,"base64");if(v.byteLength===0)return;let S=Na(v);if(!u){if(S)return;u=!0}a.push(v),d=S?d+1:0,h()}),m=null,_,g,y;try{y=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let v=new Promise(I=>{g=setTimeout(I,s.capMs)}),S=!1;for(;;){let I=y.next(),L=await Promise.race([I,v]);if(L===void 0){S=!0,I.catch(()=>{});break}if(L.done)break;let O=L.value;if(O.type==="error"){let W=O.error??{};throw await y.return?.(),new C(502,`speech upstream error: ${String(W.message??"upstream reported an error")}`)}if(O.type==="response.completed"){m=O.response??null,c=!0,h(),await y.return?.();break}}if(clearTimeout(g),S)throw new C(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(m===null)throw new C(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let w=!1;if(await Promise.race([p,new Promise(I=>{_=setTimeout(()=>{w=!0,I()},o.capMs)})]),_!==void 0&&clearTimeout(_),r.voice!==void 0){let I=m[Dt];if(typeof I!="string"||I!==r.voice){let L=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof I=="string"?`${Dt} ${JSON.stringify(I)}`:`no ${Dt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw l?new Ft(L):new C(502,L)}}if(!u)throw new C(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(w&&!l&&d<1)throw new C(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);let x=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(x),completed:m}}catch(E){throw E instanceof Ft||await Ba(t,n,y,s.returnBoundMs),E}finally{_!==void 0&&clearTimeout(_),g!==void 0&&clearTimeout(g),k()}})}async function ja(t,e,n){let r;try{r=await t(e)}catch(o){throw nt(o)}return r?!0:(Cn(n,new C(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 Ga={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},Ha="wav, pcm";async function us(t,e,n){let r=n.maxBodyBytes??Pa,o=!1;e.once("close",()=>{o=!0});let s=()=>o||e.destroyed;try{if(t.method!=="POST")throw new C(405,`${String(t.method)} is not supported on ${rt}`);let i;try{i=JSON.parse((await $a(t,r)).toString("utf8")||"{}")}catch(y){throw y instanceof Le?new C(413,y.message):new C(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new C(400,"request body must be a JSON object");let a=i;for(let y of Object.keys(a))if(!Ga[y])throw new C(400,`request field "${y}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,y);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new C(400,"input is required and must be a non-empty string","input");if(u.length>rs)throw new C(400,`input is ${u.length} chars \u2014 over the ${rs}-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 C(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new C(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new C(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 ${rt} against a stale copy of the list`);let l;try{l=await n.clients.speechVoices(d)}catch(y){throw nt(y)}if(l.defect!==null)throw new C(500,`the voice set for this model cannot be resolved: ${l.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let f=typeof c=="string"?c:void 0;if(f!==void 0&&l.published.length>0&&!l.published.includes(f))throw new C(400,`voice ${JSON.stringify(f)} is not one of the voices this model publishes \u2014 accepted voices: ${l.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new C(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${Ha} \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 C(400,"stream_format, when present, must be a string","stream_format");let h=a.speed;if(h!==void 0){if(typeof h!="number"||!Number.isFinite(h))throw new C(400,"speed, when present, must be a number","speed");if(h!==1)throw new C(400,`speed=${JSON.stringify(h)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let k=a.instructions;if(k!==void 0){if(typeof k!="string")throw new C(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new C(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 La(n.turn,n.clients,d);let m=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",m,m),!await ja(n.speechModels,d,e))return;if(typeof n.clients.openAudioOn!="function")throw new C(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 C(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 C(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(y){throw nt(y)}let g;try{g=await n.clients.openAudioOn(_)}catch(y){throw nt(y)}n.turn&&(n.turn.sessionId=g.sessionId);try{let y=await qa(n.clients,g,_,{model:d,text:u,...f!==void 0?{voice:f}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ia,returnBoundMs:n.turnReturnBoundMs??Ta},s);if(y===null||s())return;if(Ua(n.turn,y.pcm.byteLength),e.statusCode=200,f===void 0){let E=y.completed[Dt];typeof E=="string"&&e.setHeader(Ca,E)}p==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([Da(y.pcm.byteLength),y.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(y.pcm))}catch(y){throw nt(y)}}catch(i){if(i instanceof Le){Cn(e,new C(413,i.message));return}if(i instanceof C){Cn(e,i);return}throw i}}var ls="/v1/usage/requests",ds=1e4,Va=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ye=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},Ue=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var cs=1024*1024;function $n(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ye(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new ye(`"${e}" must be an array of uuid strings`);if(n.length>ds)throw new ye(`"${e}" carries ${n.length} ids; at most ${ds} 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"||!Va.test(s))throw new ye(`"${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 ps(t){return $n(t,"inference_ids")}function Bt(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 Ue(`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 Ue(`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 Jt=require("@urun-sh/core");var Ln="/partners/huggingface/v1/billing/requests";function Ja(t){return $n(t,"requestIds")}function Wa(t){return t>=200&&t<=399}function Ka(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Wa(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function fs(t,e){let n=Ja(t),r=await e(n);return Bt(r,n),Ka(r)}var za={"/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"};function Ya(t){return za[t]??null}var ys=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Xa(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Qa(t){return t==="surface"}function Za(t){let e=t?.ledgerFailureReason;return ys.includes(e)?e:"unknown"}var eu=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ms=["priced","unpriced"],tu={written:ms,already_written:ms,skipped:eu,failed:ys},mc=Object.entries(tu).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function nu(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function ru(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 ou=256,gs=4096,st=12e4,su=250,iu=8e3,it=[],hs=new Set,at=0,ot=!1;var au=new Set;function uu(){return at===0&&it.length===0}function du(){if(uu()){ot=!1;for(let t of[...au])t()}}function ws(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
29
|
-
`}function lu(t){ne(process.stdout,t)}function _s(t,e){try{t(e)}catch{}}function vs(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??lu,o=Ya(e.path);if(o===null)return;let s=c=>{try{n.observe(c)}catch{}},i=(c,l)=>{s({outcome:"skipped",reason:c}),_s(r,ws("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:c,detail:l}))};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:ru(e),completed_at:e.ts,billable_outcome:nu(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,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(it.length>=gs){i("queue_full",`${it.length} ledger writes are already waiting (capacity ${gs}, ${at} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}it.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),at<ou&&(at+=1,cu())}async function cu(){try{for(;;){let t=pu();if(t===void 0)return;hs.add(t);try{await fu(t)}finally{hs.delete(t)}}}finally{at-=1,du()}}function pu(){let t=Date.now();for(;;){let e=it.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<st)return e;Me(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 ${st}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 fu(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Me(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=Xa(o);if(s!==null){Me(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=Za(o),a=Date.now()-t.queuedAt;if(ot){Me(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(Qa(i)&&a<st){if(await gu(mu(t.attempts)),ot||Date.now()-t.queuedAt>=st){let u=Date.now()-t.queuedAt;Me(t,{outcome:"failed",reason:ot?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:ot?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${st}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}Me(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 mu(t){return Math.min(iu,su*2**Math.max(0,t-1))}function gu(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Me(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;_s(t.report,ws(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var Un=ve(require("crypto"),1),hu="urun-runtime-key-v1";function yu(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return Un.createHmac("sha256",t).update(`${hu}|${e}`,"ascii").digest("base64url")}var wu="decision-intake",qt=6e4,_u=qt/1e3+5,bs=3,Mn=15;function vu(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:wu,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=Un.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function bu(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function ku(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(qt)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new ie(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${qt}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!bu(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=Mn)}var Su=Mn*1e3,xu=Mn*500,Ru=256,jt=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new ie("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new ie(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let c=null;for(let l=0;l<bs;l++){let f=this.pick(d);if(f===null)throw new ie(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let p=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,h=vu(yu(this.opts.secret,p),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},_u);try{return{...await this.post(f,e,h),target:{...r,fnName:s}}}catch(k){if(k instanceof Ae)throw k;c=k;let m=this.replicas.get(f)??{outstanding:0,cooldownUntil:0};m.cooldownUntil=this.nowMs()+5e3,this.replicas.set(f,m);let _=this.presenceCache.get(u);_&&(_.rows=_.rows.filter(g=>g.address!==f),_.rows.length===0&&this.presenceCache.delete(u))}}throw new ie(`no runtime for app=${o} answered within ${bs} attempts: ${String(c instanceof Error?c.message:c)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>Su)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>xu&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=Ru;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return ku({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??qt)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new Ae(s.status,i);return{status:s.status,body:i,completed:Eu(i)}}finally{o.outstanding-=1}}};function Eu(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var Ae=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},ie=class extends Error{};function Fn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function H(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function V(t,e,n,r="invalid_request_error",o){H(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Bn(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);H(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ae(t,e,n,r){H(t,e,{type:"error",error:{type:n,message:r}})}function ue(t,e,n){if(e==="anthropic"){H(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}H(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Au=64*1024*1024,ut=class extends Error{};async function ks(t,e=Au){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new ut(`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 Rs(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 Gt(t){let e=Rs(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Ss(t){let e=Gt(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 Ou(t,e){let n=Rs(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Iu(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 Tu(t,e){let n=Iu(e);n&&(t.timing=n)}function fe(t,e){Ou(t,e),Tu(t,e)}async function Wt(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 Es(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 Pu(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 Ht=class extends Error{};function Cu(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 Ht(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function $u(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:Cu(n.role,n.content)})}return e}function Nn(t){return Te(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 Lu(t,e,n,r,o,s){let i=Ke(s.id),a=t.stream===!0;if(s.model=te(t),s.stream=a,await Wt(s,e,typeof t.model=="string"?t.model:void 0),a){let _;try{_=await Ye({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(g){if(g instanceof M){ue(r,"openai",g);return}if(g instanceof ee){V(r,g.status,g.message);return}throw g}Fn(r);for await(let g of _.events)g.type==="error"&&(s.streamError=!0),g.type==="response.completed"&&fe(s,g.response),r.write(`event: ${String(g.type??"message")}
|
|
30
|
-
data: ${JSON.stringify(
|
|
26
|
+
${Da(n)}\r
|
|
27
|
+
`),t.destroy()}function Fa(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
28
|
+
`}function ja(t){ie(process.stdout,t)}function qa(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Bn(t){return t.audioSession?.audio.sessionId??void 0}function jn(t,e){let n=new Zo.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==Fn)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=R("rtup"),d=qa(o),l=b=>{(e.log??ja)(Fa(b))};l({stage:"accept",conn:u,model:d}),s.resume();let p=new AbortController,m=null,c=b=>{m??=b,p.abort(new Error(m))},f=()=>c("client socket closed"),g=()=>c("client socket closed (half-close)"),_=b=>c(`client socket error: ${b.message}`);s.once("close",f),s.once("end",g),s.once("error",_);let y=()=>{s.removeListener("close",f),s.removeListener("end",g),s.removeListener("error",_)},h=b=>{l({stage:"close",conn:u,model:d,...b})},w=b=>{let k=b,v=k.session!=null&&typeof k.session.sendResponseCreate=="function",x=k.clients!=null&&typeof k.clients.createResponse=="function";if(!v&&!x)throw new Error("resolver returned a binding without an upstream turn seam (session.sendResponseCreate or clients.createResponse required) \u2014 refusing the upgrade LOUD");return new Promise((O,T)=>{n.handleUpgrade(o,s,i,$=>{try{new rt({ws:$,binding:b,onClosed:(K,Q)=>{h({while:"live",reason:Q.reason})}}),l({stage:"admit",conn:u,model:d,...Bn(b)===void 0?{}:{session:Bn(b)}}),O()}catch(K){T(K)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,p.signal).then(async b=>{if(p.signal.aborted){y();let k=Bn(b);try{await b.release?.()}catch(v){h({while:"queued",...k===void 0?{}:{session:k},reason:m??"client socket closed",release_failed:v instanceof Error?v.message:String(v)});return}h({while:"queued",...k===void 0?{}:{session:k},reason:m??"client socket closed",released:!0}),s.destroy();return}y(),await w(b)}).catch(b=>{let k=b instanceof Qo.SessionFailedError?$t(b):null,v=null;if(b!==null&&typeof b=="object"&&"status"in b){let T=b.status;typeof T=="number"&&(v=T)}let x=v??k?.status??502,O=b instanceof Error?b.message:String(b);h({while:"queued",...p.signal.aborted?{reason:m??"client socket closed"}:{reason:O,status:x}}),s.destroyed||Ba(s,x,O)}).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 ot=(t,e)=>Object.assign(new Error(e),{status:t});function Ga(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function Ha(t,e,n){if(!t.supportsAudio)throw ot(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let r;try{r=await t.supportsAudio(e)}catch(a){throw a instanceof U?ot(404,a.message):a}if(!r)throw ot(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 ot(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=await t.sessionHandle(e),s={audio:await t.openAudioOn(o,n)},i={clients:{createResponse:async a=>await t.createResponseOn(o,a)},voice:r,audioSession:s};return e!==void 0&&(i.model=e),i}function es(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 ot(401,"invalid local proxy api key")}return Ha(t,Ga(n),r)}}}var X=class extends Error{};async function Ft(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 jt(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 p of l)i.append(d,p);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 ts="/v1/images/generations",qt="/v1/images/edits";function ns(t){return t===ts||t===qt}var rs="/v1/images/models";async function os(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var L=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Va=16*1024*1024,ss=64*1024*1024;function is(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 st(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 as(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let p of o){if(p.type==="error"){let m=p.error??{};throw new L(502,`image upstream error: ${String(m.message??"upstream reported an error")}`)}if(p.type==="response.completed"){s=p.response??null;break}}if(s===null)throw new L(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 L(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(is(d)===null)throw new L(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function us(t){return t instanceof L?t:t instanceof U?new L(404,t.message):new L(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function ds(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 st(r,new L(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 cs(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 Wa={model:!0,prompt:!0,response_format:!0,n:!0};async function ps(t,e,n){let r=n.maxBodyBytes??ss;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${ts}`);let o;try{o=JSON.parse((await Ft(t,r)).toString("utf8")||"{}")}catch(p){throw p instanceof X?new L(413,p.message):new L(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new L(400,"request body must be a JSON object");let s=o;for(let p of Object.keys(s))if(!Wa[p])throw new L(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new L(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 L(400,"model must be a string","model");await os(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new L(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 L(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 ds(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let p=await as(n.clients,a,l,n.turn?oe(n.turn):void 0);ls(n.turn,p),cs(e,p)}catch(p){throw us(p)}}catch(o){if(o instanceof X){st(e,new L(413,o.message));return}if(o instanceof L){st(e,o);return}throw o}}var Ja={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function fs(t,e,n){let r=n.maxBodyBytes??ss,o=n.maxImagePartBytes??Va;try{if(t.method!=="POST")throw new L(405,`${String(t.method)} is not supported on ${qt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new L(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await jt(t,r)}catch(c){throw c instanceof X?new L(413,c.message):new L(400,String(c instanceof Error?c.message:c))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new L(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 L(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 L(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 c of i.keys())if(!Ja[c])throw new L(400,`form field "${c}" 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[]).`,c);let p=[];for(let c of["image","image[]"])for(let f of i.getAll(c)){if(!(f instanceof File))throw new L(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",c);if(f.size>o)throw new L(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,c);let g=new Uint8Array(await f.arrayBuffer()),_=is(g);if(_===null)throw new L(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",c);p.push({bytes:g,mime:_})}if(p.length===0)throw new L(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await ds(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:c,mime:f}of p)m.push({type:"input_image",image_url:`data:${f};base64,${Buffer.from(c).toString("base64")}`});try{let c=await as(n.clients,d,m,n.turn?oe(n.turn):void 0);ls(n.turn,c),cs(e,c)}catch(c){throw us(c)}}catch(s){if(s instanceof X){st(e,new L(413,s.message));return}if(s instanceof L){st(e,s);return}throw s}}var at="/v1/audio/speech";function ws(t){return t===at}var ms=4096,Ka=18e4,za=5e3,Ya=64*1024*1024,gs=8,hs=5,Ht="voice_applied",Xa="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 qn(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&t.setHeader("retry-after",String(e.retryAfterSeconds)),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var Vt=class extends P{constructor(e){super(502,e)}};async function Qa(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Za(t,e){t&&(t.outputUnits=e/(24e3*2))}var eu=2;function tu(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>eu)return!1;return!0}function nu(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 ys=new WeakMap,Gt=new WeakMap;function ru(t,e){let n=Gt.get(t)??0;if(n>=gs)throw new P(503,`this model's speech queue is full \u2014 ${gs} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${hs}s`,void 0,hs);Gt.set(t,n+1);let r=ys.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return ys.set(t,s),(async()=>{await r;try{return await e()}finally{Gt.set(t,(Gt.get(t)??1)-1),o()}})()}async function ou(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 Y))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 it(t){return t instanceof P?t:t instanceof U?new P(404,t.message):new P(502,`speech upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function su(t,e,n,r,o,s,i){return ru(e,async()=>{if(i?.()===!0)return null;let a=[],u=!1,d=0,l=!1,p=!1,m,c=new Promise(E=>{m=E}),f=()=>{l&&!p&&d>=o.quietRunFrames&&(p=!0,m())},g=e.onOutputAudio(E=>{let b=Buffer.from(E,"base64");if(b.byteLength===0)return;let k=tu(b);if(!u){if(k)return;u=!0}a.push(b),d=k?d+1:0,f()}),_=null,y,h,w;try{w=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let b=new Promise(O=>{h=setTimeout(O,s.capMs)}),k=!1;for(;;){let O=w.next(),T=await Promise.race([O,b]);if(T===void 0){k=!0,O.catch(()=>{});break}if(T.done)break;let $=T.value;if($.type==="error"){let K=$.error??{};throw await w.return?.(),new P(502,`speech upstream error: ${String(K.message??"upstream reported an error")}`)}if($.type==="response.completed"){_=$.response??null,l=!0,f(),await w.return?.();break}}if(clearTimeout(h),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(_===null)throw new P(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let v=!1;if(await Promise.race([c,new Promise(O=>{y=setTimeout(()=>{v=!0,O()},o.capMs)})]),y!==void 0&&clearTimeout(y),r.voice!==void 0){let O=_[Ht];if(typeof O!="string"||O!==r.voice){let T=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof O=="string"?`${Ht} ${JSON.stringify(O)}`:`no ${Ht} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw p?new Vt(T):new P(502,T)}}if(!u)throw new P(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(v&&!p&&d<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`);let x=d>0?a.slice(0,a.length-d):a;return{pcm:Buffer.concat(x),completed:_}}catch(E){throw E instanceof Vt||await ou(t,n,w,s.returnBoundMs),E}finally{y!==void 0&&clearTimeout(y),h!==void 0&&clearTimeout(h),g()}})}async function iu(t,e,n){let r;try{r=await t(e)}catch(o){throw it(o)}return r?!0:(qn(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 au={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},uu="wav, pcm";async function _s(t,e,n){let r=n.maxBodyBytes??Ya,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 ${at}`);let i;try{i=JSON.parse((await Ft(t,r)).toString("utf8")||"{}")}catch(w){throw w instanceof X?new P(413,w.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 w of Object.keys(a))if(!au[w])throw new P(400,`request field "${w}" 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.`,w);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>ms)throw new P(400,`input is ${u.length} chars \u2014 over the ${ms}-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 ${at} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(w){throw it(w)}if(p.defect!==null)throw new P(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof l=="string"?l:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new P(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let c=a.response_format??"wav";if(c!=="wav"&&c!=="pcm")throw new P(400,`response_format ${JSON.stringify(c)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${uu} \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 f=a.speed;if(f!==void 0){if(typeof f!="number"||!Number.isFinite(f))throw new P(400,"speed, when present, must be a number","speed");if(f!==1)throw new P(400,`speed=${JSON.stringify(f)} 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 g=a.instructions;if(g!==void 0){if(typeof g!="string")throw new P(400,"instructions, when present, must be a string","instructions");if(g.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 Qa(n.turn,n.clients,d);let _=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",_,_),!await iu(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(w){throw it(w)}let h;try{h=await n.clients.openAudioOn(y)}catch(w){throw it(w)}n.turn&&(n.turn.sessionId=h.sessionId);try{let w=await su(n.clients,h,y,{model:d,text:u,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ka,returnBoundMs:n.turnReturnBoundMs??za},s);if(w===null||s())return;if(Za(n.turn,w.pcm.byteLength),e.statusCode=200,m===void 0){let E=w.completed[Ht];typeof E=="string"&&e.setHeader(Xa,E)}c==="wav"?(e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([nu(w.pcm.byteLength),w.pcm]))):(e.setHeader("content-type","audio/pcm"),e.end(w.pcm))}catch(w){throw it(w)}}catch(i){if(i instanceof X){qn(e,new P(413,i.message));return}if(i instanceof P){qn(e,i);return}throw i}}var Wt="/v1/audio/transcriptions";function vs(t){return t===Wt}var bs="/v1/audio/models",du=16*1024*1024,lu=64*1024*1024,F=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Gn(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 ks(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 cu(t){if(!ks(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 pu(t,e,n){if(t){if(t.model=te({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function fu(t,e){t&&(t.outputUnits=e.seconds)}async function mu(t,e,n,r,o){let s=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),i=[],a=null;for await(let u of s){if(i.push(u),u.type==="error"){let d=u.error??{},l=typeof d.type=="string"?d.type:"upstream_error",p=String(d.message??"upstream reported an error");throw new F(l==="invalid_request_error"?400:502,`transcription upstream error: ${p}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new F(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return De(i,a)}function Ss(t){return t instanceof F?t:t instanceof U?new F(404,t.message):new F(502,`transcription upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function gu(t,e,n){let r;try{r=await t(e)}catch(o){throw Ss(o)}return r?!0:(Gn(n,new F(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var hu=new Set(["file","model","language","response_format"]);async function xs(t,e,n){let r=n.maxBodyBytes??lu,o=n.maxAudioPartBytes??du;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${Wt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the transcriptions endpoint consumes multipart/form-data, got ${s||"none"}`);let i;try{i=await jt(t,r)}catch(y){throw y instanceof X?new F(413,y.message):new F(400,String(y instanceof Error?y.message:y))}let a=new Map;for(let y of i.keys()){if(!hu.has(y))throw new F(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);a.set(y,(a.get(y)??0)+1)}for(let[y,h]of a)if(h>1)throw new F(400,`form field "${y}" 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`,y);let u=i.get("model");if(u!==null&&typeof u!="string")throw new F(400,"model must be a string field","model");let d=u===null?void 0:u,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new F(400,"language, when present, must be a non-empty string","language");let p=l===null?void 0:l,m=i.get("response_format")??"json";if(m!=="json")throw new F(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 c=i.get("file");if(!(c instanceof File))throw new F(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(c.size>o)throw new F(413,`file part exceeds the ${o}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let f=new Uint8Array(await c.arrayBuffer());if(!ks(f))throw new F(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let g=cu(f);if(g===null)throw new F(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await pu(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",f.length,f.length),!await gu(n.transcriptionModels,d,e))return;let _=[{type:"input_audio",input_audio:{data:Buffer.from(f).toString("base64"),format:"wav"}}];try{let y=await mu(n.clients,d,_,p,n.turn?oe(n.turn):void 0);fu(n.turn,g),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:y}))}catch(y){throw Ss(y)}}catch(s){if(s instanceof X){Gn(e,new F(413,s.message));return}if(s instanceof F){Gn(e,s);return}throw s}}var Es="/v1/usage/requests",Rs=1e4,yu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Se=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 As=1024*1024;function Hn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Se(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Se(`"${e}" must be an array of uuid strings`);if(n.length>Rs)throw new Se(`"${e}" carries ${n.length} ids; at most ${Rs} 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"||!yu.test(s))throw new Se(`"${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 Os(t){return Hn(t,"inference_ids")}function Jt(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 Zt=require("@urun-sh/core");var Vn="/partners/huggingface/v1/billing/requests";function wu(t){return Hn(t,"requestIds")}function _u(t){return t>=200&&t<=399}function vu(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&_u(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Is(t,e){let n=wu(t),r=await e(n);return Jt(r,n),vu(r)}var bu={"/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 ku(t){return bu[t]??null}var $s=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Su(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function xu(t){return t==="surface"}function Ru(t){let e=t?.ledgerFailureReason;return $s.includes(e)?e:"unknown"}var Eu=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Ts=["priced","unpriced"],Au={written:Ts,already_written:Ts,skipped:Eu,failed:$s},Xc=Object.entries(Au).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ou(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Iu(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 Tu=256,Ps=4096,dt=12e4,Pu=250,Cu=8e3,lt=[],Cs=new Set,ct=0,ut=!1;var $u=new Set;function Lu(){return ct===0&<.length===0}function Mu(){if(Lu()){ut=!1;for(let t of[...$u])t()}}function Ls(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
29
|
+
`}function Uu(t){ie(process.stdout,t)}function Ms(t,e){try{t(e)}catch{}}function Us(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Uu,o=ku(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,p)=>{s({outcome:"skipped",reason:l}),Ms(r,Ls("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:p}))};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:Iu(e),completed_at:e.ts,billable_outcome:Ou(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,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(lt.length>=Ps){i("queue_full",`${lt.length} ledger writes are already waiting (capacity ${Ps}, ${ct} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}lt.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),ct<Tu&&(ct+=1,Nu())}async function Nu(){try{for(;;){let t=Du();if(t===void 0)return;Cs.add(t);try{await Bu(t)}finally{Cs.delete(t)}}}finally{ct-=1,Mu()}}function Du(){let t=Date.now();for(;;){let e=lt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<dt)return e;Ge(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 ${dt}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 Bu(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Ge(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=Su(o);if(s!==null){Ge(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=Ru(o),a=Date.now()-t.queuedAt;if(ut){Ge(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(xu(i)&&a<dt){if(await ju(Fu(t.attempts)),ut||Date.now()-t.queuedAt>=dt){let u=Date.now()-t.queuedAt;Ge(t,{outcome:"failed",reason:ut?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:ut?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${dt}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}Ge(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 Fu(t){return Math.min(Cu,Pu*2**Math.max(0,t-1))}function ju(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Ge(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;Ms(t.report,Ls(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var Wn=xe(require("crypto"),1),qu="urun-runtime-key-v1";function Gu(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return Wn.createHmac("sha256",t).update(`${qu}|${e}`,"ascii").digest("base64url")}var Hu="decision-intake",Kt=6e4,Vu=Kt/1e3+5,Ns=3,Jn=15;function Wu(t,e,n=60,r=Math.floor(Date.now()/1e3)){if(!t)throw new Error("cannot mint a decision token without a secret");let o=d=>Buffer.from(d).toString("base64url"),s=o(JSON.stringify({alg:"HS256",typ:"JWT"})),i={tenant:e.tenant,app:e.app,fn:e.fn,...e.provider?{provider:e.provider}:{},session_id:"decision-intake",sub:`machine:${e.tenant}/${e.app}/${e.fn}`,aud:Hu,iat:r,exp:r+Math.max(1,n)},a=o(JSON.stringify(i)),u=Wn.createHmac("sha256",t).update(`${s}.${a}`,"ascii").digest("base64url");return`${s}.${a}.${u}`}function Ju(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.runtime_id=="string"&&e.runtime_id!==""&&typeof e.ready=="boolean"&&typeof e.address=="string"&&e.address!==""&&typeof e.last_seen=="string"&&!Number.isNaN(Date.parse(e.last_seen))}async function Ku(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/runtimes?app=${encodeURIComponent(t.app)}&fn=${encodeURIComponent(t.fn)}`,r;try{r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"},signal:AbortSignal.timeout(Kt)})}catch(u){throw(u instanceof Error?u.name:void 0)==="TimeoutError"?new de(`runtime presence read for (app=${t.app} fn=${t.fn}) timed out after ${Kt}ms \u2014 the control plane is not answering; no replica can be discovered`):u}if(!r.ok)throw new Error(`runtime presence read failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.runtimes))throw new Error(`runtime presence read returned no "runtimes" array (GET ${n})`);let s=[],i=[];for(let u of o.runtimes){if(!Ju(u)){s.push(JSON.stringify(u));continue}i.push(u)}if(s.length>0)throw new Error(`runtime presence read for (app=${t.app} fn=${t.fn}) returned ${s.length} malformed presence row(s) \u2014 the control plane's runtimes schema drifted (runtime_id/address/ready/last_seen are all required): ${s.slice(0,3).join("; ")}`);let a=(t.nowMs??Date.now())/1e3;return i.filter(u=>u.ready===!0&&a-Date.parse(u.last_seen)/1e3<=Jn)}var zu=Jn*1e3,Yu=Jn*500,Xu=256,zt=class{constructor(e){this.opts=e;this.nowMs=e.nowMs??Date.now}opts;replicas=new Map;nowMs;presenceCache=new Map;get enabled(){return this.opts.secret!==""}async targetFor(e){let n=await this.opts.targetFor(e);return n.sharedApp===!0&&this.opts.shared===void 0?null:n}async decide(e,n){let r=await this.targetFor(n);if(r===null)throw new de("the shared-endpoint lane keeps the session dial \u2014 the stateless direct path serves caller-org functions");let o=r.appSlug,s=r.fnName??this.opts.fnName,i=r.sharedApp===!0,a=i?this.opts.shared.apiKey:this.opts.apiKey,u=`${a}\0${o}\0${s}`,d=await this.ensureRows(u,a,o,s);if(d.length===0)throw new de(`no ready runtime for (org app=${o} fn=${s}) \u2014 nothing is serving decisions right now`);let l=null;for(let p=0;p<Ns;p++){let m=this.pick(d);if(m===null)throw new de(`every discovered runtime for app=${o} failed at the transport layer \u2014 no replica took the decision`);let c=i&&r.sharedOrgId?r.sharedOrgId:this.opts.orgId,f=Wu(Gu(this.opts.secret,c),{tenant:this.opts.orgId,app:o,fn:s,...i&&r.sharedOrgId?{provider:r.sharedOrgId}:{}},Vu);try{return{...await this.post(m,e,f),target:{...r,fnName:s}}}catch(g){if(g instanceof Ce)throw g;l=g;let _=this.replicas.get(m)??{outstanding:0,cooldownUntil:0};_.cooldownUntil=this.nowMs()+5e3,this.replicas.set(m,_);let y=this.presenceCache.get(u);y&&(y.rows=y.rows.filter(h=>h.address!==m),y.rows.length===0&&this.presenceCache.delete(u))}}throw new de(`no runtime for app=${o} answered within ${Ns} attempts: ${String(l instanceof Error?l.message:l)}`)}async ensureRows(e,n,r,o){let s=this.presenceCache.get(e);if(s)if(this.nowMs()-s.fetchedAtMs>zu)this.presenceCache.delete(e);else return this.nowMs()-s.fetchedAtMs>Yu&&!s.refreshing&&(s.refreshing=!0,this.readPresence(n,r,o).then(a=>{this.presenceCache.set(e,{rows:a,fetchedAtMs:this.nowMs(),refreshing:!1})}).catch(()=>{s.refreshing=!1})),s.rows;let i=await this.readPresence(n,r,o);for(;this.presenceCache.size>=Xu;){let a=this.presenceCache.keys().next();if(a.done)break;this.presenceCache.delete(a.value)}return this.presenceCache.set(e,{rows:i,fetchedAtMs:this.nowMs(),refreshing:!1}),i}readPresence(e,n,r){return Ku({apiUrl:this.opts.apiUrl,apiKey:e,app:n,fn:r,fetchImpl:this.opts.fetchImpl,nowMs:this.nowMs()})}pick(e){let n=this.nowMs(),r=null,o=1/0;for(let s of e){let i=this.replicas.get(s.address);if(i!==void 0&&i.cooldownUntil>n)continue;let a=i?.outstanding??0;a<o&&(r=s.address,o=a)}return r}async post(e,n,r){let o=this.replicas.get(e)??{outstanding:0,cooldownUntil:0};o.outstanding+=1,this.replicas.set(e,o);try{let s=await fetch(`${e.replace(/\/+$/,"")}/v1/decision`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.opts.timeoutMs??Kt)}),i=null;try{i=await s.json()}catch{i={error:{message:`runtime answered ${s.status} with a non-JSON body`,type:"upstream_error"}}}if(s.status>=500)throw new Error(`runtime ${e} answered ${s.status}`);if(s.status>=400)throw new Ce(s.status,i);return{status:s.status,body:i,completed:Qu(i)}}finally{o.outstanding-=1}}};function Qu(t){if(t===null||typeof t!="object")return null;let e=t,n=e.usage;if(n===null||typeof n!="object")return e;let r=n;return{...e,usage:{input_tokens:r.prompt_tokens??r.input_tokens,output_tokens:r.completion_tokens??r.output_tokens}}}var Ce=class extends Error{constructor(n,r){super(`runtime answered ${n}`);this.status=n;this.body=r}status;body},de=class extends Error{};function Yn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function H(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function J(t,e,n,r="invalid_request_error",o){H(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Xn(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);H(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function le(t,e,n,r){H(t,e,{type:"error",error:{type:n,message:r}})}function ce(t,e,n){if(e==="anthropic"){H(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}H(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Zu=64*1024*1024,pt=class extends Error{};async function Ds(t,e=Zu){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new pt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function He(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 js(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 Yt(t){let e=js(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Bs(t){let e=Yt(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 ed(t,e){let n=js(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=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 nd(t,e){let n=td(e);n&&(t.timing=n)}function ye(t,e){ed(t,e),nd(t,e)}async function en(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 qs(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 rd(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 Xt=class extends Error{};function od(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 Xt(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function sd(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:od(n.role,n.content)})}return e}function Kn(t){return Ue(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 id(t,e,n,r,o,s){let i=Ze(s.id),a=t.stream===!0;if(s.model=te(t),s.stream=a,await en(s,e,typeof t.model=="string"?t.model:void 0),a){let y;try{y=await tt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(h){if(h instanceof U){ce(r,"openai",h);return}if(h instanceof se){J(r,h.status,h.message);return}throw h}Yn(r);for await(let h of y.events)h.type==="error"&&(s.streamError=!0),h.type==="response.completed"&&ye(s,h.response),r.write(`event: ${String(h.type??"message")}
|
|
30
|
+
data: ${JSON.stringify(h)}
|
|
31
31
|
|
|
32
32
|
`);r.write(`data: [DONE]
|
|
33
33
|
|
|
34
|
-
`),r.end();return}let u;try{u=
|
|
34
|
+
`),r.end();return}let u;try{u=Be(n,t)}catch(y){if(y instanceof se){J(r,y.status,y.message);return}throw y}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,l=te(t);o.model(l);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await kn(e,t,u,!1,oe(s))}catch(y){if(y instanceof U){ce(r,"openai",y);return}if(y instanceof se){J(r,y.status,y.message);return}throw y}let c=[],f=null;for await(let y of o.track(m,l,s)){if(c.push(y),y.type==="error"){Xn(r,y);return}y.type==="response.completed"&&(f=y.response)}if(f==null){J(r,502,"upstream produced no response.completed event","upstream_error");return}ye(s,f);let g=De(c,f),_=Pe(p,Ue(f).length,g);if(_){J(r,502,Te(l,_),"upstream_error");return}d&&n.remember(i,u,bn(f,g),d),H(r,200,{...f,id:i})}async function ad(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){J(n,400,"chat/completions requires a messages array");return}let i=String(t.model??"urun"),a=ho(o.id),u;try{u=sd(s)}catch(v){if(v instanceof Xt){J(n,400,v.message);return}throw v}let d=te(t);r.model(d),o.model=d,o.stream=t.stream===!0,await en(o,e,typeof t.model=="string"?t.model:void 0);let l=Array.isArray(t.tools)&&t.tools.length>0;if(t.stream!==!0&&e.stateless?.enabled){let v;try{v=await e.stateless.targetFor(typeof t.model=="string"?t.model:void 0)}catch(x){if(x instanceof U){ce(n,"openai",x);return}throw x}if(v!==null){try{let x=await e.stateless.decide(t,typeof t.model=="string"?t.model:void 0);o.catalog=ze(x.target),ye(o,x.completed),H(n,200,{...x.body,id:a})}catch(x){if(x instanceof U){ce(n,"openai",x);return}if(x instanceof Ce){H(n,x.status,x.body);return}if(x instanceof de){J(n,503,x.message,"upstream_error");return}throw x}return}}let p;try{p=await e.createResponse({model:t.model,input:u,stream:!0,tools:rd(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},oe(o))}catch(v){if(v instanceof U){ce(n,"openai",v);return}throw v}if(t.stream===!0){Yn(n);let v=[],x=new be,O="";n.write(`data: ${JSON.stringify(He(a,i,{role:"assistant"},null))}
|
|
35
35
|
|
|
36
|
-
`);for await(let
|
|
36
|
+
`);for await(let z of r.track(p,d,o)){v.push(z);let Z=Ne(z);if(z.type==="response.output_text.delta"&&typeof z.delta=="string")O+=z.delta,n.write(`data: ${JSON.stringify(He(a,i,{content:z.delta},null))}
|
|
37
37
|
|
|
38
|
-
`);else if(
|
|
38
|
+
`);else if(z.type==="response.reasoning_text.delta"&&typeof z.delta=="string")n.write(`data: ${JSON.stringify(He(a,i,{reasoning_content:z.delta},null))}
|
|
39
39
|
|
|
40
|
-
`);else if(
|
|
40
|
+
`);else if(Z){let{call:pe,isNew:q}=x.add(Z),fe=q?{index:Z.tool_index,id:pe.id??`call_${Z.tool_index}`,type:"function",function:{name:pe.name??"",arguments:Z.delta}}:{index:Z.tool_index,function:{arguments:Z.delta}};n.write(`data: ${JSON.stringify(He(a,i,{tool_calls:[fe]},null))}
|
|
41
41
|
|
|
42
|
-
`)}else if(
|
|
42
|
+
`)}else if(z.type==="error"){o.streamError=!0,n.write(`data: ${JSON.stringify({error:z})}
|
|
43
43
|
|
|
44
|
-
`),n.end();return}}let
|
|
44
|
+
`),n.end();return}}let T=Kn(ue(v)),$=Pe(l,x.size+T.length,O);if($){o.streamError=!0,n.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Te(d,$)}})}
|
|
45
45
|
|
|
46
|
-
`),n.end();return}x.size===0&&
|
|
46
|
+
`),n.end();return}x.size===0&&T.length>0&&n.write(`data: ${JSON.stringify(He(a,i,{tool_calls:T},null))}
|
|
47
47
|
|
|
48
|
-
`);let
|
|
48
|
+
`);let K=x.size>0||T.length>0;n.write(`data: ${JSON.stringify(He(a,i,{},K?"tool_calls":"stop"))}
|
|
49
49
|
|
|
50
|
-
`);let
|
|
50
|
+
`);let Q=Yt(ue(v));ye(o,ue(v)),Q&&n.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:Bs(ue(v))})}
|
|
51
51
|
|
|
52
52
|
`),n.write(`data: [DONE]
|
|
53
53
|
|
|
54
|
-
`),n.end();return}let
|
|
55
|
-
data: ${JSON.stringify({type:
|
|
54
|
+
`),n.end();return}let m="",c="",f=[],g=new be;for await(let v of r.track(p,d,o)){f.push(v),v.type==="response.output_text.delta"&&typeof v.delta=="string"&&(m+=v.delta),v.type==="response.reasoning_text.delta"&&typeof v.delta=="string"&&(c+=v.delta);let x=Ne(v);if(x&&g.add(x),v.type==="error"){Xn(n,v);return}}let _=ue(f);ye(o,_);let y=Kn(_),h=y.length>0?y:Kn({output:g.items()}),w=Pe(l,h.length,m);if(w){J(n,502,Te(d,w),"upstream_error");return}let E=h.map(({index:v,...x})=>x),b={role:"assistant",content:m||null},k=c||qs(_);k&&(b.reasoning_content=k),E.length>0&&(b.tool_calls=E),H(n,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:b,finish_reason:E.length>0?"tool_calls":"stop"}],usage:Bs(_)})}var ud="reflex-latest";async function dd(t,e,n,r,o){if(t===null||typeof t!="object"||Array.isArray(t)){J(n,400,"systemone requires a JSON object body");return}delete t.key;let s=typeof t.model=="string"&&t.model?t.model:ud,i=te({model:s});if(o.model=i,o.stream=!1,t.state===void 0||t.state===null){J(n,400,"systemone requires a state (string or JSON structure)");return}let a=t.questions;if(a===null||typeof a!="object"||Array.isArray(a)||Object.keys(a).length===0){J(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){J(n,400,"systemone media, when present, must be an array");return}if(r.model(i),await en(o,e,s),e.stateless?.enabled){let c;try{c=await e.stateless.targetFor(s)}catch(f){if(f instanceof U){ce(n,"openai",f);return}throw f}if(c!==null){try{let f=await e.stateless.decide(t,s);o.catalog=ze(f.target),ye(o,f.completed),H(n,200,f.body)}catch(f){if(f instanceof U){ce(n,"openai",f);return}if(f instanceof Ce){H(n,f.status,f.body);return}if(f instanceof de){J(n,503,f.message,"upstream_error");return}throw f}return}}let u;try{u=await e.createResponse({model:s,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},oe(o))}catch(c){if(c instanceof U){ce(n,"openai",c);return}throw c}let d=[];try{for await(let c of r.track(u,i,o))if(d.push(c),c.type==="error"){Xn(n,c);return}}catch(c){if(c instanceof U){ce(n,"openai",c);return}throw c}let l=ue(d);if(l==null){J(n,502,"upstream produced no response.completed event","upstream_error");return}ye(o,l);let p=De(d,l),m;try{m=JSON.parse(p)}catch{J(n,502,"systemone answer was not valid JSON","upstream_error");return}if(m===null||typeof m!="object"||Array.isArray(m)){J(n,502,"systemone answer was not a JSON object","upstream_error");return}H(n,200,m)}function ld(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var ft=class extends Error{};function Qt(t){return new ft(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function cd(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 pd(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 ft(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function fd(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Qt(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Qt(`tool_result > ${r}`);e+=String(n.text??"")}return e}function md(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 Qt(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:fd(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Qt(a)}}return s(),r}function zn(t){return Ue(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 gd(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){le(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){le(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){le(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(v=>typeof v!="string"))){le(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=yo(o.id),u=[],d;try{t.system&&u.push({role:"system",content:ld(t.system)});for(let v of s)u.push(...md(v));d=pd(t.tool_choice)}catch(v){if(v instanceof ft){le(n,400,"invalid_request_error",v.message);return}throw v}let l=te(t);r.model(l),o.model=l,o.stream=t.stream===!0,await en(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:u,stream:!0,tools:cd(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},oe(o))}catch(v){if(v instanceof U){ce(n,"anthropic",v);return}throw v}let c=(v,x)=>{n.destroyed||n.write(`event: ${v}
|
|
55
|
+
data: ${JSON.stringify({type:v,...x})}
|
|
56
56
|
|
|
57
|
-
`)};if(t.stream===!0){let
|
|
58
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:
|
|
57
|
+
`)};if(t.stream===!0){let v=r.track(m,l,o);Yn(n),c("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let x=0,O="",T=0,$="none",K=()=>$,Q=-1,z=-1,Z=new be,pe=[],q=()=>{$!=="none"&&($="none",c("content_block_stop",{index:Q}))},fe=(B,ee)=>{q(),$=B,Q=T++,c("content_block_start",{index:Q,content_block:ee})};for await(let B of v){if(n.destroyed)break;pe.push(B);let ee=Ne(B);if(B.type==="response.reasoning_text.delta"&&typeof B.delta=="string")K()!=="thinking"&&fe("thinking",{type:"thinking",thinking:""}),c("content_block_delta",{index:Q,delta:{type:"thinking_delta",thinking:B.delta}});else if(B.type==="response.output_text.delta"&&typeof B.delta=="string")K()!=="text"&&fe("text",{type:"text",text:""}),x+=1,O+=B.delta,c("content_block_delta",{index:Q,delta:{type:"text_delta",text:B.delta}});else if(ee){let{call:_e}=Z.add(ee);(K()!=="tool"||ee.tool_index!==z)&&(z=ee.tool_index,fe("tool",{type:"tool_use",id:_e.id??`call_${ee.tool_index}`,name:_e.name??"",input:{}})),ee.delta&&c("content_block_delta",{index:Q,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(B.type==="error"){o.streamError=!0,c("error",{error:{type:"api_error",message:JSON.stringify(B)}}),n.end();return}}if(n.destroyed)return;let we=ue(pe),mt=Ue(we),C=Pe(p,Z.size+mt.length,O);if(C){o.streamError=!0,c("error",{error:{type:"api_error",message:Te(l,C)}}),n.end();return}q();let N=[];if(Z.size===0)try{N=zn(we)}catch(B){o.streamError=!0,c("error",{error:{type:"api_error",message:String(B instanceof Error?B.message:B)}}),n.end();return}T===0&&N.length===0&&(fe("text",{type:"text",text:""}),q()),N.forEach(B=>{let ee=T++;c("content_block_start",{index:ee,content_block:{...B,input:{}}}),c("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(B.input??{})}}),c("content_block_stop",{index:ee})});let W=Z.size>0||N.length>0,me=Yt(we);ye(o,we),c("message_delta",{delta:{stop_reason:W?"tool_use":"end_turn"},usage:me?{input_tokens:me.input_tokens,output_tokens:me.output_tokens}:{output_tokens:x}}),c("message_stop",{}),n.end();return}let f="",g="",_=[],y=new be;for await(let v of r.track(m,l,o)){_.push(v),v.type==="response.output_text.delta"&&typeof v.delta=="string"&&(f+=v.delta),v.type==="response.reasoning_text.delta"&&typeof v.delta=="string"&&(g+=v.delta);let x=Ne(v);if(x&&y.add(x),v.type==="error"){let O=v.error,T=O?.type==="invalid_request_error";le(n,T?400:502,T?"invalid_request_error":"api_error",O?.message??JSON.stringify(v));return}if(n.destroyed)break}if(n.destroyed)return;let h=ue(_);ye(o,h);let w;try{w=zn(h),w.length===0&&y.size>0&&(w=zn({output:y.items()}))}catch(v){le(n,502,"api_error",String(v instanceof Error?v.message:v));return}let E=Pe(p,w.length,f);if(E){le(n,502,"api_error",Te(l,E));return}let b=[],k=g||qs(h);k&&b.push({type:"thinking",thinking:k}),(f||w.length===0)&&b.push({type:"text",text:f}),b.push(...w),H(n,200,{id:a,type:"message",role:"assistant",content:b,model:i,stop_reason:w.length>0?"tool_use":"end_turn",usage:Yt(h)??{input_tokens:0,output_tokens:0}})}function hd(t){ie(process.stdout,t)}function yd(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??hd,a=t.observe,u=new Oe;return(d,l)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),c=(h,w,E,b,k)=>m?le(l,h,b,w):J(l,h,w,E,k),f=vn(p.pathname),g=p.pathname.startsWith("/partners/"),_=f||g?{id:Qe(),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,sessionId:null,timing:null}:null;_&&(l.setHeader(mo,_.id),l.once("close",()=>{let h=wo({turn:_,method:d.method??"",path:p.pathname,res:l});i(_o(h)),a?.(h),Us({record:h,ledger:t.ledger??null,req:d})}));let y=()=>go(p.pathname,_);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){H(l,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){H(l,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){c(401,"invalid local proxy api key","authentication_error","authentication_error");return}let h=p.pathname===Es?"canonical":p.pathname===Vn?"huggingface":null;if(h){if(d.method!=="POST"){c(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let k=t.usage;if(!k){c(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let v=k.authorize(d),x;try{x=await Ds(d,As)}catch($){if($ instanceof pt){c(413,$.message,"request_too_large","request_too_large");return}c(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let O=$=>k.lookup(v,$),T;try{if(h==="canonical"){let $=Os(x),K=await O($);Jt(K,$),T={requests:K}}else T=await Is(x,O)}catch($){if($ instanceof Se){c($.status,$.message,"invalid_request_error","invalid_request_error");return}throw $}H(l,200,T);return}if(p.pathname.startsWith("/partners/")){c(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Vn}`,"invalid_request_error","not_found_error");return}let w=await s(d);if(_&&(_.org=w.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){if(!w.openRouterModels){c(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}H(l,200,await w.openRouterModels());return}H(l,200,await w.listModels());return}if(d.method==="GET"&&p.pathname===rs){if(!w.listImageModels){c(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}H(l,200,await w.listImageModels());return}if(ns(p.pathname)){if(!w.supportsImages){c(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let k={clients:w,imageModels:w.supportsImages,stats:u,turn:y()};p.pathname===qt?await fs(d,l,k):await ps(d,l,k);return}if(d.method==="GET"&&p.pathname===bs){if(!w.listSpeechToTextModels){c(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}H(l,200,await w.listSpeechToTextModels());return}if(vs(p.pathname)){if(!w.supportsTranscription){c(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Wt}`,"not_implemented","not_implemented_error");return}let k={clients:w,transcriptionModels:w.supportsTranscription,stats:u,turn:y()};await xs(d,l,k);return}if(ws(p.pathname)){if(!w.supportsSpeech){c(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${at}`,"not_implemented","not_implemented_error");return}let k={clients:w,speechModels:w.supportsSpeech,stats:u,turn:y()};await _s(d,l,k);return}if(d.method!=="POST"){c(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let E;try{E=await Ds(d)}catch(k){if(k instanceof pt){c(413,k.message,"request_too_large","request_too_large");return}c(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=Buffer.byteLength(JSON.stringify(E));if(p.pathname==="/v1/responses"){u.request("responses",b,b),await id(E,w,et(w),l,u,y());return}if(p.pathname==="/v1/chat/completions"){u.request("chat_completions",b,b),await ad(E,w,l,u,y());return}if(p.pathname==="/v1/systemone"){u.request("systemone",b,b),await dd(E,w,l,u,y());return}if(p.pathname==="/v1/messages"){u.request("messages",b,b),await gd(E,w,l,u,y());return}if(p.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",b,b),le(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}c(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(h=>{let w=String(h instanceof Error?h.message:h);if(!l.headersSent){let E=o?.(h)??null;if(E){c(E.status,w,E.openaiType,E.anthropicType);return}if(h instanceof Zt.SessionAllocationError){let b=Ct(h.code);if(b){let k=h.retryAfterSeconds??(b.status===429?30:void 0);k!==void 0&&l.setHeader("Retry-After",String(k)),c(b.status,En(b,h.code??void 0),b.openaiType,b.anthropicType,b.code);return}}if(h instanceof Zt.SessionFailedError){let b=$t(h);if(b){let k=b.status===429?30:void 0;k!==void 0&&l.setHeader("Retry-After",String(k)),c(b.status,En(b,h.status.sessionId?`session ${h.status.sessionId}`:void 0),b.openaiType,b.anthropicType,b.code);return}}if(h instanceof qe){c(502,w,"upstream_error","api_error");return}c(500,w,"proxy_error","api_error","proxy_error");return}_&&(_.streamError=!0),l.destroyed||(m?l.write(`event: error
|
|
58
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:w}})}
|
|
59
59
|
|
|
60
|
-
`):
|
|
60
|
+
`):l.write(`data: ${JSON.stringify({error:{message:w,type:"upstream_error"}})}
|
|
61
61
|
|
|
62
|
-
`)),
|
|
63
|
-
`),null):{catalogUrl:r,anonKey:o}}function
|
|
64
|
-
`),new
|
|
65
|
-
`),o(127)})})}function
|
|
66
|
-
`)}async function
|
|
67
|
-
`)
|
|
68
|
-
`),0):(
|
|
69
|
-
`),1)}if(n==="proxy"){let o=e??
|
|
70
|
-
`):a.reason&&
|
|
71
|
-
`);let
|
|
72
|
-
`)}),
|
|
73
|
-
`),
|
|
74
|
-
`),
|
|
75
|
-
`),
|
|
76
|
-
`),
|
|
62
|
+
`)),l.end()})}}function Gs(t){let{clients:e,apiKey:n}=t,r=(0,Fs.createServer)(yd(t)),o=xo(r,{clients:e,apiKey:n,statusOf:t.statusOf}),s=jn(r,{resolver:es(e,n)}),i=r.close.bind(r);return r.close=(a=>(o.close(),s(),i(a))),po(r,{clients:e,apiKey:n}),r}var tn=require("@urun-sh/core/internal");var wd={ensureWebRTC:tn.ensureNodeWebRTC,webrtcUnavailableReason:tn.nodeWebRTCUnavailableReason,audioBackend:_t};async function Hs(t=wd){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 _d(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?Lt(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
|
|
63
|
+
`),null):{catalogUrl:r,anonKey:o}}function vd(t){return Gr({baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:_d(M.default.env,e=>M.default.stderr.write(e)),statelessDirect:Ks(t)})}function Ks(t){return t.decisionSecret!==""&&t.auth.lane==="api-key"}function bd(t,e){if(Ks(t))return M.default.stderr.write(`urun compat: stateless direct path ENABLED (POST /v1/decision answered by the serving pods)
|
|
64
|
+
`),new zt({targetFor:n=>e.targetFor(n),apiUrl:t.apiUrl,fnName:t.fnName,apiKey:t.auth.apiKey,orgId:t.orgId,secret:t.decisionSecret})}async function Vs(t,e,n){let r=(0,Qn.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{M.default.stderr.write(`failed to launch ${t}: ${String(s)}
|
|
65
|
+
`),o(127)})})}function Ws(){return Uo(M.default.env,I,ae.existsSync)}function zs(t){for(let[e,n]of Object.entries(In(t)))M.default.stdout.write(`export ${e}=${n}
|
|
66
|
+
`)}async function Js(t,e){let n=Fe(M.default.env),r=e?Pn(n):void 0,o=vd(n),s=null,i=d=>{if(s===null){let l=a.address();if(l===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");s=$n(l.port),(0,ae.mkdirSync)(Zn.default.dirname(s),{recursive:!0})}(0,ae.appendFileSync)(s,d)},a=Gs({clients:Hr(o,void 0,void 0,bd(n,o)),identity:r,...e?{requestLog:i}:{}});try{await new Promise((d,l)=>{a.once("error",l),a.listen(t,"127.0.0.1",d)})}catch(d){throw await o.closeAll().catch(()=>{}),d.code==="EADDRINUSE"?new Error(Wo(t,await Cn(t))):d}let u=a.address().port;return e&&(M.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${u}/v1
|
|
67
|
+
`),zs(u)),{port:u,close:async()=>{let d=new Promise(l=>a.close(()=>l()));a.closeAllConnections(),await d,await o.closeAll()}}}async function kd(){let t=M.default.argv.slice(2),e=Do(t),n=t.shift()??"proxy";if(n==="env")return zs(Bo(e??Tn(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await Hs();return o?(M.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
|
|
68
|
+
`),0):(M.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
|
|
69
|
+
`),1)}if(n==="proxy"){let o=e??Tn(t),s=await Js(o,!0);return await new Promise(i=>{M.default.once("SIGINT",i),M.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(Mt).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let h=Fe(M.default.env);return Vs("pi",["-e",Ws(),...Lo(h.appId,t)],M.default.env)}if(r==="omp"){let h=Fe(M.default.env);return Vs("omp",["-e",Ws(),...Mo(h.appId,t)],M.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=Mt[r];if(!h)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(Mt).join(" | ")} \u2014 or \`-- <cmd>\``);o=h.bin,s=[...h.args??[],...t],i=h.env}let a=await jo(e,Pn(Fe(M.default.env))),u=null,d=a.port;a.mode==="reuse"?M.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})
|
|
70
|
+
`):a.reason&&M.default.stderr.write(`urun compat: ${a.reason}
|
|
71
|
+
`);let l=null,p=null,m=null,c=null;a.mode!=="reuse"&&(u=await Js(a.port,!1),d=u.port,c=$n(d),(0,ae.mkdirSync)(Zn.default.dirname(c),{recursive:!0}),m=(0,ae.createWriteStream)(c,{flags:"a"}),p=Ho({streams:M.default,note:h=>(0,ae.appendFileSync)(c,h)}).uninstall,m.on("error",h=>{l?.(),l=null,ie(M.default.stderr,`urun compat: proxy log ${c} failed: ${String(h)} \u2014 proxy output continues on the terminal
|
|
72
|
+
`)}),M.default.stdout.write(`urun openai proxy on http://127.0.0.1:${d}/v1 \u2014 proxy logs: ${c}
|
|
73
|
+
`),l=qo(m)),r==="codex"&&(s=$o(d,Fe(M.default.env).appId,s));let f=(0,Qn.spawn)(o,s,{stdio:"inherit",env:Co(M.default.env,d,i)}),g=c!==null?Vo({logPath:c,appendSync:ae.appendFileSync,restore:()=>{l?.(),l=null},writeStderr:h=>M.default.stderr.write(h),killChild:()=>f.kill("SIGTERM"),exit:h=>M.default.exit(h),proc:M.default}):null,_=await new Promise(h=>{f.once("exit",w=>h(w??1)),f.once("error",w=>{l?.(),l=null,ie(M.default.stderr,`failed to launch ${o}: ${String(w)}
|
|
74
|
+
`),h(127)})});g?.();let y=null;try{u&&await u.close()}catch(h){y=h}finally{l?.(),l=null,p?.(),p=null,m?.end()}return y!==null&&ie(M.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${_} preserved): ${String(y instanceof Error?y.message:y)}
|
|
75
|
+
`),_}}kd().then(t=>M.default.exit(t),t=>{M.default.stderr.write(`${String(t instanceof Error?t.message:t)}
|
|
76
|
+
`),M.default.exit(1)});
|