@urun-sh/openai 0.6.44 → 0.6.45
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-J3KCHTSA.js → chunk-3QZYIRAL.js} +3 -3
- package/dist/{chunk-BA3NCMS5.js → chunk-5JTIJPFV.js} +1 -1
- package/dist/{chunk-MJSK6W3W.js → chunk-BMSZZYSZ.js} +1 -1
- package/dist/{chunk-Y774TOE7.js → chunk-GCQR62TJ.js} +1 -1
- package/dist/chunk-LNQW3VFC.js +66 -0
- package/dist/{chunk-FNAZ2XBE.js → chunk-NUPHEB3L.js} +1 -1
- package/dist/{chunk-G6AFKOVS.js → chunk-PXV7QBSD.js} +1 -1
- package/dist/{chunk-HB5KNEY5.js → chunk-Q3AIBMET.js} +1 -1
- package/dist/chunk-ZXQXOEVN.js +4 -0
- package/dist/{composite-DNNAm0PY.d.ts → composite-BXbbnmL2.d.ts} +9 -0
- package/dist/{composite-DM2sT1Sp.d.cts → composite-n3axzdCh.d.cts} +34 -0
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +11 -0
- package/dist/gemini-live.d.ts +2 -0
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +42 -42
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +43 -43
- 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 +7 -7
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +54 -54
- package/dist/pooler/bin.cjs +2 -2
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +52 -52
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +30 -30
- package/dist/proxy/index.d.cts +16 -3
- package/dist/proxy/index.d.ts +8 -3
- package/dist/proxy/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DMRZZTYI.js +0 -4
- package/dist/chunk-VQSCBUKT.js +0 -66
package/dist/proxy/cli.cjs
CHANGED
|
@@ -1,92 +1,92 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ia=Object.create;var oo=Object.defineProperty;var Oa=Object.getOwnPropertyDescriptor;var Ta=Object.getOwnPropertyNames;var Pa=Object.getPrototypeOf,Ca=Object.prototype.hasOwnProperty;var $a=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ta(e))!Ca.call(t,o)&&o!==n&&oo(t,o,{get:()=>e[o],enumerable:!(r=Oa(e,o))||r.enumerable});return t};var nt=(t,e,n)=>(n=t!=null?Ia(Pa(t)):{},$a(e||!t||!t.__esModule?oo(n,"default",{value:t,enumerable:!0}):n,t));var Ma=()=>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,$=Ma();var eo=require("child_process"),Ae=require("fs"),to=nt(require("path"),1),B=nt(require("process"),1);var re=require("@urun-sh/core");var Ie=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ce=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Yt=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};async function so(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}function io(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),typeof t.language=="string"&&(r.language=t.language),r}function ao(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 uo=require("@urun-sh/core/internal");var La="llm-resp";async function*lo(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let u=typeof i.index=="number"?i.index:0,a=r.get(u)??{};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),r.set(u,a),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${u}`,tool_index:u,call_id:a.id,name:a.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield ao(s);return}}}async function*Wn(t,e){let n=`${La}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*lo(e,t.stream(n).messages())}finally{try{(0,uo.gcRequest)(t.doc("llm"),e)}catch{}}}var Qt=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Jn(e,n,this.consumerId);return this.write(r),Wn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=io(e,n,r,this.consumerId);return this.write(o),Wn(this.session,r)})}async writeGated(e,n){try{await so(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var co=0;function Ua(){return co+=1,`req_${Date.now().toString(36)}_${co.toString(36)}`}var bt=class{transport;constructor(e,n){this.transport=new Qt(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Ua(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var fo="audio",Kn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function mo(t,e,n=1e4){try{return await Da(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Da(t,e,n){let r=new Kn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(fo);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Fa(t,n);return await r.startInbound(i),r}function Fa(t,e){let n=t.stream(fo);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=a=>{a!=null&&(clearTimeout(i),s?.(),r(a))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var po="rt-video-in",kt=256e3;function Yn(t){let e=t.stream(po),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${po}') 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>kt)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${kt}-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 Ba=24e3,St=480,ja=111,qa=50,Zt=null;async function Ha(){if(Zt)return;let t=await import("opusscript");Zt=t.default??t}function Ga(){if(!Zt)throw new Error("[opus-guard] opusscript module not loaded");return new Zt(Ba,1,2048)}var zn=class{constructor(e=Ga){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=qa}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function en(){let t=await import("werift");await Ha();let e=new zn;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:u=>{let a=new Int16Array(i.length+u.length);a.set(i,0),a.set(u,i.length);let l=0;for(;a.length-l>=St;){let d=a.subarray(l,l+St);l+=St;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,St);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+St>>>0;let m=new t.RtpHeader({version:2,payloadType:ja,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),g=new t.RtpPacket(m,p);n.writeRtp(g)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(a){if(e.wedged)throw a;return}let u=new Int16Array(i.length/2);for(let a=0;a<u.length;a++)u[a]=i.readInt16LE(a*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function go(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var tn=require("@urun-sh/core"),Xn="rt-video-out";var Va="h264";function Ja(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 Wa(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;Ja(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 ho="urun.videoOut.v2-ws";function yo(t){let e=t.stream(Xn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Xn}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=a=>{for(let l of r)l(a)},i=!1,u=async()=>{for await(let a of e.messages()){if(!(a instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Xn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Wa(a)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let a of o)a()};return{codec:Va,onOutputFrame:a=>(n.add(a),i||(i=!0,u().catch(l=>s(l instanceof Error?l:new Error(String(l))))),()=>n.delete(a)),onLaneError:a=>(r.add(a),()=>r.delete(a)),onEnd:a=>(o.add(a),()=>o.delete(a))}}var wo={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},rt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function _o(t){let e=t.t;if(typeof e!="string"||!(e in wo))throw new rt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(wo).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function Ka(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new rt(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new rt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return _o(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new rt(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return _o(t)}function vo(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function za(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function bo(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw vo(e);let s=o.next();if(e!==void 0&&await za(s,e)==="aborted")throw s.catch(()=>{}),vo(e);let i=await s;if(i.done)return;yield Ka(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var So=require("@urun-sh/core"),Qn=2;function Ya(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Xa(t){let e=t?.type;return e==="response.completed"||e==="error"}function ko(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Qn;i++){let{app:u,entry:a,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(a,n);for await(let m of p){if(Xa(m)&&(d=!0),Ya(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof So.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<Qn&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<Qn&&!c){await t.evict(u,a);continue}return}})()}}var mr=require("crypto");var ge=class extends Error{name="ModelPriceError"},Zn="per_million_input_tokens",er="per_million_output_tokens",Ro="model_id,variant,unit,price_usd,effective_at,expires_at",xo={per_request:!0,per_minute:!0,per_output_unit:!0},Qa=5e3;function Za(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ge(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Eo(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ge(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function eu(t,e,n){return t===null?null:Eo(t,e,n)}function tu(t,e){if(t===Zn)return"input";if(t===er)return"output";if(typeof t=="string"&&Object.hasOwn(xo,t))return null;throw new ge(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Zn} | ${er}) nor a known GPU-time unit (${Object.keys(xo).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 nu(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 tr(t,e){return`${t}\0${e}`}function ru(t){if(!Array.isArray(t))throw new ge(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ge(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Ro.split(","))if(!Object.hasOwn(s,l))throw new ge(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=tu(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new ge(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new ge(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:Za(s.price_usd,o),effective_at:Eo(s.effective_at,o,"effective_at"),expires_at:eu(s.expires_at,o,"expires_at")})}return e}function Ao(t,e=Date.now(),n){let r=new Map,o=new Map;for(let a of t){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=r.get(a.model_id);l||(l=new Map,r.set(a.model_id,l),o.set(a.model_id,new Map));let d=a.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(a.model_id).set(d,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let s=[],i=[];for(let[a,l]of r){let d=l.get(""),c=(p,m,g)=>{let v=p&&p.length>0?p:d?.[m];if(!v||v.length===0)return null;let x=nu(v,m);return"reason"in x?x:x.rate.usd===0?m==="output"&&g!==null&&n?.has(tr(a,g))?x.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:x.rate};for(let[p,m]of o.get(a)){let g=l.get(p),v=c(g?.input,"input",m),x=c(g?.output,"output",m);if(v!==null&&"reason"in v){i.push({model_id:a,variant:m,reason:v.reason});continue}if(x!==null&&"reason"in x){i.push({model_id:a,variant:m,reason:x.reason});continue}v===null||x===null||s.push({model_id:a,variant:m,pricing:{input:v.usd,output:x.usd}})}}let u=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:s.sort(u),refusals:i.sort(u)}}function xt(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var Rt={prices:[],refusals:[]};async function Io(t){let e=t.fetchImpl??fetch,n=`${Zn},${er}`,r=await e(`${t.catalogUrl}/model_prices?select=${Ro}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Qa)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return ru(await r.json())}var qo=require("crypto");var X=class extends Error{},ou=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function su(t){if(typeof t!="string")return!1;let e=ou.exec(t);if(!e)return!1;let[,n,r,o,s,i,u]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let a=new Date(Date.UTC(n,r-1,o,s,i,u));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===o&&a.getUTCHours()===s&&a.getUTCMinutes()===i&&a.getUTCSeconds()===u}function iu(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new X(`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 X(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new X(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((u,a)=>{if(u===null||typeof u!="object")throw new X(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(u)}`);let l=u;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new X(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new X(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new X(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",su(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new X(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(u=>typeof u=="string"&&u.length>0)))throw new X(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let u=s;if(typeof s!="object"||typeof u.zdr!="boolean"||typeof u.hipaa!="boolean")throw new X(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let a of Object.keys(u))if(a!=="zdr"&&a!=="hipaa")throw new X(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function ot(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Oo(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=u=>new X(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${u}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let u of["model_id","variant"]){let a=o[u];if(typeof a!="string"||a===""||a.includes(":"))throw i(`"${u}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function nr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let u=t.endpoints.filter(l=>l.model_id===o);if(u.length===0)return null;if(s!==void 0){let l=u.find(d=>d.variant===s);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(u.length===1)return{shared_org_id:t.shared_org_id,endpoint:u[0]};let a=u.filter(l=>l.compat_default===!0);if(a.length!==1)throw new X(`shared model "${o}" has ${a.length} compat_default rows (exactly one required) among variants ${u.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:a[0]}}async function To(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 X(`catalog read failed: GET ${n} \u2192 ${r.status}`);return iu(await r.json())}function pe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var At="/partners/openrouter/models",au={chat:!0,code:!0,agent:!0,vl:!0},Po={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function uu(t){let e=t.toLowerCase();return Object.hasOwn(Po,e)?Po[e]:null}var Co={"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 lu(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Co,o)?Co[o]:null;if(s===null){r.push(o);continue}n.some(u=>u.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var $o={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Mo={2:"Llama2",3:"Llama3"};function du(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($o,s))return $o[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Mo,i))return Mo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var cu=["context_length","max_model_len"];function pu(t){let e=cu.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 nn(t){let e=t.map(pu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function fu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function rr(t){if(t.length===0)return null;let e=t.map(fu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function or(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function mu(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return Et(n);let r=e.filter(s=>pe(s.model_id)===t);if(r.length>0)return Et(r);let o=or(t,e);return o.length>0?Et(o):null}function Et(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:gu(t),matches:t}:null}function gu(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var Me=class extends Error{name="ModelCreatedError"};function st(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new Me(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new Me(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new Me(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),u=Number(o[3]),a=Date.UTC(s,i-1,u),l=new Date(a);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==u)throw new Me(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function Ge(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function rn(t,e,n){let r=mu(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=nn(s),u=st(s),a=xt(o.model_id,o.variant,n),l=Uo(o,s),d=rr(s);return Ge({id:t,object:"model",created:u,owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var hu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Uo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,u)=>i===r[u])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...hu],defect:o}:{published:[],defect:o}}function sr(t){let e=t.length>0?Et(t):null;return e===null?{published:[],defect:null}:Uo(e.row,e.matches)}function Lo(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 No(t){return{input:[{type:"prompt",unit:"token",cost_usd:Lo(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Lo(t.output)}]}}function yu(t,e,n,r){if(e.length===0)return null;let o=Et(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||au[s.task]!==!0)return null;let u=nn(i),a=xt(s.model_id,s.variant,n),l=du(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return u!==null&&(d.max_tokens={type:"integer",min:1,max:u,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:st(i),quantization:uu(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...u!==null?{supported_inputs:{max_context_length:{value:u,unit:"token"}}}:{},...a?{pricing:No(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:No(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Do(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?ot(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:lu(t?.regions,o),compliance:t?.compliance??null},u=[],a=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(a.has(d))continue;a.add(d);let c=yu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Ho="https://api.urun.sh/v1",G=class extends Error{},V=class extends Error{},ar="urs1.";function Tt(t,e){return ar+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function it(t){if(!t.startsWith(ar))return null;try{let e=JSON.parse(Buffer.from(t.slice(ar.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 Go(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 Fo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=bu(t);return e===null?[]:[e]}function wu(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
|
|
2
|
+
"use strict";var Ta=Object.create;var io=Object.defineProperty;var Oa=Object.getOwnPropertyDescriptor;var Pa=Object.getOwnPropertyNames;var Ca=Object.getPrototypeOf,$a=Object.prototype.hasOwnProperty;var Ma=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pa(e))!$a.call(t,o)&&o!==n&&io(t,o,{get:()=>e[o],enumerable:!(r=Oa(e,o))||r.enumerable});return t};var rt=(t,e,n)=>(n=t!=null?Ta(Ca(t)):{},Ma(e||!t||!t.__esModule?io(n,"default",{value:t,enumerable:!0}):n,t));var La=()=>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,M=La();var no=require("child_process"),Ae=require("fs"),ro=rt(require("path"),1),q=rt(require("process"),1);var oe=require("@urun-sh/core");var Ie=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ce=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var Zt=class extends Error{pool;model;constructor(e,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=e,this.model=n}};async function ao(t,e,n){if(t.synced===!0||typeof t.onSynced!="function")return;let r;await new Promise((o,s)=>{let i=t.onSynced(()=>{clearTimeout(r),o()});r=setTimeout(()=>{i(),s(new Error(`[urun] llm doc plane never synced within ${e}ms \u2014 ${n} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},e)})}var fo=require("@urun-sh/core/internal");function uo(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),typeof t.language=="string"&&(r.language=t.language),r}function lo(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 co=require("@urun-sh/core/internal");var Na="llm-resp";async function*po(t,e){let n=`resp_${t}`,r=new Map;for await(let o of e){let s=o;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:n,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:n,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let i of s.tool_calls){let u=typeof i.index=="number"?i.index:0,a=r.get(u)??{};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),r.set(u,a),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${u}`,tool_index:u,call_id:a.id,name:a.name,delta:i.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:n,status:"completed",...s.body}};return}else if(s.t==="error"){yield lo(s);return}}}async function*Wn(t,e){let n=`${Na}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*po(e,t.stream(n).messages())}finally{try{(0,co.gcRequest)(t.doc("llm"),e)}catch{}}}var en=class{constructor(e,n=15e3,r){this.session=e;this.docSyncTimeoutMs=n;this.sessionTag=r===void 0?e.sessionId??globalThis.crypto.randomUUID():r}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(e){this.sessionTag!==null&&(e.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){return this.writeGated(n,()=>{let r=Jn(e,n,this.consumerId);return this.write(r),Wn(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=uo(e,n,r,this.consumerId);return this.write(o),Wn(this.session,r)})}cancelTurn(e){try{(0,fo.gcRequest)(this.session.doc("llm"),e)}catch{}}async writeGated(e,n){try{await ao(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(r){throw new Error(`[urun] responses dial ${e} aborted before its envelope write: ${r instanceof Error?r.message:String(r)}`)}return n()}};var mo=0;function Da(){return mo+=1,`req_${Date.now().toString(36)}_${mo.toString(36)}`}var St=class{transport;constructor(e,n){this.transport=new en(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=Da(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var ho="audio",Kn=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),o=Math.floor(r.byteLength/2),s=new Int16Array(o);for(let i=0;i<o;i++)s[i]=r.readInt16LE(i*2);this.source.onData(s),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(i=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(i instanceof Error?i.message:String(i)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function yo(t,e,n=1e4){try{return await Fa(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function Fa(t,e,n){let r=new Kn(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(ho);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(u=>s.emit(u));let i=await Ba(t,n);return await r.startInbound(i),r}function Ba(t,e){let n=t.stream(ho);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=a=>{a!=null&&(clearTimeout(i),s?.(),r(a))};s=n.on?.("track",u),n.track!=null&&u(n.track)})}var go="rt-video-in",xt=256e3;function Yn(t){let e=t.stream(go),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${go}') 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>xt)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${xt}-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 qa=24e3,kt=480,ja=111,Ha=50,tn=null;async function Ga(){if(tn)return;let t=await import("opusscript");tn=t.default??t}function Va(){if(!tn)throw new Error("[opus-guard] opusscript module not loaded");return new tn(qa,1,2048)}var zn=class{constructor(e=Va){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=Ha}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let o=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,o}catch(o){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${o instanceof Error?o.message:String(o)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function nn(){let t=await import("werift");await Ga();let e=new zn;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:u=>{let a=new Int16Array(i.length+u.length);a.set(i,0),a.set(u,i.length);let l=0;for(;a.length-l>=kt;){let d=a.subarray(l,l+kt);l+=kt;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),p=e.encode(c,kt);if(p===null){i=a.slice(l);break}o=o+1&65535,s=s+kt>>>0;let m=new t.RtpHeader({version:2,payloadType:ja,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),h=new t.RtpPacket(m,p);n.writeRtp(h)}i=a.slice(l)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{if(s.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${s.payload.length} B > 3828 B max`);return}let i;try{i=e.decode(s.payload)}catch(a){if(e.wedged)throw a;return}let u=new Int16Array(i.length/2);for(let a=0;a<u.length;a++)u[a]=i.readInt16LE(a*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function wo(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,serve_app_slug,serve_function,created_at,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}var rn=require("@urun-sh/core"),Xn="rt-video-out";var Ja="h264";function Wa(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 Ka(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;Wa(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 _o="urun.videoOut.v2-ws";function vo(t){let e=t.stream(Xn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Xn}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=a=>{for(let l of r)l(a)},i=!1,u=async()=>{for await(let a of e.messages()){if(!(a instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${Xn}" delivered a non-BINARY \xA75 payload (${typeof a}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let l;try{l=Ka(a)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(l)}for(let a of o)a()};return{codec:Ja,onOutputFrame:a=>(n.add(a),i||(i=!0,u().catch(l=>s(l instanceof Error?l:new Error(String(l))))),()=>n.delete(a)),onLaneError:a=>(r.add(a),()=>r.delete(a)),onEnd:a=>(o.add(a),()=>o.delete(a))}}var bo={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},ot=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function So(t){let e=t.t;if(typeof e!="string"||!(e in bo))throw new ot(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(bo).join(", ")}`);let n={kind:e};return typeof t.delta=="string"&&(n.text=t.delta),typeof t.start_ms=="number"&&Number.isFinite(t.start_ms)&&(n.startMs=t.start_ms),n}function za(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new ot(`the "stt" transcript lane delivered a string payload that is not valid JSON (${n instanceof Error?n.message:String(n)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new ot(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return So(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new ot(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(t)?"array":typeof t}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return So(t)}function ko(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Ya(t,e){return e.aborted?"aborted":await new Promise(n=>{let r=!1,o=i=>{r||(r=!0,e.removeEventListener("abort",s),n(i))},s=()=>o("aborted");e.addEventListener("abort",s,{once:!0}),t.then(()=>o("pulled"),()=>o("pulled"))})}function xo(t,e){let n=t.stream("stt");if(typeof n.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*r(){let o=n.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw ko(e);let s=o.next();if(e!==void 0&&await Ya(s,e)==="aborted")throw s.catch(()=>{}),ko(e);let i=await s;if(i.done)return;yield za(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var Ro=require("@urun-sh/core"),Qn=2;function Xa(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Qa(t){let e=t?.type;return e==="response.completed"||e==="error"}function Eo(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Qn;i++){let{app:u,entry:a,identity:l}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:l});let d=!1,c=!1;try{let p=await t.createStream(a,n);for await(let m of p){if(Qa(m)&&(d=!0),Xa(m)){if(i>1)continue}else c=!0;yield m}}catch(p){if(p instanceof Ro.SessionFailedError&&(p.kind==="never-live"||p.kind==="create-failed")){try{t.onAdmissionVerdict?.(u,a,p)}catch{}throw p}if(i<Qn&&!c){await t.evict(u,a);continue}throw p}if(d)return;if(i<Qn&&!c){await t.evict(u,a);continue}return}})()}}var mr=require("crypto");var ge=class extends Error{name="ModelPriceError"},Zn="per_million_input_tokens",er="per_million_output_tokens",Io="model_id,variant,unit,price_usd,effective_at,expires_at",Ao={per_request:!0,per_minute:!0,per_output_unit:!0},Za=5e3;function eu(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new ge(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function To(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new ge(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function tu(t,e,n){return t===null?null:To(t,e,n)}function nu(t,e){if(t===Zn)return"input";if(t===er)return"output";if(typeof t=="string"&&Object.hasOwn(Ao,t))return null;throw new ge(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${Zn} | ${er}) nor a known GPU-time unit (${Object.keys(Ao).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 ru(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 tr(t,e){return`${t}\0${e}`}function ou(t){if(!Array.isArray(t))throw new ge(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new ge(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let l of Io.split(","))if(!Object.hasOwn(s,l))throw new ge(`${o} has no "${l}" column: ${JSON.stringify(s)}`);let i=nu(s.unit,o);if(i===null)continue;let u=s.model_id;if(typeof u!="string"||u==="")throw new ge(`${o} has no model_id (${JSON.stringify(s)})`);let a=s.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new ge(`${o} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:u,variant:a,side:i,usd:eu(s.price_usd,o),effective_at:To(s.effective_at,o,"effective_at"),expires_at:tu(s.expires_at,o,"expires_at")})}return e}function Oo(t,e=Date.now(),n){let r=new Map,o=new Map;for(let a of t){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=r.get(a.model_id);l||(l=new Map,r.set(a.model_id,l),o.set(a.model_id,new Map));let d=a.variant??"",c=l.get(d);c||(c={input:[],output:[]},l.set(d,c),o.get(a.model_id).set(d,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let s=[],i=[];for(let[a,l]of r){let d=l.get(""),c=(p,m,h)=>{let v=p&&p.length>0?p:d?.[m];if(!v||v.length===0)return null;let k=ru(v,m);return"reason"in k?k:k.rate.usd===0?m==="output"&&h!==null&&n?.has(tr(a,h))?k.rate:{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:k.rate};for(let[p,m]of o.get(a)){let h=l.get(p),v=c(h?.input,"input",m),k=c(h?.output,"output",m);if(v!==null&&"reason"in v){i.push({model_id:a,variant:m,reason:v.reason});continue}if(k!==null&&"reason"in k){i.push({model_id:a,variant:m,reason:k.reason});continue}v===null||k===null||s.push({model_id:a,variant:m,pricing:{input:v.usd,output:k.usd}})}}let u=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:s.sort(u),refusals:i.sort(u)}}function Rt(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var Et={prices:[],refusals:[]};async function Po(t){let e=t.fetchImpl??fetch,n=`${Zn},${er}`,r=await e(`${t.catalogUrl}/model_prices?select=${Io}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Za)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return ou(await r.json())}var Vo=require("crypto");var Q=class extends Error{},su=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function iu(t){if(typeof t!="string")return!1;let e=su.exec(t);if(!e)return!1;let[,n,r,o,s,i,u]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let a=new Date(Date.UTC(n,r-1,o,s,i,u));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===o&&a.getUTCHours()===s&&a.getUTCMinutes()===i&&a.getUTCSeconds()===u}function au(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new Q(`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 Q(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new Q(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((u,a)=>{if(u===null||typeof u!="object")throw new Q(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(u)}`);let l=u;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new Q(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new Q(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let d=(c,p)=>{if(l[c]!==void 0&&l[c]!==null&&!p)throw new Q(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};d("ready",typeof l.ready=="boolean"),d("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),d("ready_since",iu(l.ready_since));for(let c of["model_id","variant"]){let p=l[c];if(p.includes(":"))throw new Q(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(p)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof l.output_free=="boolean"),l});if(o!=null&&(!Array.isArray(o)||!o.every(u=>typeof u=="string"&&u.length>0)))throw new Q(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let u=s;if(typeof s!="object"||typeof u.zdr!="boolean"||typeof u.hipaa!="boolean")throw new Q(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let a of Object.keys(u))if(a!=="zdr"&&a!=="hipaa")throw new Q(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(s)}`)}return i.length===0?null:{shared_org_id:n,endpoints:i,...o!=null?{regions:o}:{},...s!=null?{compliance:s}:{}}}function st(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Co(t){let e=t.filter(o=>typeof o.shared_org_id=="string"&&o.shared_org_id!=="");if(e.length===0)return null;let n=e[0].shared_org_id,r=e.map((o,s)=>{let i=u=>new Q(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${u}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let u of["model_id","variant"]){let a=o[u];if(typeof a!="string"||a===""||a.includes(":"))throw i(`"${u}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof o.app_slug!="string"||o.app_slug==="")throw i("no app_slug");if(typeof o.function!="string"||o.function==="")throw i("no function");if(o.app_id!==void 0&&o.app_id!==null&&(typeof o.app_id!="string"||o.app_id===""))throw i(`malformed app_id ${JSON.stringify(o.app_id)}`);return{model_id:o.model_id,variant:o.variant,app_slug:o.app_slug,app_id:o.app_id??null,function:o.function,...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...o.warm!==void 0&&o.warm!==null?{warm:o.warm}:{},...o.compat_default===!0?{compat_default:!0}:{},...o.output_free===!0?{output_free:!0}:{},...o.ready!==void 0&&o.ready!==null?{ready:o.ready}:{},...o.ready_runtimes!==void 0&&o.ready_runtimes!==null?{ready_runtimes:o.ready_runtimes}:{},...o.ready_since?{ready_since:o.ready_since}:{}}});return{shared_org_id:n,endpoints:r}}function nr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let u=t.endpoints.filter(l=>l.model_id===o);if(u.length===0)return null;if(s!==void 0){let l=u.find(d=>d.variant===s);return l?{shared_org_id:t.shared_org_id,endpoint:l}:null}if(u.length===1)return{shared_org_id:t.shared_org_id,endpoint:u[0]};let a=u.filter(l=>l.compat_default===!0);if(a.length!==1)throw new Q(`shared model "${o}" has ${a.length} compat_default rows (exactly one required) among variants ${u.map(l=>l.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:a[0]}}async function $o(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 Q(`catalog read failed: GET ${n} \u2192 ${r.status}`);return au(await r.json())}function pe(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var It="/partners/openrouter/models",uu={chat:!0,code:!0,agent:!0,vl:!0},Mo={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function lu(t){let e=t.toLowerCase();return Object.hasOwn(Mo,e)?Mo[e]:null}var Lo={"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 du(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Lo,o)?Lo[o]:null;if(s===null){r.push(o);continue}n.some(u=>u.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var No={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Uo={2:"Llama2",3:"Llama3"};function cu(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(No,s))return No[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Uo,i))return Uo[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var pu=["context_length","max_model_len"];function fu(t){let e=pu.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 on(t){let e=t.map(fu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function mu(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function rr(t){if(t.length===0)return null;let e=t.map(mu),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function or(t,e){let n=e.filter(o=>o.serve_app_slug===t);return new Set(n.map(o=>o.model_id)).size===1?n:[]}function gu(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return At(n);let r=e.filter(s=>pe(s.model_id)===t);if(r.length>0)return At(r);let o=or(t,e);return o.length>0?At(o):null}function At(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:hu(t),matches:t}:null}function hu(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}var Me=class extends Error{name="ModelCreatedError"};function it(t){if(t.length===0)return 0;let e=`${t[0].model_id}:${t[0].variant}`,n=t.map(d=>d.created_at??void 0);if(n.some(d=>d===void 0))throw new Me(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let r=n[0];if(!n.every(d=>d===r))throw new Me(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(n)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(o===null)throw new Me(`model "${e}" carries a malformed created_at ("${r}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let s=Number(o[1]),i=Number(o[2]),u=Number(o[3]),a=Date.UTC(s,i-1,u),l=new Date(a);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==i-1||l.getUTCDate()!==u)throw new Me(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return a/1e3}function Ge(t){let e={id:t.id,object:t.object,created:t.created,owned_by:t.owned_by,...t.context_length!==void 0?{context_length:t.context_length}:{},...t.pricing!==void 0?{pricing:t.pricing}:{},...t.voices!==void 0?{voices:t.voices}:{},...t.capabilities!==void 0?{capabilities:t.capabilities}:{}};return"image_modes"in t?{...e,image_modes:t.image_modes}:e}function sn(t,e,n){let r=gu(t,e);if(!r)return Ge({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=on(s),u=it(s),a=Rt(o.model_id,o.variant,n),l=Bo(o,s),d=rr(s);return Ge({id:t,object:"model",created:u,owned_by:"urun",...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var yu=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Bo(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,u)=>i===r[u])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...yu],defect:o}:{published:[],defect:o}}function sr(t){let e=t.length>0?At(t):null;return e===null?{published:[],defect:null}:Bo(e.row,e.matches)}function Do(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 Fo(t){return{input:[{type:"prompt",unit:"token",cost_usd:Do(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Do(t.output)}]}}function wu(t,e,n,r){if(e.length===0)return null;let o=At(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||uu[s.task]!==!0)return null;let u=on(i),a=Rt(s.model_id,s.variant,n),l=cu(s.hf_repo),d={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return u!==null&&(d.max_tokens={type:"integer",min:1,max:u,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:it(i),quantization:lu(s.variant),...l!==null?{tokenizer:l}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...u!==null?{supported_inputs:{max_context_length:{value:u,unit:"token"}}}:{},...a?{pricing:Fo(a).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...a?{pricing:Fo(a).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function qo(t,e,n,r){let o=r??(l=>console.warn(l.trimEnd())),s=t?st(t):[];if(s.length>0){let l=s.filter(d=>d.ready===void 0);if(l.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let d=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");o(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${d} carry no ready field and are declared not ready`)}}let i={datacenters:du(t?.regions,o),compliance:t?.compliance??null},u=[],a=new Set;for(let l of s){let d=`${l.model_id}:${l.variant}`;if(a.has(d))continue;a.add(d);let c=wu(l,e.filter(p=>p.model_id===l.model_id&&p.variant===l.variant),n,i);c&&u.push(c)}return{data:u}}var Jo="https://api.urun.sh/v1",G=class extends Error{},J=class extends Error{bindingLost;constructor(e,n){super(e),this.bindingLost=n?.bindingLost??!1}},ar="urs1.";function Pt(t,e){return ar+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Ve(t){if(!t.startsWith(ar))return null;try{let e=JSON.parse(Buffer.from(t.slice(ar.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 Wo(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/apps`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${r.status}`);let o=await r.json();if(!Array.isArray(o.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(o.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${o.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return o.apps}function jo(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Su(t);return e===null?[]:[e]}function _u(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(t)}
|
|
3
3
|
`),null;let e={},n=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],r=!1;for(let[o,s]of n){let i=t[o];if(i==null)continue;let u=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(u)||u<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
|
|
4
|
-
`),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function
|
|
5
|
-
`),
|
|
6
|
-
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(tr(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(
|
|
7
|
-
`);let a=(n?ot(n):[]).map(l=>{let d=s.filter(S=>S.model_id===l.model_id&&S.variant===l.variant),c=nn(d),p=st(d),m=rr(d),g=xt(l.model_id,l.variant,i),v=sr(d);return Ge({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...g!==null?{pricing:g}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>rn(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Do(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=ir(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Bo(`${r.modelId}:${r.variant}`,s).includes(n)}return Fo(ur(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Le(It(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Le(It(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Le(It(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):It(n,r);return ku(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):It(n,r);return sr(o)}async imageModelList(){let e=await this.catalogRows(),n=Rt,r=[];for(let s of await this.availableIds()){let i=Fo(ur(s,e));i.length!==0&&r.push(Ge({...rn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of ot(o)){let i=ir(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Bo(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:st(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Rt,r=[];for(let s of await this.availableIds())Le(Jo(s,e))==="stt"&&r.push(rn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of ot(o)){let i=ir(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Le(i)!=="stt")continue;let u=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:st(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Ue=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Pt=class extends Ue{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},lr=class extends Ue{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},be=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},un=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(n=>n.state==="paused"&&!n.opening).sort((n,r)=>n.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Pt;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new Pt;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand();continue}let a=r+n-Date.now();if(a<=0)throw new lr(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,a)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Pt}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening);(r||o)&&this.openForDemand()}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var dr=require("@urun-sh/core"),Se=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},dn=33e4;function Wo(t,e=dn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new ln),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof V||l instanceof dr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof ln?(await r.return?.(void 0),new Se("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Se("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new Se("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var ln=class extends Error{constructor(){super("stream idle timeout")}};function Ko(t){return t instanceof Se?!1:t instanceof V?!0:t instanceof dr.SessionFailedError?t.kind==="transport-failed":!1}var xu=require("http");var cn=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds};var cr=require("@urun-sh/core"),Ru="audio";function zo(t){let e=t.streamEndpoint(Ru);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,cr.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,cr.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var Yo=require("@urun-sh/core"),Eu="rt-video-in";function Xo(t){let e=t.streamEndpoint(Eu);return{sendInputFrame:async n=>{e.send((0,Yo.encodeStreamEnvelope)(n))}}}var Au=3,Iu="llm",Ou=new Set(["paused","error"]);function Qo(t,e,n){let r=t.doc(Iu),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<Au||d(new V(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&Ou.has(c.name)&&d(new V(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*pr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var Pu=0,Cu=4,$u=4;function es(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Pu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,Cu));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",$u),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function ts(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return dn;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function fr(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 ns(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=v=>({session:v,responses:new bt(v),gone:Qo(v,n)});if(i.lane==="jwt"){let v=(0,re.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(fr(v,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let v=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:x}=i,S=(typeof t.subject=="function"?t.subject():t.subject)??(0,mr.randomUUID)(),w=(0,re.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,re.createClientToken)(v,{baseUrl:x,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:S,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(fr(w,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,mr.randomUUID)(),g=(0,re.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,re.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(fr(g,e.appSlug,u,l))}function rs(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 gr(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 Mu=new Set(["error","paused"]);function os(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=ns(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new sn({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Go({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>go(n):null),listPrices:n?()=>Io(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return Oo(i)}:e.lane==="api-key"?()=>To({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:rs});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ne({appSlug:t.defaultApp}))),s}function ss(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
8
|
-
`)},a=(d,c)=>{let p=o.get(c);if(p)return p;let m=new un({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async g=>{let v=ns(t,d,c,{concurrencyKey:g.concurrencyKey});return v.gone.onGone(()=>m.markSessionDead(v)),await fn(v.session),u(`slot attached pool=${c} slot=${g.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async g=>{g.gone.dispose(),g.audioDispose?.(),await g.session.end()},onDetach:(g,v)=>u(`slot detached pool=${c} slot=${g.concurrencyKey} reason=${v}`),terminalOpenFailure:g=>g instanceof re.SessionFailedError&&gr(g)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);a(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){u(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ne(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ne(c),m=a(c,p);await l(c,p);let g=await m.acquire({timeoutMs:m.requestWaitMs}),v=i.get(g.entry)??[];return v.push(g),i.set(g.entry,v),{app:p,entry:g.entry,identity:Ot(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ne(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Lu(t){return(0,re.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?re.DEFAULT_WHEN_LIVE_TIMEOUT_MS:re.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:re.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function fn(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Lu(t.phase),signal:e})}async function Nu(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}async function Zo(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function pn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function is(t,e=en,n,r,o=dn,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let h=f.session.id;return typeof h=="string"&&h.length>0?h:null},p="lane",m=f=>{let h=it(f);if(!s||!h||h.app!==p)return null;let y=s.entryFor(h.key);if(!y)throw new V(`the lane behind this handle (${h.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:h.key,entry:y}},g=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let h=i.get(f);if(!h){let y={waiting:0,gone:new AbortController};d.set(f,y),h=(async()=>{if(await fn(f.session,y.gone.signal),y.gone.signal.aborted)throw pn(y.gone.signal);d.get(f)===y&&d.delete(f);let b=await mo(f.session,await e());return Object.assign(b,{sessionId:f.session.id})})(),i.set(f,h),h.then(b=>{i.get(f)===h&&(f.audioDispose=()=>b.dispose())},()=>{}),h.catch(()=>{i.get(f)===h&&i.delete(f)}),h.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return h},x=f=>{let h=l.get(f);return h||(h=(async()=>{let y=await v(f);return{appendInputAudio:(b,E)=>y.appendInputAudio(b,E),onOutputAudio:b=>y.onOutputAudio(b),sessionId:c(f)}})(),l.set(f,h),h.catch(()=>{l.get(f)===h&&l.delete(f)})),h},S=async(f,h,y,b=!1)=>{let E=()=>b?Zo(f.session):Nu(f.session);if(y?.aborted){let _=d.get(f);throw(i.get(f)===void 0||_!==void 0&&_.waiting===0)&&await E().catch(()=>{}),pn(y)}let I=h(f),O=d.get(f);return O!==void 0&&O.waiting++,y===void 0?I:new Promise((_,R)=>{let k=()=>{O!==void 0&&--O.waiting===0&&d.get(f)===O&&(O.gone.abort(),d.delete(f),i.delete(f),l.delete(f),E().catch(()=>{})),R(pn(y))};y.addEventListener("abort",k,{once:!0});let C=()=>y.removeEventListener("abort",k);I.then(N=>{C(),_(N)},N=>{C(),R(N)})})},w=async(f,h,y)=>{try{return await y}catch(b){throw(b instanceof V||b instanceof re.SessionFailedError&&gr(b))&&(t.evict(f,h),b instanceof re.SessionFailedError&&n?.(f,b.kind==="never-live"?"never-live":"create-failed")),b}};return{createResponse:ko({sessionFor:s?async f=>{let h=await t.resolveTargetFor(f);if(h.sharedApp)try{let y=await s.sessionFor(f,h);return{app:y.app,entry:y.entry,identity:y.identity}}catch(y){if(y instanceof Yt)return r?r.sessionFor(f):t.sessionFor(f);if(y instanceof cn)return console.error(`[pooler-fallback] pooler channel failed for ${f} (${y.name} ${y.code}: ${y.message}) \u2014 serving via the per-request path`),r?r.sessionFor(f):t.sessionFor(f);throw y}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,h)=>{s&&s.owns(h)?s.evict(h):r?r.evict(h):t.evict(f,h)},onAdmissionVerdict:(f,h,y)=>{gr(y)&&(s&&s.owns(h)?s.evict(h):r?r.markSessionDead(h):t.evict(f,h),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,h)=>{try{await fn(f.session);let y=Wo(pr(await f.responses.responses.create(h),f.gone),o);if(!r&&!s)return y;let b=f;return(async function*(){try{yield*y}catch(I){throw Ko(I)&&(s&&s.owns(b)?s.evict(b):r&&(I instanceof V?r.markSessionDead(b):r.evict(b))),I}finally{s&&s.owns(b)?s.release(b):r?.end(b)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,h)=>t.supportsImages(f,h),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,h)=>{let{app:y,entry:b}=await t.sessionFor(f);return await w(y,b,S(b,v,h))},openAudioOn:async(f,h,y,b)=>{let E=m(f);if(E){let R=E.entry.session;return zo(R)}let{app:I,entry:O}=await t.sessionForHandle(f);if(b&&O.session.phase?.name!=="live"){let R=O.session.phase?.name;b({status:R==="queued"||R==="waiting_for_capacity"?R:"pending",reason:`the dial's session is ${R??"not yet admitted"} \u2014 the connection waits for admission`})}let _=it(f)?.app.startsWith(an)??!1;return await w(I,O,S(O,x,h,_))},openTurnsOn:async function*(f,h){if(h?.aborted)throw pn(h);let y=await g(f);yield*bo(y.session,h)},openVideoOn:async f=>{let h=m(f);if(h)return Xo(h.entry.session);let{entry:y}=await t.sessionForHandle(f),b=u.get(y);return b||(b=Yn(y.session),u.set(y,b)),b},openVideo:async f=>{let{entry:h}=await t.sessionFor(f),y=u.get(h);return y||(y=Yn(h.session),u.set(h,y)),y},openVideoOut:async f=>{let{entry:h}=await t.sessionFor(f),y=a.get(h);return y||(y=yo(h.session),a.set(h,y)),y},sessionHandle:async f=>{if(s){let h=await t.resolveTargetFor(f);if(h.sharedApp){let y=await s.sessionFor(f,h),b=c(y.entry);if(b===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Tt(p,b)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:y,entry:b}=await t.dedicatedSessionFor(f);return Tt(y,rs(b))},releaseSessionHandle:f=>{let h=it(f);if(!h)return;if(h.app.startsWith(an)){(async()=>{let b=null;try{b=(await t.sessionForHandle(f)).entry}catch{return}await Zo(b.session).catch(()=>{}),await t.evict(h.app,b)})();return}if(!s||h.app!==p)return;let y=s.entryFor(h.key);y&&s.release(y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:h,entry:y}=await t.sessionForHandle(f);await t.evict(h,y)},createResponseOn:async(f,h,y)=>{let b=await g(f);await fn(b.session);let E=y!==void 0&&m(f)?new bt({...b.session,consumerId:y},{sessionTag:y}):b.responses;return pr(await E.responses.create(h),b.gone)},onSessionEnd:async(f,h)=>{let y=m(f);if(y)return y.entry.gone.onGone(O=>h({timeLeftMs:null,reason:O.message}));let{entry:b}=await t.sessionForHandle(f),E=b.session;if(typeof E.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let I=!1;return E.onPhase(O=>{if(I||!Mu.has(O.name))return;I=!0;let _=E.endsAt??null;h({timeLeftMs:_?Math.max(0,_.getTime()-Date.now()):null,reason:O.reason??`session ${O.name}`})})}}}var ya=require("http");var Rs=require("crypto"),Es=require("ws");var us="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Uu=1007,ls=1008,Pe=1011,yn=1008,A=class extends Error{constructor(n,r=Uu){super(n);this.closeCode=r}closeCode},te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,mn=["setup","clientContent","realtimeInput","toolResponse"];function ds(t){let e;try{e=JSON.parse(t)}catch{throw new A("client message is not valid JSON")}let n=te(e);if(!n)throw new A("client message must be a JSON object");let r=mn.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!mn.includes(u));if(o.length>0)throw new A(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${mn.join(", ")}`);if(r.length!==1)throw new A(`client message must contain exactly one of ${mn.join(", ")} (got ${r.length})`);let s=r[0],i=te(n[s]);if(!i)throw new A(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function cs(t,e){if(typeof t=="string")return t;let n=te(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new A(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=te(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new A(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new A(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new A(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
9
|
-
`)}var Du={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Je="urun.videoOut";function ps(t){return{framing:ho,codec:t}}function fs(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Je]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Fu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},Bu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Je],as=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ju(t){let e=te(t);if(!e)throw new A("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new A(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=te(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new A("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new A(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new A("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!as.includes(e.activityHandling))throw new A(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${as.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var qu=["temperature","maxOutputTokens","responseModalities"];function ms(t){for(let[c,p]of Object.entries(Fu))if(t[c]!==void 0)throw new A(p);for(let c of Object.keys(t))if(!Bu.includes(c))throw new A(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new A('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=te(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new A("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!qu.includes(c))throw new A(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new A("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new A("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new A(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:cs(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new A("setup.tools must be an array");u=[];for(let c of t.tools){let p=te(c);if(!p)throw new A("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new A(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new A("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let g=te(m);if(!g||typeof g.name!="string")throw new A("functionDeclarations entries require a string name");u.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=te(t.sessionResumption);if(!c)throw new A("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new A(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new A("sessionResumption.handle must be a non-empty string when present");a={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?Du:ju(t.realtimeInputConfig),d=!1;if(t[Je]!==void 0){if(!te(t[Je]))throw new A(`setup["${Je}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:u,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:a,videoOut:d}}function gs(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function hs(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ys(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new A(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new A("clientContent.turns must be an array");let n=[];for(let r of e){let o=te(r);if(!o)throw new A("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new A(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:cs(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var gn=16e3,ws=24e3,Hu=`audio/pcm;rate=${ws}`,_s=Buffer.alloc(960).toString("base64");function Gu(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let u=0;u<r;u++){let a=u*s,l=Math.floor(a);if(l>=i){o[u]=t[i];continue}let d=a-l;o[u]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Vu(t){let e=te(t);if(!e)throw new A("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new A("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Ju(t){let e=te(t);if(!e)throw new A("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new A(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==gn)throw new A(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${gn} Hz (audio/pcm;rate=${gn})`);if(typeof e.data!="string"||e.data.length===0)throw new A("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new A(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Gu(o,gn,ws);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function vs(t){if(t.mediaChunks!==void 0)throw new A('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new A("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=te(t[o]);if(!s||Object.keys(s).length!==0)throw new A(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new A(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new A(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Ju(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Vu(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new A("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new A("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function bs(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new A(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new A("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=te(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new A("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Ss(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function ks(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Hu,data:t}}]}}}}function xs(t){let e=te(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=te(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=te(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=te(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new A(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Pe);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new A(`upstream function_call arguments are not valid JSON: ${c}`,Pe)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let u=te(e.usage),a={serverContent:{turnComplete:!0}};if(u){let l={};typeof u.input_tokens=="number"&&(l.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(l.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(l.totalTokenCount=u.total_tokens),Object.keys(l).length>0&&(a.usageMetadata=l)}return i.push(a),{messages:i,assistantItems:o}}var Wu=256,hr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Wu;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ku="local",Ct=t=>t.slice(0,120),yr=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 G){this.ws.close(ls,Ct(e.message));return}if(e instanceof V){this.ws.close(yn,Ct(e.message));return}if(e instanceof A){this.ws.close(e.closeCode,Ct(e.message));return}this.ws.close(Pe,Ct(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=ds(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new A(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=ys(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=vs(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:_s);return}this.transcript.push(...bs(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new A("setup may only be sent once, as the first client message");let n=ms(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new A("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",yn);if(s.model!==n.model)throw new A(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new A("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new A(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,yn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),u=i.onOutputFrame(l=>this.send(fs(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[Je]=ps(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new A("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new A("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Pe);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(ks(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new A("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new A("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Pe);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new A(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new A("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new A("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,Rs.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(gs(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(hs(e.timeLeftMs)),this.ws.close(Pe,Ct(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let a of r){if(n.interrupted)break;let l=a;if(l.type==="error")throw new A(`upstream error: ${JSON.stringify(l)}`,Pe);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=Ss(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new A("upstream produced no response.completed event",Pe);let{messages:i,assistantItems:u}=xs(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},We=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function zu(t,e,n){let r=new Set;(a=>{if(typeof a=="string")a!==""&&r.add(a);else if(Array.isArray(a))for(let l of a)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new We(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 We(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let u;for(let a of r)u=a;if(u===void 0&&n)throw new We(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function As(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Es.WebSocketServer({noServer:!0}),o=new hr;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===us&&(u.on("error",()=>{}),(async()=>{let d=zu(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new We(401,"invalid local proxy api key");c={clients:e.clients,scope:Ku}}r.handleUpgrade(i,u,a,p=>{new yr(p,c,o)})})().catch(d=>{let c=502;(d instanceof We||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);u.destroyed||(u.write(`HTTP/1.1 ${c} ${p}\r
|
|
4
|
+
`),r=!0;break}e[o]=u}return r||Object.keys(e).length===0?null:e}function vu(t,e){if(t.length===0)return null;let n;return e.modelId&&(n=t.find(r=>r.model_id===e.modelId&&(!e.variant||r.variant===e.variant))),n||(n=t.find(r=>r.serve_app_slug===e.appSlug||pe(`${r.model_id}-${r.variant}`)===e.appSlug||pe(r.model_id)===e.appSlug)),n?_u(n.engine_args?.pool):null}function ir(t,e,n,r,o){if(!o)throw new Q(`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 Q(`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 Q(`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 Ho(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 Q(`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 Ko="shared:",Go="speech:",Ct="realtime:";function Ne(t){return t.sharedApp?Ko+t.appSlug:t.appSlug}function Ot(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 ur(t,e){let n=e.filter(s=>pe(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>pe(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function bu(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Su(t){let e=t.map(bu),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var ku={stt:"stt",tts:"tts"};function Le(t){if(t.length===0)return null;let e=t[0].task??void 0,n=t.every(o=>(o.task??void 0)===e),r=e===void 0?void 0:ku[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function zo(t,e){let n=ur(t,e);return n.length>0?n:or(t,e)}function Tt(t,e){return zo(t.appSlug,e)}function xu(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Q(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var an=6e4,un=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,n,r){let o=e.current;return o&&Date.now()-o.at<r?o.value:o?(o.refreshing||(o.refreshing=(async()=>{try{e.current={at:Date.now(),value:await n()}}catch{}finally{o.refreshing=void 0}})()),o.value):(e.current={at:Date.now(),value:await n()},e.current.value)}seed(e,n){this.snapshotMintId(n),this.pool.set(e,Promise.resolve(n))}snapshotMintId(e){try{let n=this.keyOf(e),r=e;this.mintedIds.has(r)||this.mintedIds.set(r,n)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??an):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??an):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??an):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??an;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let n=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:n},n}async pricesForListing(e){let n;try{n=await this.priceRows()}catch(o){if(o instanceof ge)throw o;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(o instanceof Error?o.message:o)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
5
|
+
`),Et}let r=Oo(n,Date.now(),e);for(let o of r.refusals)this.warn(`urun /v1/models: refusing to price ${o.model_id}:${o.variant??"*"} \u2014 ${o.reason}
|
|
6
|
+
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(tr(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(Ko)||o.startsWith(Go)||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 G(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${r}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${r}`)}async sharedLane(e){if(!this.opts.shared)return null;let n=await this.sharedBlock();if(!n)return null;let r=nr(n,e);if(r)return r;let o=e.lastIndexOf(":"),s=o>0?e.slice(0,o):e,i=o>0?e.slice(o+1):void 0,u=pe(s),a=n.endpoints.filter(c=>pe(c.model_id)===u&&(i===void 0||c.variant===i)),l=new Set(a.map(c=>c.model_id)),d=[...l][0];return d===void 0||l.size!==1?null:nr(n,d,i)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=pe(n);if(o===r)return{appSlug:r};let s=await this.sharedLane(n);if(s)return{appSlug:s.endpoint.app_slug,fnName:s.endpoint.function,sharedApp:!0,modelId:s.endpoint.model_id,variant:s.endpoint.variant,sharedOrgId:s.shared_org_id,gpuSpec:s.endpoint.gpu_spec??void 0,appId:s.endpoint.app_id??void 0};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let i=await this.deployedApps(),u=this.servable(i);if(u.includes(o))return{appSlug:o};let a=u.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new G(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(l)throw new G(`model "${n}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let u=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===pe(a.model_id)||o===pe(`${a.model_id}-${a.variant}`));if(u)throw new G(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${u.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=Ot(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return vu(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ne(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ne(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return Ot(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Go+Ne(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ct+(0,Vo.randomUUID)())}async evictHandle(e){let n=Ve(e);if(!n)return;let r=this.pool.get(n.app);if(!r)return;let o=await r.then(s=>s,()=>null);o!==null&&await this.evict(n.app,o)}async acquire(e,n){let r=this.pool.get(n);return r||(r=Promise.resolve(this.opts.openSession(e,n)),this.pool.set(n,r),r.then(o=>this.snapshotMintId(o),()=>{}),r.catch(()=>this.pool.delete(n))),{app:n,entry:await r,identity:Ot(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:Pt(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:Pt(n,this.keyOf(r))}}async sessionForHandle(e){let n=Ve(e);if(!n)throw new J(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(u=>u,()=>null):null;if(i===null)throw new J(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o&&this.mintedIds.get(i)!==o)throw new J(`the session behind this handle (app "${r}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:r,entry:i}}async evict(e,n){let r=this.pool.get(e);!r||await r.then(s=>s,()=>null)!==n||this.pool.get(e)!==r||(this.pool.delete(e),await this.opts.closeSession(n).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),n=await this.sharedBlock(),[r,o]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:Et;r.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
|
|
7
|
+
`);let a=(n?st(n):[]).map(l=>{let d=s.filter(S=>S.model_id===l.model_id&&S.variant===l.variant),c=on(d),p=it(d),m=rr(d),h=Rt(l.model_id,l.variant,i),v=sr(d);return Ge({id:`${l.model_id}:${l.variant}`,object:"model",created:p,owned_by:"urun",...c!==null?{context_length:c}:{},...h!==null?{pricing:h}:{},...v.published.length>0?{voices:[...v.published]}:{},...m!==null?{capabilities:{reasoning:m}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>sn(l,s,i)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return qo(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=ir(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Ho(`${r.modelId}:${r.variant}`,s).includes(n)}return jo(ur(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:Le(Tt(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":Le(Tt(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?Le(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":Le(Tt(n,r))==="stt"}async transcriptStreamFor(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Tt(n,r);return xu(o)}async speechVoices(e){let n=await this.resolveTarget(e),r=await this.catalogRows(),o=n.sharedApp?r.filter(s=>s.model_id===n.modelId&&s.variant===n.variant):Tt(n,r);return sr(o)}async imageModelList(){let e=await this.catalogRows(),n=Et,r=[];for(let s of await this.availableIds()){let i=jo(ur(s,e));i.length!==0&&r.push(Ge({...sn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of st(o)){let i=ir(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),u=Ho(`${s.model_id}:${s.variant}`,i);if(u.length===0)continue;let a=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:it(i),owned_by:"urun",image_modes:u});r.push(a)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=Et,r=[];for(let s of await this.availableIds())Le(zo(s,e))==="stt"&&r.push(sn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of st(o)){let i=ir(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(Le(i)!=="stt")continue;let u=Ge({id:`${s.model_id}:${s.variant}`,object:"model",created:it(i),owned_by:"urun"});r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Ue=class extends Error{code;status;retryAfterSeconds;constructor(e,n,r,o){super(o),this.name="DecisionStreamFailure",this.code=e,this.status=n,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},$t=class extends Ue{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},lr=class extends Ue{constructor(e,n=!1){super("acquire_timeout",429,30,n?"no capacity available for this model right now \u2014 the request is being dispatched; retry shortly":"no capacity available for this model right now, retry in 30s")}},be=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},ln=class{slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;opts;constructor(e){if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.opts={...e},this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}get requestWaitMs(){return this.opts.warmWaitMs??2e4}retune(e){let n={min:e.min??this.opts.min,max:e.max??this.opts.max,inFlightCap:e.inFlightCap??this.opts.inFlightCap,warmWaitMs:e.warmWaitMs??this.opts.warmWaitMs},r=e.idleGraceMs??this.idleGraceMs;if(!Number.isInteger(n.min)||n.min<0)throw new Error("decision pool retune: min must be a non-negative integer");if(!Number.isInteger(n.max)||n.max<n.min||n.max<1)throw new Error("decision pool retune: max must be an integer >= min and >= 1");if(!Number.isInteger(n.inFlightCap)||n.inFlightCap<1)throw new Error("decision pool retune: inFlightCap must be an integer >= 1");if(r<0)throw new Error("decision pool retune: idleGraceMs must be >= 0");if(n.warmWaitMs!==void 0&&(!Number.isInteger(n.warmWaitMs)||n.warmWaitMs<=0))throw new Error("decision pool retune: warmWaitMs must be a positive integer");this.opts.min=n.min,this.opts.max=n.max,this.opts.inFlightCap=n.inFlightCap,this.opts.warmWaitMs=n.warmWaitMs,this.idleGraceMs=r,this.reap()}slotKey(e,n=0){let r=`decision:${this.opts.replicaId}:${e}`;return n===0?r:`${r}:${n}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(e){e||this.dropDeadSlots();let n=this.now(),r=this.slots.filter(o=>o.state==="paused"&&!o.opening&&(e||!o.dead)&&(!o.dead||n>=o.nextDialAt)).sort((o,s)=>o.slot.index-s.slot.index);return r.length>0?(this.openRuntime(r[0]),r[0]):this.ensureSlot()}dropDeadSlots(){for(let e=this.slots.length-1;e>=0;e--){let n=this.slots[e];n.dead&&!n.opening&&n.inFlight===0&&(n.backoffTimer&&(clearTimeout(n.backoffTimer),n.backoffTimer=void 0),this.slots.splice(e,1))}}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null,generation:0,dead:!1,rotations:0,nextDialAt:0,backoffTimer:void 0};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let n=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(n).catch(()=>{}),this.signalDrain();return}e.entry=n,e.state="attached",e.dead=!1,e.rotations=0,e.nextDialAt=0,e.backoffTimer&&(clearTimeout(e.backoffTimer),e.backoffTimer=void 0),e.idleSince=this.now(),this.pump()}catch(n){e.entry=null,e.opening=null,this.opts.terminalOpenFailure?.(n)?this.rotate(e,`open failed (terminal) \u2014 slot identity rotated: ${n instanceof Error?n.message:String(n)}`):(e.state="paused",this.opts.onDetach?.(e.slot,n instanceof Error?n.message:String(n))),this.pump();return}e.opening=null})())}async acquire(e){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t;this.lastDemandAt=this.now();let n=e?.timeoutMs??this.opts.acquireTimeoutMs??6e5,r=Date.now();for(;;){let o=this.tryLease();if(o)return this.pump(),o;if(this.draining)throw new $t;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),u=this.slots.some(c=>c.dead&&!c.opening&&this.now()>=c.nextDialAt);if(!s&&(i||u)&&this.slots.length<this.opts.max){this.openForDemand(!0);continue}let a=r+n-Date.now();if(a<=0)throw new lr(n,this.slots.some(c=>c.state==="queued"));let l,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{l=setTimeout(c,a)})])}finally{clearTimeout(l);let c=this.waiters.indexOf(d);c!==-1&&this.waiters.splice(c,1),d.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new $t}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let n=this.tryLease();if(n)return n;if(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max){let r=!this.slots.some(s=>s.state==="attached"),o=this.slots.some(s=>s.dead&&!s.opening&&this.now()>=s.nextDialAt);(r||o)&&this.openForDemand(!1)}return this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null}async pingReady(e){if(this.closed)return!1;for(let n=0;n<this.slots.length;n++){let r=this.slots[n];if(r.state!=="attached"||r.entry===null)continue;let o=r.entry;if(o===null||typeof o!="object"||!("session"in o))return!1;let s=o.session;if(typeof s!="object"||s===null||!("whenLive"in s))return!1;let i=s.whenLive;if(typeof i!="function")return!1;let u=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(u),r.entry!==null&&r.entry!==u&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}markSessionDead(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.opening=null,this.rotate(n,"session dead (terminal 410) \u2014 slot identity rotated"))}rotate(e,n){e.state="paused",e.dead=!0,e.generation+=1,e.slot={index:e.slot.index,concurrencyKey:this.slotKey(e.slot.index,e.generation)},e.rotations+=1;let r=e.rotations<=1?0:Math.min(6e4,2e3*2**(e.rotations-2));e.nextDialAt=this.now()+r,r>0&&(clearTimeout(e.backoffTimer),e.backoffTimer=setTimeout(()=>{e.backoffTimer=void 0,this.pump()},r)),this.opts.onDetach?.(e.slot,n),this.signalDrain()}reap(){if(this.closed||this.draining)return;let e=this.now(),n=this.slots.filter(s=>s.state==="attached"&&s.inFlight===0&&s.idleSince!==null&&e-s.idleSince>=this.idleGraceMs).sort((s,i)=>(s.idleSince??0)-(i.idleSince??0)||i.slot.index-s.slot.index),r=this.slots.filter(s=>s.state==="attached").length,o=Math.max(0,Math.min(n.length,r-this.opts.min));for(let s of n.slice(0,o))this.endSlot(s);this.maintainFloor()}maintainFloor(){if(this.closed||this.draining)return;let e=this.slots.filter(n=>n.state==="attached"||n.state==="queued").length;for(;e<this.opts.min&&this.slots.length<this.opts.max;)this.openForDemand(!0),e+=1}endSlot(e){e.state="paused";let n=e.entry;e.entry=null,clearTimeout(e.backoffTimer),e.backoffTimer=void 0,this.slots.splice(this.slots.indexOf(e),1),n&&this.opts.closeSlot(n).catch(()=>{})}stats(){let e=this.slots.filter(o=>o.state==="attached").length,n=this.slots.filter(o=>o.state==="queued").length,r=this.slots.filter(o=>o.state==="paused").length;return{requested:this.slots.length,attached:e,queued:n,paused:r,inFlight:this.slots.reduce((o,s)=>o+s.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,n)=>e+n.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let n of this.waiters.splice(0))n.settled||(n.settled=!0,n.resolve());if(this.slots.reduce((n,r)=>n+r.inFlight,0)>0){if(!this.drainComplete){let r,o=new Promise(s=>{r=s});this.drainComplete={promise:o,resolve:r}}let n=this.drainComplete;await Promise.race([n.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let o of this.waiters.splice(0))o.settled||(o.settled=!0,o.resolve());let e=this.slots.map(o=>o.entry).filter(o=>o!==null);for(let o of this.slots)clearTimeout(o.backoffTimer),o.backoffTimer=void 0;this.slots.length=0;let r=(await Promise.allSettled(e.map(o=>this.opts.closeSlot(o)))).filter(o=>o.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};var dr=require("@urun-sh/core"),Se=class extends Error{kind;code;retryable;constructor(e,n,r,o){super(n),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=o,Object.setPrototypeOf(this,new.target.prototype)}},cn=33e4;function Yo(t,e=cn){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((l,d)=>{o=d}),i=setTimeout(()=>o(new dn),e),u;try{u=await Promise.race([r.next(),s])}catch(l){throw l instanceof J||l instanceof dr.SessionFailedError&&l.kind==="transport-failed"?l:l instanceof dn?(await r.return?.(void 0),new Se("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new Se("upstream_threw",`decision stream failed: ${String(l instanceof Error?l.message:l)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(u.done)return;let a=u.value;if(typeof a=="object"&&a!==null&&"type"in a&&a.type==="error")throw new Se("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield a}})()}var dn=class extends Error{constructor(){super("stream idle timeout")}};function Xo(t){return t instanceof Se?!1:t instanceof J?!0:t instanceof dr.SessionFailedError?t.kind==="transport-failed":!1}var Ru=require("http");var pn=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds};var cr=require("@urun-sh/core"),Eu="audio";function Qo(t){let e=t.streamEndpoint(Eu);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,cr.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,cr.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var Zo=require("@urun-sh/core"),Au="rt-video-in";function es(t){let e=t.streamEndpoint(Au);return{sendInputFrame:async n=>{e.send((0,Zo.encodeStreamEnvelope)(n))}}}var Iu=3,Tu="llm",Ou=new Set(["paused","error"]);function ts(t,e,n){let r=t.doc(Tu),o=typeof r.onConnectionState=="function",s=typeof t.onPhase=="function";if(!o&&!s)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let i=null,u=!1,a=new Set,l=[],d=c=>{if(!i){i=c;for(let p of[...a])p(c);a.clear()}};return o&&l.push(r.onConnectionState(c=>{u&&(c.consecutiveFailures<Iu||d(new J(`the pooled session for app "${e}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),n?.armOnFirstSync===!0&&typeof r.onSynced=="function"?l.push(r.onSynced(()=>{u=!0})):s&&l.push(t.onPhase(c=>{if(c.name==="live"){u=!0;return}u&&Ou.has(c.name)&&d(new J(`the pooled session for app "${e}" lost its compute binding (phase "${c.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`,{bindingLost:!0}))})),{gone:()=>i,onGone(c){return i?(c(i),()=>{}):(a.add(c),()=>a.delete(c))},dispose(){a.clear();for(let c of l.splice(0))c()}}}async function*pr(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,u)=>{o=e.onGone(a=>u(a))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}var Cu=0,$u=4,Mu=4;function rs(t,e){let n=(i,u)=>{let a=(t[i]??"").trim();if(!a)return u;let l=Number.parseInt(a,10);if(!Number.isInteger(l)||l<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return l},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Cu;if(!Number.isInteger(o)||o<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(t.URUN_DECISION_POOL_MIN)})`);let s=n("URUN_DECISION_POOL_MAX",Math.max(o,$u));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Mu),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function os(t){let e=(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!e)return cn;let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(t.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return n*1e3}function fr(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 ss(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,u=e.fnName??t.fnName,a=t.sessionStartOptions?.(n),l=r||a||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...a,...r}:void 0,d=v=>({session:v,responses:new St(v),gone:ts(v,n)});if(i.lane==="jwt"){let v=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(fr(v,e.appSlug,u,l))}if(i.lane==="machine"||i.lane==="user"){let v=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:k}=i,S=(typeof t.subject=="function"?t.subject():t.subject)??(0,mr.randomUUID)(),w=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(v,{baseUrl:k,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:S,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(fr(w,e.appSlug,u,l))}let{apiKey:c,gatewayUrl:p}=i,m=(typeof t.subject=="function"?t.subject():t.subject)??(0,mr.randomUUID)(),h=(0,oe.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,oe.createClientToken)(c,{baseUrl:p,expiresIn:300,allowedFunctions:[`${e.appSlug}/${u}`],subject:m,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(fr(h,e.appSlug,u,l))}function is(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 gr(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 Lu=new Set(["error","paused"]);function as(t){let{auth:e,catalog:n}=t,r=null,o=(i,u)=>{let a=ss(t,i,u);return t.onSessionOpen&&typeof a.session.id=="string"&&a.session.id!==""&&t.onSessionOpen(u,a.session.id),a.gone.onGone(()=>{r?.evict(u,a)}),a},s=new un({sharedOnlyListing:t.sharedOnlyListing===!0,defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),i.audioDispose?.(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>Wo({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>wo(n):null),listPrices:n?()=>Po(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return Co(i)}:e.lane==="api-key"?()=>$o({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:is});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ne({appSlug:t.defaultApp}))),s}function us(t,e){let n=t.decisionPool;if(!n)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let r=n.replicaId??"proxy",o=new Map,s=new Map,i=new Map,u=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
8
|
+
`)},a=(d,c)=>{let p=o.get(c);if(p)return p;let m=new ln({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async h=>{let v=ss(t,d,c,{concurrencyKey:h.concurrencyKey});return v.gone.onGone(k=>k.bindingLost?m.evict(v):m.markSessionDead(v)),await mn(v.session),u(`slot attached pool=${c} slot=${h.concurrencyKey} session=${v.session.id??"(no id)"}`),v},closeSlot:async h=>{h.gone.dispose(),h.audioDispose?.(),await h.session.end()},onDetach:(h,v)=>u(`slot detached pool=${c} slot=${h.concurrencyKey} reason=${v}`),terminalOpenFailure:h=>h instanceof oe.SessionFailedError&&gr(h)});return s.set(c,{target:d,env:n}),o.set(c,m),m},l=async(d,c)=>{let p=s.get(c);if(p)try{let m=await e.poolTuningFor(d);a(d,c).retune({min:m?.min??p.env.min,max:m?.max??p.env.max,inFlightCap:m?.in_flight_cap??p.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){u(`pool tuning refresh failed pool=${c} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await a(d,Ne(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),p=Ne(c),m=a(c,p);await l(c,p);let h=await m.acquire({timeoutMs:m.requestWaitMs}),v=i.get(h.entry)??[];return v.push(h),i.set(h.entry,v),{app:p,entry:h.entry,identity:Ot(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await a(c,Ne(c)).boot()},end(d){let c=i.get(d)?.shift();c&&(i.get(d)?.length===0&&i.delete(d),c.release())},evict(d){for(let c of o.values())c.evict(d)},markSessionDead(d){for(let c of o.values())c.markSessionDead(d)},reap(){for(let[d,{target:c}]of s)l(c,d).then(()=>{let p=o.get(d);p&&p.reap()})},async pingReady(d){for(let c of o.values())if(await c.pingReady(d))return!0;return!1},stats(){return[...o.entries()].map(([d,c])=>({poolKey:d,...c.stats()}))},async drain(d){await Promise.all([...o.values()].map(c=>c.drain({timeoutMs:d})))},async close(){await Promise.all([...o.values()].map(d=>d.close()))}}}function Nu(t){return(0,oe.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS:oe.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:oe.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function mn(t,e){let n=t.whenLive;if(typeof n!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await n.call(t,{timeout:Nu(t.phase),signal:e})}async function Uu(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}async function ns(t){let e=t.phase?.name;if(e==="live"||e==="paused"){if(typeof t.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");t.detach();return}if(typeof t.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await t.end()}function fn(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function ls(t,e=nn,n,r,o=cn,s){let i=new WeakMap,u=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=f=>{let g=f.session.id;return typeof g=="string"&&g.length>0?g:null},p="lane",m=f=>{let g=Ve(f);if(!s||!g||g.app!==p)return null;let y=s.entryFor(g.key);if(!y)throw new J(`the lane behind this handle (${g.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:g.key,entry:y}},h=async f=>m(f)?.entry??(await t.sessionForHandle(f)).entry,v=f=>{let g=i.get(f);if(!g){let y={waiting:0,gone:new AbortController};d.set(f,y),g=(async()=>{if(await mn(f.session,y.gone.signal),y.gone.signal.aborted)throw fn(y.gone.signal);d.get(f)===y&&d.delete(f);let b=await yo(f.session,await e());return Object.assign(b,{sessionId:f.session.id})})(),i.set(f,g),g.then(b=>{i.get(f)===g&&(f.audioDispose=()=>b.dispose())},()=>{}),g.catch(()=>{i.get(f)===g&&i.delete(f)}),g.then(()=>{d.get(f)===y&&d.delete(f)},()=>{d.get(f)===y&&d.delete(f)})}return g},k=f=>{let g=l.get(f);return g||(g=(async()=>{let y=await v(f);return{appendInputAudio:(b,x)=>y.appendInputAudio(b,x),onOutputAudio:b=>y.onOutputAudio(b),sessionId:c(f)}})(),l.set(f,g),g.catch(()=>{l.get(f)===g&&l.delete(f)})),g},S=async(f,g,y,b=!1)=>{let x=()=>b?ns(f.session):Uu(f.session);if(y?.aborted){let _=d.get(f);throw(i.get(f)===void 0||_!==void 0&&_.waiting===0)&&await x().catch(()=>{}),fn(y)}let A=g(f),E=d.get(f);return E!==void 0&&E.waiting++,y===void 0?A:new Promise((_,R)=>{let T=()=>{E!==void 0&&--E.waiting===0&&d.get(f)===E&&(E.gone.abort(),d.delete(f),i.delete(f),l.delete(f),x().catch(()=>{})),R(fn(y))};y.addEventListener("abort",T,{once:!0});let $=()=>y.removeEventListener("abort",T);A.then(P=>{$(),_(P)},P=>{$(),R(P)})})},w=async(f,g,y)=>{try{return await y}catch(b){throw(b instanceof J||b instanceof oe.SessionFailedError&&gr(b))&&(t.evict(f,g),b instanceof oe.SessionFailedError&&n?.(f,b.kind==="never-live"?"never-live":"create-failed")),b}};return{createResponse:Eo({sessionFor:s?async f=>{let g=await t.resolveTargetFor(f);if(g.sharedApp)try{let y=await s.sessionFor(f,g);return{app:y.app,entry:y.entry,identity:y.identity}}catch(y){if(y instanceof Zt)return r?r.sessionFor(f):t.sessionFor(f);if(y instanceof pn)return console.error(`[pooler-fallback] pooler channel failed for ${f} (${y.name} ${y.code}: ${y.message}) \u2014 serving via the per-request path`),r?r.sessionFor(f):t.sessionFor(f);throw y}return r?r.sessionFor(f):t.sessionFor(f)}:r?f=>r.sessionFor(f):f=>t.sessionFor(f),sessionIdOf:f=>c(f),evict:(f,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(f,g)},onAdmissionVerdict:(f,g,y)=>{gr(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(f,g),n?.(f,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(f,g)=>{try{await mn(f.session);let y=Yo(pr(await f.responses.responses.create(g),f.gone),o);if(!r&&!s)return y;let b=f;return(async function*(){try{yield*y}catch(A){throw Xo(A)&&(s&&s.owns(b)?s.evict(b):r&&(A instanceof J&&!A.bindingLost?r.markSessionDead(b):r.evict(b))),A}finally{s&&s.owns(b)?s.release(b):r?.end(b)}})()}catch(y){throw s&&s.owns(f)?s.release(f):r&&r.end(f),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(f,g)=>t.supportsImages(f,g),listImageModels:()=>t.imageModelList(),catalogIdentity:f=>t.catalogIdentityFor(f),servingAppSlug:async f=>await t.servingAppSlugFor(f),supportsAudio:f=>t.supportsAudio(f),supportsSpeech:f=>t.supportsSpeech(f),speechVoices:f=>t.speechVoices(f),supportsTranscription:f=>t.supportsTranscription(f),transcriptStreamFor:f=>t.transcriptStreamFor(f),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(f,g)=>{let{app:y,entry:b}=await t.sessionFor(f);return await w(y,b,S(b,v,g))},openAudioOn:async(f,g,y,b)=>{let x=m(f);if(x){let R=x.entry.session;return Qo(R)}let{app:A,entry:E}=await t.sessionForHandle(f);if(b&&E.session.phase?.name!=="live"){let R=E.session.phase?.name;b({status:R==="queued"||R==="waiting_for_capacity"?R:"pending",reason:`the dial's session is ${R??"not yet admitted"} \u2014 the connection waits for admission`})}let _=Ve(f)?.app.startsWith(Ct)??!1;return await w(A,E,S(E,k,g,_))},openTurnsOn:async function*(f,g){if(g?.aborted)throw fn(g);let y=await h(f);yield*xo(y.session,g)},openVideoOn:async f=>{let g=m(f);if(g)return es(g.entry.session);let{entry:y}=await t.sessionForHandle(f),b=u.get(y);return b||(b=Yn(y.session),u.set(y,b)),b},openVideo:async f=>{let{entry:g}=await t.sessionFor(f),y=u.get(g);return y||(y=Yn(g.session),u.set(g,y)),y},openVideoOut:async f=>{let{entry:g}=await t.sessionFor(f),y=a.get(g);return y||(y=vo(g.session),a.set(g,y)),y},sessionHandle:async f=>{if(s){let g=await t.resolveTargetFor(f);if(g.sharedApp){let y=await s.sessionFor(f,g),b=c(y.entry);if(b===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return Pt(p,b)}}return(await t.handleFor(f)).handle},dedicatedSessionHandle:async f=>{if(!(await t.resolveTargetFor(f)).sharedApp)return(await t.handleFor(f)).handle;let{app:y,entry:b}=await t.dedicatedSessionFor(f);return Pt(y,is(b))},releaseSessionHandle:f=>{let g=Ve(f);if(!g)return;if(g.app.startsWith(Ct)){(async()=>{let b=null;try{b=(await t.sessionForHandle(f)).entry}catch{return}await ns(b.session).catch(()=>{}),await t.evict(g.app,b)})();return}if(!s||g.app!==p)return;let y=s.entryFor(g.key);y&&s.release(y)},endDedicatedSession:async f=>{let g=Ve(f);if(!g||!g.app.startsWith(Ct))return;let y=null;try{y=(await t.sessionForHandle(f)).entry}catch{return}if(typeof y.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");await y.session.end().catch(()=>{}),await t.evict(g.app,y)},speechSessionHandle:async f=>(await t.speechHandleFor(f)).handle,evictSpeechSession:async f=>{let{app:g,entry:y}=await t.sessionForHandle(f);await t.evict(g,y)},createResponseOn:async(f,g,y)=>{let b=await h(f);await mn(b.session);let x=y!==void 0&&m(f)?new St({...b.session,consumerId:y},{sessionTag:y}):b.responses;return pr(await x.responses.create(g),b.gone)},onSessionEnd:async(f,g)=>{let y=m(f);if(y)return y.entry.gone.onGone(E=>g({timeLeftMs:null,reason:E.message}));let{entry:b}=await t.sessionForHandle(f),x=b.session;if(typeof x.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let A=!1;return x.onPhase(E=>{if(A||!Lu.has(E.name))return;A=!0;let _=x.endsAt??null;g({timeLeftMs:_?Math.max(0,_.getTime()-Date.now()):null,reason:E.reason??`session ${E.name}`})})}}}var wa=require("http");var Is=require("crypto"),Ts=require("ws");var cs="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Du=1007,ps=1008,Pe=1011,wn=1008,I=class extends Error{constructor(n,r=Du){super(n);this.closeCode=r}closeCode},te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,gn=["setup","clientContent","realtimeInput","toolResponse"];function fs(t){let e;try{e=JSON.parse(t)}catch{throw new I("client message is not valid JSON")}let n=te(e);if(!n)throw new I("client message must be a JSON object");let r=gn.filter(u=>n[u]!==void 0),o=Object.keys(n).filter(u=>!gn.includes(u));if(o.length>0)throw new I(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${gn.join(", ")}`);if(r.length!==1)throw new I(`client message must contain exactly one of ${gn.join(", ")} (got ${r.length})`);let s=r[0],i=te(n[s]);if(!i)throw new I(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ms(t,e){if(typeof t=="string")return t;let n=te(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new I(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=te(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new I(`${e}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):i&&(i.functionCall!==void 0||i.functionResponse!==void 0)?new I(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new I(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
9
|
+
`)}var Fu={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},We="urun.videoOut";function gs(t){return{framing:_o,codec:t}}function hs(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[We]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Bu={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},qu=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",We],ds=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ju(t){let e=te(t);if(!e)throw new I("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new I(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=te(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new I("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new I(`automaticActivityDetection.${o} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(n?.disabled!==!0)throw new I("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let r="START_OF_ACTIVITY_INTERRUPTS";if(e.activityHandling!==void 0){if(!ds.includes(e.activityHandling))throw new I(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ds.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var Hu=["temperature","maxOutputTokens","responseModalities"];function ys(t){for(let[c,p]of Object.entries(Bu))if(t[c]!==void 0)throw new I(p);for(let c of Object.keys(t))if(!qu.includes(c))throw new I(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new I('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=te(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new I("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!Hu.includes(c))throw new I(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new I("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new I("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let p of c){let m=String(p).toUpperCase();if(m==="AUDIO"){o=!0;continue}if(m!=="TEXT")throw new I(`responseModalities ${JSON.stringify(p)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:ms(t.systemInstruction,"setup.systemInstruction")});let u;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new I("setup.tools must be an array");u=[];for(let c of t.tools){let p=te(c);if(!p)throw new I("setup.tools entries must be objects");for(let m of Object.keys(p))if(m!=="functionDeclarations")throw new I(`unsupported tool "${m}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(p.functionDeclarations))throw new I("tool.functionDeclarations must be an array");for(let m of p.functionDeclarations){let h=te(m);if(!h||typeof h.name!="string")throw new I("functionDeclarations entries require a string name");u.push({type:"function",name:h.name,description:h.description,parameters:h.parameters})}}u.length===0&&(u=void 0)}let a={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=te(t.sessionResumption);if(!c)throw new I("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let p of Object.keys(c))if(p!=="handle")throw new I(`unsupported sessionResumption field "${p}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new I("sessionResumption.handle must be a non-empty string when present");a={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let l=t.realtimeInputConfig===void 0?Fu:ju(t.realtimeInputConfig),d=!1;if(t[We]!==void 0){if(!te(t[We]))throw new I(`setup["${We}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:u,temperature:n,maxOutputTokens:r,audioModality:o,activity:l,sessionResumption:a,videoOut:d}}function ws(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function _s(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function vs(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new I(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new I("clientContent.turns must be an array");let n=[];for(let r of e){let o=te(r);if(!o)throw new I("clientContent.turns entries must be Content objects");let s=o.role===void 0?"user":String(o.role).toLowerCase();if(s!=="user"&&s!=="model")throw new I(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:ms(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var hn=16e3,bs=24e3,Gu=`audio/pcm;rate=${bs}`,Ss=Buffer.alloc(960).toString("base64");function Vu(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let u=0;u<r;u++){let a=u*s,l=Math.floor(a);if(l>=i){o[u]=t[i];continue}let d=a-l;o[u]=Math.round(t[l]+(t[l+1]-t[l])*d)}return o}function Ju(t){let e=te(t);if(!e)throw new I("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(e.mimeType)}`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.video.data must be non-empty base64");let n=Buffer.from(e.data,"base64");if(n.length<3||n[0]!==255||n[1]!==216)throw new I("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function Wu(t){let e=te(t);if(!e)throw new I("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new I(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(e.mimeType)}`);let n=/;\s*rate=(\d+)/.exec(e.mimeType);if(n&&Number(n[1])!==hn)throw new I(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${hn} Hz (audio/pcm;rate=${hn})`);if(typeof e.data!="string"||e.data.length===0)throw new I("realtimeInput.audio.data must be non-empty base64");let r=Buffer.from(e.data,"base64");if(r.length===0||r.length%2!==0)throw new I(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${r.length} bytes \u2014 not even)`);let o=new Int16Array(r.length/2);for(let i=0;i<o.length;i++)o[i]=r.readInt16LE(i*2);let s=Vu(o,hn,bs);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function ks(t){if(t.mediaChunks!==void 0)throw new I('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(t.activityStart!==void 0||t.activityEnd!==void 0){if(Object.keys(t).length!==1||t.activityStart!==void 0&&t.activityEnd!==void 0)throw new I("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=te(t[o]);if(!s||Object.keys(s).length!==0)throw new I(`realtimeInput.${o} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:o}}let e=["text","audio","audioStreamEnd","video"];for(let r of Object.keys(t))if(!e.includes(r))throw new I(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new I(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:Wu(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:Ju(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new I("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new I("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function xs(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new I(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new I("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=te(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new I("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:n.id,output:JSON.stringify(n.response??null)}})}function Rs(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function Es(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:Gu,data:t}}]}}}}function As(t){let e=te(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let l of n){let d=te(l);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let p=te(c);p?.type==="output_text"&&typeof p.text=="string"&&(s+=p.text)}}s&&o.push({role:"assistant",content:s});for(let l of n){let d=te(l);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new I(`upstream function_call item is missing call_id/name: ${JSON.stringify(l)}`,Pe);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",p;try{p=JSON.parse(c)}catch{throw new I(`upstream function_call arguments are not valid JSON: ${c}`,Pe)}r.push({id:d.call_id,name:d.name,args:p}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let u=te(e.usage),a={serverContent:{turnComplete:!0}};if(u){let l={};typeof u.input_tokens=="number"&&(l.promptTokenCount=u.input_tokens),typeof u.output_tokens=="number"&&(l.responseTokenCount=u.output_tokens),typeof u.total_tokens=="number"&&(l.totalTokenCount=u.total_tokens),Object.keys(l).length>0&&(a.usageMetadata=l)}return i.push(a),{messages:i,assistantItems:o}}var Ku=256,hr=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Ku;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},zu="local",Mt=t=>t.slice(0,120),yr=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 G){this.ws.close(ps,Mt(e.message));return}if(e instanceof J){this.ws.close(wn,Mt(e.message));return}if(e instanceof I){this.ws.close(e.closeCode,Mt(e.message));return}this.ws.close(Pe,Mt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=fs(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(n.kind==="setup"){this.handleSetup(n.setup).catch(o=>this.fail(o));return}if(!this.config)throw new I(`"${n.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(n.kind==="clientContent"){let{items:o,turnComplete:s}=vs(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=ks(n.realtimeInput);if(o.kind==="activityStart"||o.kind==="activityEnd"){this.onActivity(o.kind,r);return}if(o.kind==="text"){this.transcript.push({role:"user",content:o.text}),this.enqueue(()=>this.runTurn());return}if(o.kind==="video"){this.appendVideoFrame(o.jpegFrame);return}this.appendAudio(o.kind==="audio"?o.base64Pcm24k:Ss);return}this.transcript.push(...xs(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new I("setup may only be sent once, as the first client message");let n=ys(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new I("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",wn);if(s.model!==n.model)throw new I(`sessionResumption.handle was issued for model "${s.model}" \u2014 the model cannot change on resume (got "${n.model}", per the Live API session-resumption contract)`);if(n.systemItems.length>0)throw new I("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(n.model),this.proxyHandle!==s.proxyHandle)throw new I(`sessionResumption.handle named pooled session "${s.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,wn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),u=i.onOutputFrame(l=>this.send(hs(l))),a=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{u(),a()},o[We]=gs(i.codec)}}this.send({setupComplete:o}),n.audioModality&&this.ensureAudioLane(),n.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new I("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new I("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Pe);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(Es(o))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(n=>n.appendInputAudio(e)).catch(n=>this.fail(n))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new I("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new I("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Pe);return this.video=Promise.resolve(n.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(n=>n.sendInputFrame(e)).catch(n=>this.fail(n))}onActivity(e,n){if(!n.activity.manualActivity)throw new I(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new I("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,n.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new I("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,Is.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ws(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(_s(e.timeLeftMs)),this.ws.close(Pe,Mt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let a of r){if(n.interrupted)break;let l=a;if(l.type==="error")throw new I(`upstream error: ${JSON.stringify(l)}`,Pe);if(l.type==="response.completed"){o=l.response,s=!0;continue}let d=Rs(l);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new I("upstream produced no response.completed event",Pe);let{messages:i,assistantItems:u}=As(o);this.transcript.push(...u);for(let a of i)this.send(a);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Ke=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Yu(t,e,n){let r=new Set;(a=>{if(typeof a=="string")a!==""&&r.add(a);else if(Array.isArray(a))for(let l of a)l!==""&&r.add(l)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Ke(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new Ke(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let u;for(let a of r)u=a;if(u===void 0&&n)throw new Ke(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return u??""}function Os(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 Ts.WebSocketServer({noServer:!0}),o=new hr;t.on("upgrade",(i,u,a)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===cs&&(u.on("error",()=>{}),(async()=>{let d=Yu(i,l,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Ke(401,"invalid local proxy api key");c={clients:e.clients,scope:zu}}r.handleUpgrade(i,u,a,p=>{new yr(p,c,o)})})().catch(d=>{let c=502;(d instanceof Ke||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);u.destroyed||(u.write(`HTTP/1.1 ${c} ${p}\r
|
|
10
10
|
Connection: close\r
|
|
11
11
|
\r
|
|
12
12
|
${m}\r
|
|
13
|
-
`),u.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,u)=>r.close(a=>a===void 0?i():u(a)))})(),s)}var Fe=require("ws");var
|
|
14
|
-
`}var Yu=256,Xu=128;function ue(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Xu)}var Ke=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>=Yu?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,u=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Qu=256;function Zu(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 ze=class extends Error{},at=class{conversations=new Map;thread(e,n){let r=Zu(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new ze(`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<=Qu)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Ls=new WeakMap;function Lt(t){let e=Ls.get(t);return e||(e=new at,Ls.set(t,e)),e}function ut(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Oe(t){return t.find(e=>e.type==="response.completed")?.response??null}function lt(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var De=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},el=["<tool_call>","<function="];function tl(t){return el.find(e=>t.includes(e))}function Ye(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 Xe(t,e,n){if(!(!t||e>0))return tl(n)}function dt(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ce(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function nl(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 _r(t,e){let n=nl(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ye=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function ct(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof ze?new ye(n.message,"previous_response_not_found",400,"previous_response_id"):new ye(String(n instanceof Error?n.message:n),"invalid_input")}}function Ns(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function vr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ye("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...Ns(e)!==void 0?{response_format:Ns(e)}:{}},o)}async function Nt(t){let{body:e,clients:n,store:r,stats:o}=t,s=ct(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ue(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await vr(n,e,s,!0,c?he(c):void 0);return{responseId:i,events:il({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function rl(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?sl(o[i++],a):a),...ol(r,n)]}function ol(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function sl(t,e){let n=u=>u!==null&&typeof u=="object"&&u.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(u=>n(u)?{...u,text:s.text}:u),i}async function*il(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=M=>M.response&&typeof M.response=="object"?{...M,response:{...M.response,id:r}}:M,p=`item_${r.slice(5)}`,m=!1,g=!1,v=0;function*x(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let S=[],w=(M,H)=>{S.push({output_index:M,item:H})},f=!1,h=0,y="",b=0,E="";function*I(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:h,content_index:0,text:E};let M={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:E}],status:"completed"};yield{type:"response.output_item.done",output_index:h,item:M},w(h,M),E=""}let O=!1,_=0,R="",k=0,C="",N="";function*j(M){if(!O)return;O=!1,yield{type:"response.output_text.done",item_id:R,output_index:_,content_index:0,text:C},yield{type:"response.content_part.done",item_id:R,output_index:_,content_index:0,part:{type:"output_text",text:C}};let H={id:R,type:"message",role:"assistant",status:M,content:[{type:"output_text",text:C}]};yield{type:"response.output_item.done",output_index:_,item:H},w(_,H),C=""}let U=new De,D=null,oe=-1;function*J(M){if(!D)return;let H=D;D=null,yield{type:"response.function_call_arguments.done",item_id:H.fcId,output_index:H.outputIndex,arguments:H.args};let z={id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:H.args,status:M};yield{type:"response.output_item.done",output_index:H.outputIndex,item:z},w(H.outputIndex,z)}let ne=!1;for await(let M of l.track(e,o,t.turn)){d.push(M);let H=String(M.type??"");if(H==="response.created"||H==="response.in_progress"){m=!0,yield c(M);continue}if(H==="response.output_item.added"){g=!0,yield c(M);continue}if(H==="response.reasoning_text.delta"&&!g){yield*x(),f||(f=!0,h=v++,b+=1,y=b===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${b}`,yield{type:"response.output_item.added",output_index:h,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),E+=String(M.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:h,content_index:0,delta:M.delta};continue}if(H==="response.output_text.delta"&&!g){yield*x(),yield*I(),O||(O=!0,_=v++,k+=1,R=k===1?p:`${p}_${k}`,yield{type:"response.output_item.added",output_index:_,item:{id:R,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:R,output_index:_,content_index:0,part:{type:"output_text",text:""}}),C+=String(M.delta??""),N+=String(M.delta??""),yield{type:H,item_id:R,output_index:_,content_index:0,delta:M.delta};continue}let z=g?null:lt(M);if(z){if(yield*x(),yield*I(),yield*j("completed"),U.add(z),z.tool_index!==oe){yield*J("completed"),oe=z.tool_index;let qe=v++;D={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:qe,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:qe,item:{id:D.fcId,type:"function_call",call_id:D.callId??D.fcId,name:D.name??"",arguments:"",status:"in_progress"}}}D&&(z.call_id&&(D.callId=z.call_id),z.name&&(D.name=z.name),D.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:D.fcId,output_index:D.outputIndex,delta:z.delta});continue}if(H==="response.completed"&&!g){let qe=ut(M.response),tt=Xe(s,U.size+qe.length,N);if(tt){ne=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Ye(o,tt)}};break}if(yield*I(),yield*j("completed"),yield*J("completed"),U.size===0)for(let ee of qe){let ve=v++,He=ee.id??ee.call_id??`fc_${ve}`,Vn=ee.arguments??"",no={id:He,type:"function_call",call_id:ee.call_id??He,name:ee.name??""};yield{type:"response.output_item.added",output_index:ve,item:{...no,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:He,output_index:ve,delta:Vn},yield{type:"response.function_call_arguments.done",item_id:He,output_index:ve,arguments:Vn};let ro={...no,arguments:Vn,status:"completed"};yield{type:"response.output_item.done",output_index:ve,item:ro},w(ve,ro)}let Y=rl(S,M.response);yield Y.length>0?c({...M,response:{...M.response,output:Y}}):c(M);continue}yield c(M)}if(yield*I(),yield*j("incomplete"),yield*J("incomplete"),i&&!ne){let M=Oe(d);a.remember(r,n,_r(M,dt(d,M)),u)}}var al=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ke(t){return!al.some(e=>e.test(t))}function xe(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function fe(t,e){if(t instanceof V)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=Us(t);return n||{message:xe(e?.inferenceId??null),redacted:!0}}function Us(t){return t instanceof Me?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof X?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof G?{message:t.message,redacted:!1}:t instanceof Ie?{message:t.message,redacted:!1}:t instanceof Ue?{message:t.message,redacted:!1}:t instanceof Se?ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof be?{message:t.message,redacted:!1}:t instanceof ce?{message:t.message,redacted:!1}:null}function pt(t,e,n){let r=n??(i=>console.error(i)),o=Us(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed while serving this request`)}function Te(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ke(e)?e:null}function we(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var ul="/v1/responses",ll=64*1024*1024,dl=8*1024*1024,cl=16,Ds=32,Fs=3600*1e3,pl=/^[A-Za-z0-9._-]{1,256}$/;function le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var fl=le(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function kr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function ml(t){for(;t.bufferedAmount>dl&&t.readyState===Fe.WebSocket.OPEN;){let{promise:e,resolve:n}=kr();setTimeout(n,5),await e}}var br=class extends at{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 ze))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Sr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new br(Lt(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${Fs/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},Fs).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(le(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(le(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(le(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(le(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!pl.test(o.stream_id)){this.sendFrame(fl);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=Ds){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${Ds}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=$t();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Nt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Mt(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await ml(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=$t(),o=Mt(r);try{let s=ct(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:we(e);if(e instanceof ye)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof G)return le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof V){let u=fe(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),le(s.status,{type:s.openaiType,message:o},n);let i=fe(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Te(o),u=i??xe(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=cl;){let{promise:e,resolve:n}=kr();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Fe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function wn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
13
|
+
`),u.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,u)=>r.close(a=>a===void 0?i():u(a)))})(),s)}var Fe=require("ws");var Ps=require("crypto"),Cs="Inference-Id";function Lt(){return(0,Ps.randomUUID)()}function wr(t){return t==="/v1"||t.startsWith("/v1/")}function $s(t,e){if(!wr(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 Nt(t){return`resp_${t}`}function Ms(t){return`chatcmpl-${t}`}function Ls(t){return`msg_${t}`}function he(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Ns(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,output_minutes:t.turn.outputMinutes,output_seconds:t.turn.outputSeconds??null,session_seconds:null,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,...t.turn.decision?{decision_resolve_ms:t.turn.decision.resolve_ms,decision_dial_ms:t.turn.decision.dial_ms,decision_first_event_ms:t.turn.decision.first_event_ms,decision_stream_ms:t.turn.decision.stream_ms,decision_question_fwd_ms:t.turn.decision.question_fwd_ms,decision_head_ms:t.turn.decision.head_ms}:{},catalog:t.turn.catalog}}function Us(t){return`${JSON.stringify(t)}
|
|
14
|
+
`}var Xu=256,Qu=128;function ue(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Qu)}var ze=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(e,n,r){this.requests[e]=(this.requests[e]??0)+1,this.localInBytes+=n,this.naiveInBytes+=r}modelEntry(e){let n=this.models[e];if(n)return n;let r=Object.keys(this.models).length>=Xu?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,u=0;return(async function*(){for await(let l of e)l.type==="response.output_text.delta"&&typeof l.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),u+=1,o.tokensOut+=1,o.charsOut+=l.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield l;let a=(performance.now()-(i??s))/1e3;u>0&&a>0&&(o.tokRates.push(u/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Zu=256;function el(t){if(typeof t=="string")return[{role:"user",content:t}];if(Array.isArray(t))return t;throw new Error("responses input must be a string or an array of messages/items")}var Ye=class extends Error{},at=class{conversations=new Map;thread(e,n){let r=el(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new Ye(`unknown previous_response_id ${String(e)} (proxy restarts drop stored responses)`);return[...o,...r]}remember(e,n,r,o=!0){this.conversations.set(e,[...n,...r]);for(let s of this.conversations.keys()){if(this.conversations.size<=Zu)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Ds=new WeakMap;function Ut(t){let e=Ds.get(t);return e||(e=new at,Ds.set(t,e)),e}function ut(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Te(t){return t.find(e=>e.type==="response.completed")?.response??null}function lt(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var De=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},tl=["<tool_call>","<function="];function nl(t){return tl.find(e=>t.includes(e))}function Xe(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function Qe(t,e,n){if(!(!t||e>0))return nl(n)}function dt(t,e){let n=e?.output_text;return typeof n=="string"?n:t.filter(r=>r.type==="response.output_text.delta"&&typeof r.delta=="string").map(r=>r.delta).join("")}function Ce(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function rl(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 _r(t,e){let n=rl(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ye=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function ct(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof Ye?new ye(n.message,"previous_response_not_found",400,"previous_response_id"):new ye(String(n instanceof Error?n.message:n),"invalid_input")}}function Fs(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function vr(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ye("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...Fs(e)!==void 0?{response_format:Fs(e)}:{}},o)}async function Dt(t){let{body:e,clients:n,store:r,stats:o}=t,s=ct(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,u=t.remember??e.store!==!1,a=e.store!==!1,l=ue(e);o.model(l);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,p=await vr(n,e,s,!0,c?he(c):void 0);return{responseId:i,events:al({events:p,conversation:s,responseId:i,modelKey:l,requestHadTools:d,remember:u,persist:a,store:r,stats:o,turn:t.turn})}}function ol(t,e){let n=[...t].sort((a,l)=>a.output_index-l.output_index).map(({item:a})=>a),r=Array.isArray(e?.output)?e.output:[],o=r.filter(a=>a!==null&&typeof a=="object"&&a.type==="message"),s=n.filter(a=>a.type==="message").length===o.length,i=0;return[...n.map(a=>a.type==="message"&&s?il(o[i++],a):a),...sl(r,n)]}function sl(t,e){let n=e.some(l=>l.type==="message"),r=e.some(l=>l.type==="reasoning"),o=l=>String(l.call_id??l.id??""),s=e.filter(l=>l.type==="function_call"),i=t.filter(l=>l!==null&&typeof l=="object"&&l.type==="function_call").length,u=s.length===i,a=new Set(s.map(o));return t.filter(l=>{if(l===null||typeof l!="object")return!0;let d=l;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!u&&!a.has(o(d)):!0})}function il(t,e){let n=u=>u!==null&&typeof u=="object"&&u.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(u=>n(u)?{...u,text:s.text}:u),i}async function*al(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:u,store:a,stats:l}=t,d=[],c=U=>U.response&&typeof U.response=="object"?{...U,response:{...U.response,id:r}}:U,p=`item_${r.slice(5)}`,m=!1,h=!1,v=0;function*k(){m||(m=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let S=[],w=(U,H)=>{S.push({output_index:U,item:H})},f=!1,g=0,y="",b=0,x="";function*A(){if(!f)return;f=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:x};let U={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:x}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:U},w(g,U),x=""}let E=!1,_=0,R="",T=0,$="",P="";function*B(U){if(!E)return;E=!1,yield{type:"response.output_text.done",item_id:R,output_index:_,content_index:0,text:$},yield{type:"response.content_part.done",item_id:R,output_index:_,content_index:0,part:{type:"output_text",text:$}};let H={id:R,type:"message",role:"assistant",status:U,content:[{type:"output_text",text:$}]};yield{type:"response.output_item.done",output_index:_,item:H},w(_,H),$=""}let L=new De,N=null,ne=-1;function*V(U){if(!N)return;let H=N;N=null,yield{type:"response.function_call_arguments.done",item_id:H.fcId,output_index:H.outputIndex,arguments:H.args};let z={id:H.fcId,type:"function_call",call_id:H.callId??H.fcId,name:H.name??"",arguments:H.args,status:U};yield{type:"response.output_item.done",output_index:H.outputIndex,item:z},w(H.outputIndex,z)}let re=!1;for await(let U of l.track(e,o,t.turn)){d.push(U);let H=String(U.type??"");if(H==="response.created"||H==="response.in_progress"){m=!0,yield c(U);continue}if(H==="response.output_item.added"){h=!0,yield c(U);continue}if(H==="response.reasoning_text.delta"&&!h){yield*k(),f||(f=!0,g=v++,b+=1,y=b===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${b}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),x+=String(U.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:U.delta};continue}if(H==="response.output_text.delta"&&!h){yield*k(),yield*A(),E||(E=!0,_=v++,T+=1,R=T===1?p:`${p}_${T}`,yield{type:"response.output_item.added",output_index:_,item:{id:R,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:R,output_index:_,content_index:0,part:{type:"output_text",text:""}}),$+=String(U.delta??""),P+=String(U.delta??""),yield{type:H,item_id:R,output_index:_,content_index:0,delta:U.delta};continue}let z=h?null:lt(U);if(z){if(yield*k(),yield*A(),yield*B("completed"),L.add(z),z.tool_index!==ne){yield*V("completed"),ne=z.tool_index;let je=v++;N={fcId:`fc_${r.slice(5)}_${z.tool_index}`,outputIndex:je,callId:z.call_id,name:z.name,args:""},yield{type:"response.output_item.added",output_index:je,item:{id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:"",status:"in_progress"}}}N&&(z.call_id&&(N.callId=z.call_id),z.name&&(N.name=z.name),N.args+=z.delta,yield{type:"response.function_call_arguments.delta",item_id:N.fcId,output_index:N.outputIndex,delta:z.delta});continue}if(H==="response.completed"&&!h){let je=ut(U.response),nt=Qe(s,L.size+je.length,P);if(nt){re=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(o,nt)}};break}if(yield*A(),yield*B("completed"),yield*V("completed"),L.size===0)for(let ee of je){let ve=v++,He=ee.id??ee.call_id??`fc_${ve}`,Vn=ee.arguments??"",oo={id:He,type:"function_call",call_id:ee.call_id??He,name:ee.name??""};yield{type:"response.output_item.added",output_index:ve,item:{...oo,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:He,output_index:ve,delta:Vn},yield{type:"response.function_call_arguments.done",item_id:He,output_index:ve,arguments:Vn};let so={...oo,arguments:Vn,status:"completed"};yield{type:"response.output_item.done",output_index:ve,item:so},w(ve,so)}let Y=ol(S,U.response);yield Y.length>0?c({...U,response:{...U.response,output:Y}}):c(U);continue}yield c(U)}if(yield*A(),yield*B("incomplete"),yield*V("incomplete"),i&&!re){let U=Te(d);a.remember(r,n,_r(U,dt(d,U)),u)}}var ul=[/org_[A-Za-z0-9]{6,}/,/model_catalog/,/urun-(?:ts|infra|python)#\d+/,/_app\.serve/,/https?:\/\/[^\s"']*?(?:\.supabase\.co|api\.urun\.sh|\.cloud\.urun\.sh|localhost|127\.0\.0\.1)/,/\bat \S+:\d+:\d+|\bat [^\n]*\([^)]*:\d+:\d+\)/,/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,/\b192\.168\.\d{1,3}\.\d{1,3}\b/,/\bconnect E[A-Z]+/,/\bauthorization[:=]/i,/\bbearer\s+[A-Za-z0-9._+~-]{8,}/i,/\bsk-[A-Za-z0-9._-]{8,}/];function ke(t){return!ul.some(e=>e.test(t))}function xe(t){return t==null||t===""?"an internal error occurred while serving this request":`an internal error occurred while serving this request \u2014 quote inference id ${t} when reporting it`}function fe(t,e){if(t instanceof J)return{message:"the session serving this request is gone \u2014 it was closed by the platform before it finished; please retry",redacted:!0};let n=Bs(t);return n||{message:xe(e?.inferenceId??null),redacted:!0}}function Bs(t){return t instanceof Me?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Q?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof G?{message:t.message,redacted:!1}:t instanceof Ie?{message:t.message,redacted:!1}:t instanceof Ue?{message:t.message,redacted:!1}:t instanceof Se?ke(t.message)?{message:t.message,redacted:!1}:null:t instanceof be?{message:t.message,redacted:!1}:t instanceof ce?{message:t.message,redacted:!1}:null}function pt(t,e,n){let r=n??(i=>console.error(i)),o=Bs(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&ke(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${we(e)}`),`the ${t} upstream failed while serving this request`)}function Oe(t){let e=t?.message;return typeof e=="string"&&e.length>0&&ke(e)?e:null}function we(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var ll="/v1/responses",dl=64*1024*1024,cl=8*1024*1024,pl=16,qs=32,js=3600*1e3,fl=/^[A-Za-z0-9._-]{1,256}$/;function le(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var ml=le(400,{type:"invalid_request_error",code:"invalid_stream_id",message:"The 'stream_id' field must be a non-empty string with at most 256 characters and may only contain letters, numbers, underscores, hyphens, and periods.",param:"stream_id"});function kr(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function gl(t){for(;t.bufferedAmount>cl&&t.readyState===Fe.WebSocket.OPEN;){let{promise:e,resolve:n}=kr();setTimeout(n,5),await e}}var br=class extends at{constructor(n){super();this.shared=n}shared;thread(n,r){if(n==null)return super.thread(n,r);try{return super.thread(n,r)}catch(o){if(!(o instanceof Ye))throw o;return this.shared.thread(n,r)}}remember(n,r,o,s=!0){s?this.shared.remember(n,r,o):super.remember(n,r,o)}forget(n){super.forget(n),this.shared.forget(n)}},Sr=class{constructor(e,n,r,o,s){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.operatorLog=s;this.store=new br(Ut(n)),e.on("message",(u,a)=>this.onMessage(u,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${js/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},js).unref?.()}ws;clients;stats;statusOf;operatorLog;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(le(400,{type:"invalid_request_error",code:"binary_frame",message:"Responses WebSocket frames must be JSON text"})),this.ws.close(1003,"binary frames are not supported");return}let r;try{r=JSON.parse(e.toString())}catch{this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_json",message:"frame is not valid JSON"}));return}if(r===null||typeof r!="object"||Array.isArray(r)){this.sendFrame(le(400,{type:"invalid_request_error",code:"invalid_event",message:"frame must be a JSON object"}));return}let o=r;if(o.type!=="response.create"){this.sendFrame(le(400,{type:"invalid_request_error",code:"unknown_event",message:`unknown client event type ${JSON.stringify(o.type??null)}; only "response.create" is supported`}));return}if("stream"in o){this.sendFrame(le(400,{type:"invalid_request_error",code:"stream_is_implicit",message:"'stream' is implicit over the Responses WebSocket and must not be sent",param:"stream"}));return}if("background"in o){this.sendFrame(le(400,{type:"invalid_request_error",code:"background_not_supported",message:"'background' is not supported over the Responses WebSocket",param:"background"}));return}let s;if(o.stream_id!==void 0){if(typeof o.stream_id!="string"||!fl.test(o.stream_id)){this.sendFrame(ml);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=qs){this.sendFrame(le(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${qs}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),u=s??"",a=this.lanes.get(u)??Promise.resolve();this.lanes.set(u,a.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=Lt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await Dt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Nt(r)})}catch(u){this.failTurn(u,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let u of i){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)break;if(u.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(u,n,r));break}this.send(u,n),await gl(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=Lt(),o=Nt(r);try{let s=ct(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(o,s,[],e.store!==!1),this.laneOfResponse.set(o,n??null),this.send({type:"response.created",response:{id:o,object:"response",status:"in_progress"}},n)}catch(s){this.failTurn(s,n,e,r)}}failTurn(e,n,r,o){this.sendFrame(this.errorFrameOf(e,n,o));let s=r.previous_response_id;typeof s=="string"&&this.laneOfResponse.get(s)===(n??null)&&(this.store.forget(s),this.laneOfResponse.delete(s))}errorFrameOf(e,n,r){let o=e instanceof Error?e.message:we(e);if(e instanceof ye)return le(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof G)return le(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof J){let u=fe(e,{inferenceId:r});return u.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(503,{type:"upstream_error",code:"session_gone",message:u.message},n)}let s=this.statusOf?.(e)??null;if(s)return s.operatorDetail!==void 0&&this.operatorLog(`[caller-message-boundary] WS /v1/responses classified failure (inference id ${r??"none"}); detail withheld from the caller: ${s.operatorDetail}`),le(s.status,{type:s.openaiType,message:o},n);let i=fe(e,{inferenceId:r});return i.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),le(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Oe(o),u=i??xe(r);return i===null&&this.operatorLog(`[caller-message-boundary] WS /v1/responses upstream terminal error event carried no safe caller message (inference id ${r}); full event withheld from the caller: ${JSON.stringify(e)}`),le(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:u},n)}async acquire(){for(;this.active>=pl;){let{promise:e,resolve:n}=kr();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==Fe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==Fe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function _n(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
15
15
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
16
16
|
Connection: close\r
|
|
17
17
|
Content-Type: text/plain; charset=utf-8\r
|
|
18
18
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
19
19
|
\r
|
|
20
|
-
${o}`)}function
|
|
21
|
-
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Rr)n[u]=i[u]}}var
|
|
22
|
-
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function
|
|
20
|
+
${o}`)}function Hs(t,e){let n=new Fe.WebSocketServer({noServer:!0,maxPayload:dl}),r=new ze,o=new Set,s=new Set,i=new Set,u=typeof e.clients=="function"?e.clients:()=>e.clients,a=!1,l=(d,c,p)=>{let m;try{m=new URL(d.url??"/","http://localhost")}catch{_n(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),m.pathname!==ll){i.add(c);return}s.add(c);let h=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){_n(c,401,"invalid local proxy api key");return}let v;try{v=await u(d)}catch(k){let S=e.statusOf?.(k)??null;_n(c,S?.status??500,"upstream resolver rejected the connection");return}a||c.destroyed||(h=!0,n.handleUpgrade(d,c,p,k=>{s.delete(c),o.add(k),k.on("close",()=>o.delete(k));try{new Sr(k,v,r,e.statusOf,e.operatorLog??(S=>console.error(S)))}catch{o.delete(k),k.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!h&&!c.destroyed&&_n(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",l),{stats:r,close:()=>{let{promise:d,resolve:c}=kr();if(a)return c(),d;a=!0,t.off("upgrade",l);for(let m of s)m.destroy();s.clear();for(let m of i)m.destroy();i.clear();for(let m of o)m.close(1001,"server shutting down");let p=setTimeout(()=>{for(let m of o)m.readyState!==Fe.WebSocket.CLOSED&&m.terminate()},2e3);return p.unref?.(),n.close(()=>{clearTimeout(p),c()}),d}}}var Br=require("@urun-sh/core");var Gs=require("@urun-sh/core"),hl={no_capacity:429,queue_timeout:429,no_attached_consumer:503,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502},yl={no_capacity:"no ready GPU capacity for this model right now \u2014 the platform starts capacity for it on demand; retry",queue_timeout:"the session was admitted but never became live in time \u2014 the backend is busy; retry",cold_start_exceeded:"the cold boot exceeded its time budget without serving \u2014 the platform is still working on it; retry with a longer client timeout",queue_full:"the admission queue for this model is full \u2014 retry after the Retry-After period",admission_busy:"session admission is momentarily busy \u2014 retry shortly",admission_unavailable:"session admission is temporarily unavailable \u2014 retry",backend_error:"the control plane failed while admitting the session",no_attached_consumer:"no consumer is attached to serve this session right now \u2014 the platform is provisioning for the waiting demand; retry shortly"};function Ft(t,e){let n=yl[t.code];return e?`${n} (${e})`:n}function vn(t){if(t==null)return null;let e=hl[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:t==="no_capacity"||t==="queue_full"?"capacity_error":t==="queue_timeout"||t==="cold_start_exceeded"||t==="no_attached_consumer"?"scheduling_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function bn(t){if(t.kind==="create-failed")return vn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=Gs.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return vn(e?"cold_start_exceeded":"queue_timeout")}var Js=rt(require("os"),1),Ws=rt(require("path"),1),Ks=require("url"),zs=require("util");var Vs="0.6.45";var Ys=4141,_l=Vs,kn={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 Er(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 Xs(t,e,n){let r={...t,...Er(e,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Qs(t,e,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${t}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),i=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),u=n[0]==="exec",a=s.includes("--skip-git-repo-check"),l=u&&!a?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...i?[]:["-m",e],...l]}function Zs(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",t,...e]}function ei(t,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${t}`,...e]}function ti(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,Ks.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 ni(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 ri(t){if(t[0]!=="--port")return null;let e=ni(t[1]);return t.splice(0,2),e}function Ar(t){let e=t.indexOf("--port");if(e===-1)return Ys;let n=ni(t[e+1]);return t.splice(e,2),n}function oi(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 xr(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 ft(t){let e=vl(xr(t,"URUN_BASE_URL")),n=xr(t,"URUN_ORG_ID"),r=xr(t,"URUN_APP"),o=(t.URUN_FUNCTION??"serve").trim()||"serve",s=(t.URUN_API_URL??"").trim(),i=s?Sn(s,"URUN_API_URL"):Jo,u=(t.URUN_JWT??"").trim();if(u)return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"jwt",jwt:u}};let a=(t.URUN_API_KEY??"").trim();if(a){let l=(t.URUN_GATEWAY_URL??"").trim(),d=l?Sn(l):void 0;return{baseUrl:e,orgId:n,appId:r,fnName:o,apiUrl:i,auth:{lane:"api-key",apiKey:a,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function vl(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 Sn(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 Ir(t){return{app:t.appId,org:t.orgId,fn:t.fnName,base_url:t.baseUrl,proxy_version:_l}}function bl(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 Sl=250;async function Tr(t,e=Sl){try{let n=await fetch(`http://127.0.0.1:${t}/stats`,{signal:AbortSignal.timeout(e)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:i,base_url:u,proxy_version:a}=r;return typeof o!="string"||typeof s!="string"||typeof i!="string"||typeof u!="string"||typeof a!="string"?null:{app:o,org:s,fn:i,base_url:u,proxy_version:a}}catch{return null}}var si=2e3;async function kl(t,e=si){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 ii(t,e,n=Ys,r=si){if(t!=null)return{mode:"spawn",port:t};let o=await Tr(n);if(o!==null&&bl(o,e)){let s=await kl(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 Or(t,e=Js.default.homedir()){return Ws.default.join(e,".urun","logs",`compat-proxy-${t}.log`)}var Rr=["log","info","warn","error","debug","trace"];function ai(t,e=process,n=console){let r=e.stdout.write,o=e.stderr.write,s=(u,...a)=>t.write(u,...a);e.stdout.write=s,e.stderr.write=s;let i=Object.fromEntries(Rr.map(u=>[u,n[u]]));for(let u of Rr)n[u]=(...a)=>{t.write(`${(0,zs.format)(...a)}
|
|
21
|
+
`)};return()=>{e.stdout.write=r,e.stderr.write=o;for(let u of Rr)n[u]=i[u]}}var xl=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function ui(t){let e=t?.code;return typeof e=="string"&&xl.has(e)}function Re(t,e){try{return t.write(e),!0}catch(n){if(ui(n))return!1;throw n}}function li(t){let e={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=t.streams[r],s=i=>{ui(i)&&(e[r]=!0);let u=i?.code;try{t.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(u??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
22
|
+
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function di(t){let e=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{t.appendSync(t.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
23
23
|
`)}catch{}t.restore();try{t.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${t.logPath}
|
|
24
24
|
`)}catch(o){try{t.appendSync(t.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
|
|
25
|
-
`)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function ui(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 Bt=require("ws");var fi=require("@urun-sh/core");var di=require("crypto");function T(t){return`${t}_${(0,di.randomUUID)().replace(/-/g,"").slice(0,24)}`}var kn=4*1024*1024,Pr=8*1024*1024,Cr=512,xn=20*1024*1024;function Q(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Be(t,e){return{type:"server_error",code:t,message:e}}function W(t){return{type:"error",event_id:T("event"),error:t}}function $r(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var P=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},xl={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Rl={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},El={format:!0,voice:!0,speed:!0};function Al(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function mt(t,e){if(!Array.isArray(t)||t.length===0)throw new P(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new P(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function li(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new P(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Il=10;function Mr(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Il})}function Dt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new P("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in xl));if(s.length>0)throw new P(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=mt(o.modalities,"modalities"),a=mt(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new P("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new P(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new P(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new P('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new P(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=mt(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new P('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Al(a))throw new P(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new P("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new P("instructions must be a string or null","instructions");i.instructions=Mr(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new P("voice must be a string or null","voice");if(!n.voice)throw new P("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new P(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new P("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new P(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new P("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new P("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new P("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new P(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new P(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new P(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new P("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new P("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new P(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new P(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new P("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new P("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Rl))throw new P(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&li(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Dt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Dt({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new P("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new P("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in El))throw new P(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&li(d.format,"audio.output.format"),d.speed!==void 0)throw new P("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new P("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new P("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function Rn(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Lr(t,e){let n=t;if(!n||typeof n!="object")throw new P("item must be an object","item","invalid_request");if(n.type==="function_call_output"){if(typeof n.call_id!="string"||typeof n.output!="string")throw new P("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:T("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new P('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new P("message item content must be an array","item.content","invalid_request");let o=[];for(let s of n.content){let i=s;if(!i||typeof i!="object")throw new P("content part must be an object","item.content","invalid_request");if(i.type==="input_text"||r==="assistant"&&i.type==="output_text"){if(typeof i.text!="string")throw new P(`${String(i.type)} part requires string text`,"item.content.text","invalid_request");o.push({type:i.type,text:i.text});continue}if(i.type==="input_audio"){if(!e)throw new P("input_audio content refused: no authoritative voice binding for the resolved backend","item.content.type","audio_not_supported");if(typeof i.audio!="string")throw new P("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new P("input_image content is only valid on user message items","item.content.type","invalid_request");let u=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof u!="string"||u.length===0)throw new P("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!u.startsWith("data:image/"))throw new P("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let a=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:u,...a!==void 0?{detail:a}:{}});continue}throw new P(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:T("item"),type:"message",role:r,content:o}}throw new P(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function En(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 Ol=1001,Tl=1011,Pl=15e3;var An=class extends Error{},In=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},ci=t=>t.slice(0,120),Cl=/^[A-Za-z0-9+/=]*$/,$l=2;function Ml(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>$l)return!1;return!0}var Ft=class{id=T("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=$r();sessionId=T("sess");conversationId=T("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Pl,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:T("event"),session:Rn(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:T("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof V&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(W(Be("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:T("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:T("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:T("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:T("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=T("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:T("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(Q("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>kn){this.fail(Q("frame_too_large",`frame exceeds the ${kn}-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(W({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof An){this.fail(Be(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
|
|
26
|
-
${o?.stack??we(o)}`),this.send(W(Be(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let n=Dt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(W(Q("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:T("event"),session:Rn(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Lr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(W(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:T("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(W(Q("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:T("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(W(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:T("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(W(Q("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Cl.test(e.audio)){this.send(W(Q("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>xn){this.send(W(Q("buffer_full",`uncommitted input audio exceeds the ${xn}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:T("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(W(Q("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=T("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:T("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:T("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(W(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":if(this.isTranscriptionSession()){this.send(W(Q("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(W(Q("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(W(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 An("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(W({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=!0;try{for(;;){let o;if(r||this.turnStallMs<=0)r=!1,o=await n.next();else{let s,i=new Promise((u,a)=>{s=setTimeout(()=>a(new In),this.turnStallMs)});o=await Promise.race([n.next(),i]).finally(()=>clearTimeout(s))}if(o.done===!0)return;yield o.value}}finally{await n.return?.()}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(W(Q("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?mt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?mt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new P("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(W(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,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=T("req"),u=`resp_${i}`;this.activeResponseId=u;let a=this.binding.composite===!0,l=a?0:this.items.length,d=a?null:En(this.items),c=Mr(typeof n.instructions=="string"?n.instructions:this.config.instructions),p=typeof n.temperature=="number"?n.temperature:this.config.temperature,m=n.max_output_tokens??this.config.maxOutputTokens,g=m==="inf"||m===void 0?void 0:m,v=n.tools!==void 0?n.tools:this.config.tools,x=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,S={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...p!==void 0?{temperature:p}:{},...g!==void 0?{max_output_tokens:g}:{},...v!==void 0?{tools:v}:{},...x!==void 0?{tool_choice:x}:{}};if(!(a&&!this.ensureVoice())){for(let{audio:w,captureWallMs:f}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(w,f);this.inFlight=(async()=>{let w=[],f=E=>{this.responseFlushed?this.send(E):w.push(E)},h=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:T("event"),response:this.responseObject(u,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(u,"in_progress")});for(let E of w)this.send(E);w.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},b=null;try{if(a){if(this.pendingTranscriptItemId!==null&&(await new Promise(R=>{this.pendingTranscriptSettled=R}),this.cancelled||this.closed))return;l=this.items.length,d=En(this.items)}let{input:E,sawAudioOnlyItem:I}=d??{input:[],sawAudioOnlyItem:!1},O={...S,input:E,...a?this.compositeTurnAsk(n):{}};I&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let _;try{_=await this.upstreamStream(O,i)}catch(R){this.upstreamTurnFault(R,u);return}try{for await(let R of this.stallBoundedTurn(_)){if(this.cancelled)break;let k=R;if(k.type==="error"){let C=this.upstreamErrorBody(k);this.responseFlushed?this.send(W(C)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(u,C)});return}if(k.type==="response.output_text.delta"&&typeof k.delta=="string"){h(),y.messageOpen||(this.beginMessageItem(u,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&f({type:"response.output_text.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:k.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,f({type:"response.output_audio_transcript.delta",event_id:T("event"),item_id:`${u}_msg_0`,response_id:u,output_index:0,content_index:0,delta:k.delta})),y.messageText+=k.delta;continue}if(k.type==="response.function_call_arguments.delta"){h();let C=typeof k.delta=="string"?k.delta:"",N=typeof k.call_id=="string"&&k.call_id.length>0?k.call_id:`${u}_fc_${y.nextOutputIndex}`,j=y.tools.get(N);if(!j){let U=typeof k.name=="string"&&k.name.length>0?k.name:void 0;j={outputIndex:y.nextOutputIndex++,name:U,args:""},y.tools.set(N,j);let D={id:N,object:"realtime.item",type:"function_call",call_id:N,name:U??"",arguments:"",status:"in_progress"};f({type:"response.output_item.added",event_id:T("event"),response_id:u,output_index:j.outputIndex,item:D}),this.emitAssistantItemAdded(D)}typeof k.name=="string"&&k.name.length>0&&(j.name=k.name),j.args+=C,f({type:"response.function_call_arguments.delta",event_id:T("event"),item_id:N,response_id:u,output_index:j.outputIndex,call_id:N,name:j.name??"",delta:C});continue}if(k.type==="response.completed"){b=k.response??null;continue}}}catch(R){if(R instanceof In)this.operatorLog(`[realtime] turn ${u} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(R,u);return}}if(this.cancelled)return;this.closeOpenItems(u,y,l),h(),this.send({type:"response.done",event_id:T("event"),response:this.doneResponse(u,l,b)})}finally{this.inFlight=null,this.activeResponseId=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Ml(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(W({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:T("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:T("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:T("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:T("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:T("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:T("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:T("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:T("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Te(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??xe(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&ke(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${we(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Be("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof V){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof fi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Be(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(W(r)):this.send({type:"response.failed",event_id:T("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(W(Q("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:T("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Cr&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(W(Q("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>kt){this.send(W(Q("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${kt}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(W(Q("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(W(Be(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Pr){this.ws.close(Ol,ci("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=fe(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${we(e)}`),r.message}fail(e,n){this.send(W(e)),this.ws.close(Tl,ci(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>pi(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),pi(this.id,e)}},Nr=[];function pi(t,e){Nr.push({id:t,reason:e}),Nr.length>256&&Nr.shift()}var Fr="/v1/realtime",mi="urun.admission",gi=t=>t.slice(0,120);function Ll(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
25
|
+
`)}catch{}}t.killChild(),t.exit(1)};return t.proc.on("uncaughtException",e),t.proc.on("unhandledRejection",e),()=>{t.proc.off("uncaughtException",e),t.proc.off("unhandledRejection",e)}}function ci(t,e){let n="pass --port 0 for an OS-assigned ephemeral port";return e?`port ${t} is held by another urun-openai proxy serving app ${e.app} (org ${e.org}, fn ${e.fn}, version ${e.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${t}, or ${n}`:`port ${t} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}var jt=require("ws");var mi=require("@urun-sh/core");var fi=require("crypto");function O(t){return`${t}_${(0,fi.randomUUID)().replace(/-/g,"").slice(0,24)}`}var xn=4*1024*1024,Pr=8*1024*1024,Cr=512,Rn=20*1024*1024;function X(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function Be(t,e){return{type:"server_error",code:t,message:e}}function W(t){return{type:"error",event_id:O("event"),error:t}}function $r(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var C=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Rl={type:!0,object:!0,id:!0,expires_at:!0,model:!0,instructions:!0,modalities:!0,output_modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,tracing:!0,prompt:!0,include:!0,reasoning:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},El={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Al={format:!0,voice:!0,speed:!0};function Il(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function mt(t,e){if(!Array.isArray(t)||t.length===0)throw new C(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new C(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function pi(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new C(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Tl=10;function Mr(t){if(t==null)return t;let e;try{e=JSON.parse(t)}catch{return t}if(e===null||typeof e!="object"||Array.isArray(e))return t;let n=e;return n.hz!==void 0||n.cadence_ms!==void 0||!("questions"in n)&&!("question"in n)?t:JSON.stringify({...n,hz:Tl})}function Bt(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new C("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(u=>!(u in Rl));if(s.length>0)throw new C(`session field(s) not supported by this backend: ${s.join(", ")}`,s[0],"unsupported_field");if(o.modalities!==void 0&&o.output_modalities!==void 0){let u=mt(o.modalities,"modalities"),a=mt(o.output_modalities,"output_modalities");if(u.slice().sort().join(",")!==a.slice().sort().join(","))throw new C("modalities and output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","output_modalities","invalid_modalities")}let i={...e,outputModalities:[...e.outputModalities]};for(let[u,a]of Object.entries(o))switch(u){case"type":{if(a!=="realtime"&&a!=="transcription")throw new C(`session.type ${JSON.stringify(a)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==a)throw new C(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(a)}: the type is fixed at establishment (the connection's URL intent, the first session.update that names it, or the first input_audio_buffer.append, which establishes realtime)`,"type","invalid_request");if(a==="transcription"&&!n.turns)throw new C('session.type "transcription" is refused: the resolved backend wires no turn/transcript lane (the stt stream behind the engine\u2019s own transcripts) \u2014 there is no transcription source on this session',"type","unsupported_field");i.type=a;break}case"object":case"id":case"expires_at":{if(a===null)break;let l=u==="object"?"realtime.session":u==="id"?r:null;if(a!==l)throw new C(`session.${u} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(l)}, got ${JSON.stringify(a)}`,u,"unsupported_field");break}case"output_modalities":case"modalities":{let l=mt(a,u);for(let d of l)if(d==="audio"&&!n.voice)throw new C('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',u,"audio_not_supported");i.outputModalities=l;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Il(a))throw new C(`session.${u} cannot be honoured by this backend: the resolved session has no ${u==="reasoning"?"reasoning-effort control":u} primitive`,u,"unsupported_field");break}case"model":if(a!==null&&typeof a!="string")throw new C("model must be a string or null","model");i.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new C("instructions must be a string or null","instructions");i.instructions=Mr(a??void 0)??void 0;break;case"voice":if(a===null){delete i.voice;break}if(typeof a!="string")throw new C("voice must be a string or null","voice");if(!n.voice)throw new C("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new C(`${u} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,u);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new C("temperature must be a finite number or null","temperature");i.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new C(`${u} must be a positive integer, "inf" or null`,u);i.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new C("tools must be an array","tools");i.tools=a;break;case"tool_choice":i.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new C("metadata must be an object or null","metadata");i.metadata=a??null;break;case"turn_detection":{if(a===null){i.turnDetection=null;break}if(!n.turns)throw new C("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new C("turn_detection must be an object or null","turn_detection");let d=String(l.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new C(`turn_detection.type ${JSON.stringify(l.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[p,m]of Object.entries(l))if(!(p==="type"||p==="create_response"||p==="interrupt_response")){if(!(p in c))throw new C(`turn_detection.${p} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${p}`,"unsupported_field");if(m!=null&&m!==c[p])throw new C(`turn_detection.${p} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(m)}, the lane's own tuning is fixed)`,`turn_detection.${p}`,"unsupported_field")}i.turnDetection={createResponse:l.create_response!==!1,interruptResponse:l.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new C("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 C("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(a))if(!["model","language","languages","prompt"].includes(d))throw new C(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let l=a.model;if(l!=null){let d=typeof l=="string"?l:JSON.stringify(l);if(typeof l!="string"||l!==n.model)throw new C(`input_audio_transcription.model ${JSON.stringify(d)} does not match the model this connection is bound to (${n.model===void 0?"the unnamed default app":JSON.stringify(n.model)}) \u2014 a transcription session runs the engine the connection bound and cannot be retuned to another model mid-connection`,"input_audio_transcription.model","unsupported_field")}i.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new C("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let l=a;if(!l||typeof l!="object"||Array.isArray(l))throw new C("audio must be an object or null","audio");if(l.input!==void 0&&l.input!==null){let d=l.input;if(!d||typeof d!="object"||Array.isArray(d))throw new C("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in El))throw new C(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&pi(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=Bt({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=Bt({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new C("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(l.output!==void 0&&l.output!==null){let d=l.output;if(!d||typeof d!="object"||Array.isArray(d))throw new C("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Al))throw new C(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&pi(d.format,"audio.output.format"),d.speed!==void 0)throw new C("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete i.voice;else{if(typeof d.voice!="string")throw new C("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new C("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");i.voice=d.voice}d.format!==void 0&&!i.outputModalities.includes("audio")&&(i.outputModalities=["text","audio"])}break}default:break}return i}function En(t,e){return{id:e,object:"realtime.session",type:t.type??"realtime",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function Lr(t,e){let n=t;if(!n||typeof n!="object")throw new C("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 C("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:O("item"),type:"function_call_output",callId:n.call_id,output:n.output}}if(n.type==="message"){let r=n.role;if(r!=="user"&&r!=="assistant"&&r!=="system")throw new C('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new C("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 C("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 C(`${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 C("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 C("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}if(i.type==="input_image"){if(r!=="user")throw new C("input_image content is only valid on user message items","item.content.type","invalid_request");let u=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof u!="string"||u.length===0)throw new C("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!u.startsWith("data:image/"))throw new C("input_image image_url must be a data URI (data:image/...) \u2014 remote URLs are not fetched on this lane","item.content.image_url","invalid_request");let a=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:u,...a!==void 0?{detail:a}:{}});continue}throw new C(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio / input_image)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:O("item"),type:"message",role:r,content:o}}throw new C(`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 Ol=1001,Pl=1011,Cl=15e3;var In=class extends Error{},Tn=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},Nr=t=>t.slice(0,120),$l=/^[A-Za-z0-9+/=]*$/,Ml=2;function Ll(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Ml)return!1;return!0}var qt=class{id=O("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=$r();sessionId=O("sess");conversationId=O("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;videoLane=null;frozenAudio=[];inFlight=null;activeResponseId=null;activeRequestId=null;turnCancelled=null;wakeTurnCancelled=null;responseFlushed=!1;cancelled=!1;pendingTranscriptSettled=null;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnLaneIterator=null;turnTranscript={open:!1,text:"",final:!1};lastCommittedTranscript=null;pendingTranscriptItemId=null;manuallyDischargedTurnItem=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.operatorLog=e.operatorLog??(n=>console.error(n)),this.turnStallMs=e.turnStallMs??Cl,this.binding.model&&(this.config.model=this.binding.model),this.binding.composite===!0&&(this.config.outputModalities=["text","audio"]),this.binding.intent==="transcription"&&(this.config.type="transcription"),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:O("event"),session:En(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:O("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane();for(let n of e.replayFrames??[])this.onMessage(n)}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns(e.signal)[Symbol.asyncIterator]();this.turnLaneIterator=n,(async()=>{try{for(;;){let r=await n.next();if(r.done||this.closed||e.signal.aborted)return;this.onTurnEvent(r.value)}}catch(r){if(!this.closed&&!e.signal.aborted)if(r instanceof J&&this.binding.composite===!0)this.failSessionGone(r);else{let o=this.callerLine(r,"turn/transcript lane read"),s=this.pendingTranscriptItemId;s!==null?this.failPendingTranscription(s,o):this.send(W(Be("turn_lane_fault",`the backend turn/transcript lane failed: ${o}`)))}}finally{this.turnLaneIterator===n&&(this.turnLaneIterator=null)}})()}isTranscriptionSession(){return this.binding.intent==="transcription"||this.config.type==="transcription"}liveSttIn(){return this.isTranscriptionSession()||this.binding.composite===!0}transcriptionEventsOn(){return this.config.inputAudioTranscription||this.liveSttIn()}completePendingTranscription(e){this.pendingTranscriptItemId=null;let n=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(e,n),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:e,content_index:0,transcript:n});let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.emitItemDone(e)}failPendingTranscription(e,n){this.pendingTranscriptItemId=null,this.turnTranscript={open:!1,text:"",final:!1};let r=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,r?.(),this.send({type:"conversation.item.input_audio_transcription.failed",event_id:O("event"),item_id:e,content_index:0,error:{type:"server_error",code:"turn_lane_fault",message:n}}),this.emitItemDone(e)}writeItemTranscript(e,n){let r=this.items.find(s=>s.id===e);!r||r.type!=="message"||(r.content??[])[0]?.type!=="input_audio"||(r.content=[{type:"input_audio",transcript:n},...(r.content??[]).slice(1)])}emitItemDone(e){let n=this.items.findIndex(r=>r.id===e);n<0||this.send({type:"conversation.item.done",event_id:O("event"),previous_item_id:n>0?this.items[n-1].id:null,item:this.itemToProtocol(this.items[n])})}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"",r=this.pendingTranscriptItemId;this.turnTranscript.open=!0,n.length>0&&(this.turnTranscript.text+=n),this.turnTranscript.final=e.kind==="final",this.transcriptionEventsOn()&&n.length>0&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:O("event"),item_id:r??"input_audio_turn",content_index:0,delta:n}),e.kind==="final"&&r!==null&&(this.completePendingTranscription(r),this.manuallyDischargedTurnItem=r);return}case"turn_start":{this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!0,text:this.turnTranscript.text,final:!1},this.send({type:"input_audio_buffer.speech_started",event_id:O("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.pendingTranscriptItemId;if(n!==null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:n,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.completePendingTranscription(n);return}let r=this.manuallyDischargedTurnItem;if(r!==null){this.manuallyDischargedTurnItem=null,this.turnTranscript={open:!1,text:"",final:!1},this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:r,audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}let o=this.turnTranscript.text.trim(),s=o.length>0?o:null;if(this.turnTranscript={open:!1,text:"",final:!1},this.lastCommittedTranscript=s,this.liveSttIn()&&this.config.turnDetection===null){this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:"input_audio_turn",audio_end_ms:typeof e.startMs=="number"?e.startMs:0});return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let i=O("item"),u=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:u,item_id:i}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:u,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:O("event"),item_id:i,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.transcriptionEventsOn()&&s!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(X("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>xn){this.fail(X("frame_too_large",`frame exceeds the ${xn}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(X("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(X("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(W({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof In){this.fail(Be(null,this.callerLine(o,"event handler")),"handler_fault");return}this.operatorLog(`[handler-guard] realtime event handler threw (conn ${this.id}, session ${this.sessionId}, event ${r.type}):
|
|
26
|
+
${o?.stack??we(o)}`),this.send(W(Be(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let n=Bt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0,model:this.binding.model},this.sessionId);if(this.binding.composite===!0&&n.turnDetection!==null){this.send(W(X("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:O("event"),session:En(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Lr(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null,o=n.content??[];(o.length===0||o.some(s=>s.type!=="input_image"))&&this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:r,item:this.itemToProtocol(n)}),this.emitItemDone(n.id);return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send(W(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:O("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send(W(X("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:O("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send(W(X("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:O("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send(W(X("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!$l.test(e.audio)){this.send(W(X("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>Rn){this.send(W(X("buffer_full",`uncommitted input audio exceeds the ${Rn}-byte bound \u2014 commit or clear first`,"audio")));return}this.pendingAudioBytes.push({audio:e.audio,captureWallMs:n}),this.pendingAudioTotalBytes+=r;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.lastCommittedTranscript=null,this.pendingTranscriptItemId===null&&(this.turnTranscript={open:!1,text:"",final:!1}),this.send({type:"input_audio_buffer.cleared",event_id:O("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(W(X("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=O("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;if(this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:O("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])}),this.liveSttIn())if(n!==null)this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:n}),this.emitItemDone(r);else if(this.turnTranscript.final){let s=this.turnTranscript.text.trim();this.turnTranscript={open:!1,text:"",final:!1},this.writeItemTranscript(r,s),this.send({type:"conversation.item.input_audio_transcription.completed",event_id:O("event"),item_id:r,content_index:0,transcript:s}),this.emitItemDone(r),this.manuallyDischargedTurnItem=r}else this.pendingTranscriptItemId=r;else this.emitItemDone(r);return}case"output_audio_buffer.clear":{this.send(W(X("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(W(X("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;case"urun.session.end":{if(this.binding.endSession===void 0){this.send(W(X("unknown_event",`event type ${e.type} is not supported by this adapter`)));return}Promise.resolve().then(()=>this.binding.endSession?.()).catch(n=>{Dr(this.id,`app-close end failed: ${n instanceof Error?n.message:String(n)}`)}).finally(()=>{try{this.ws.close(1e3,Nr("session ended by client"))}catch{}});return}default:this.send(W(X("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(W(X("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 In("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(W({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async*stallBoundedTurn(e){let n=e[Symbol.asyncIterator](),r=this.turnCancelled,o=!0;try{for(;;){let s;if(o||this.turnStallMs<=0)o=!1,s=r?await Promise.race([n.next(),r]):await n.next();else{let i,u=new Promise((l,d)=>{i=setTimeout(()=>d(new Tn),this.turnStallMs)});s=await(r?Promise.race([n.next(),u,r]):Promise.race([n.next(),u])).finally(()=>clearTimeout(i))}if(s.done===!0)return;yield s.value}}finally{Promise.resolve(n.return?.()).catch(()=>{})}}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function"){let s=e.response??e;return r.sendResponseCreate({type:"response.create",response:s},e.input??[],n)}let o=this.binding.clients;if(o&&typeof o.createResponse=="function"){let{response:s,input:i,...u}=e;return await o.createResponse({...u,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(W(X("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?mt(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?mt(n.output_modalities,"response.output_modalities"):void 0;if(r!==void 0&&o!==void 0&&r.slice().sort().join(",")!==o.slice().sort().join(","))throw new C("response.modalities and response.output_modalities disagree \u2014 the two spellings name one field; send a single consistent value","response.output_modalities","invalid_modalities");if((o??r)?.includes("audio")&&!this.ensureVoice())return;if(n.input!==void 0){this.send(W(X("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;let i=()=>{},u=new Promise(g=>{i=()=>g({done:!0,value:void 0})});this.turnCancelled=u,this.wakeTurnCancelled=()=>i(),this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let a=O("req"),l=`resp_${a}`;this.activeResponseId=l,this.activeRequestId=a;let d=this.binding.composite===!0,c=d?0:this.items.length,p=d?null:An(this.items),m=Mr(typeof n.instructions=="string"?n.instructions:this.config.instructions),h=typeof n.temperature=="number"?n.temperature:this.config.temperature,v=n.max_output_tokens??this.config.maxOutputTokens,k=v==="inf"||v===void 0?void 0:v,S=n.tools!==void 0?n.tools:this.config.tools,w=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,f={stream:!0,...this.config.model?{model:this.config.model}:{},...m!==void 0?{instructions:m}:{},...h!==void 0?{temperature:h}:{},...k!==void 0?{max_output_tokens:k}:{},...S!==void 0?{tools:S}:{},...w!==void 0?{tool_choice:w}:{}};if(!(d&&!this.ensureVoice())){for(let{audio:g,captureWallMs:y}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(g,y);this.inFlight=(async()=>{let g=[],y=E=>{this.responseFlushed?this.send(E):g.push(E)},b=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:O("event"),response:this.responseObject(l,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(l,"in_progress")});for(let E of g)this.send(E);g.length=0,this.responseFlushed=!0}},x={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1,contentFlowed:!1},A=null;try{if(d){if(this.pendingTranscriptItemId!==null&&(await new Promise($=>{this.pendingTranscriptSettled=$}),this.cancelled||this.closed))return;c=this.items.length,p=An(this.items)}let{input:E,sawAudioOnlyItem:_}=p??{input:[],sawAudioOnlyItem:!1},R={...f,input:E,...d?this.compositeTurnAsk(n):{}};_&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let T;try{T=await this.upstreamStream(R,a)}catch($){this.upstreamTurnFault($,l);return}b();try{for await(let $ of this.stallBoundedTurn(T)){if(this.cancelled)break;let P=$;if(P.type==="error"){let B=this.upstreamErrorBody(P);x.contentFlowed?this.send(W(B)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(l,B)});return}if(P.type==="response.output_text.delta"&&typeof P.delta=="string"){b(),x.contentFlowed=!0,x.messageOpen||(this.beginMessageItem(l,x.nextOutputIndex++),x.messageOpen=!0),this.config.outputModalities.includes("text")&&y({type:"response.output_text.delta",event_id:O("event"),item_id:`${l}_msg_0`,response_id:l,output_index:0,content_index:0,delta:P.delta}),this.turnOutputIsAudio()&&(x.transcriptDelta=!0,y({type:"response.output_audio_transcript.delta",event_id:O("event"),item_id:`${l}_msg_0`,response_id:l,output_index:0,content_index:0,delta:P.delta})),x.messageText+=P.delta;continue}if(P.type==="response.function_call_arguments.delta"){b(),x.contentFlowed=!0;let B=typeof P.delta=="string"?P.delta:"",L=typeof P.call_id=="string"&&P.call_id.length>0?P.call_id:`${l}_fc_${x.nextOutputIndex}`,N=x.tools.get(L);if(!N){let ne=typeof P.name=="string"&&P.name.length>0?P.name:void 0;N={outputIndex:x.nextOutputIndex++,name:ne,args:""},x.tools.set(L,N);let V={id:L,object:"realtime.item",type:"function_call",call_id:L,name:ne??"",arguments:"",status:"in_progress"};y({type:"response.output_item.added",event_id:O("event"),response_id:l,output_index:N.outputIndex,item:V}),this.emitAssistantItemAdded(V)}typeof P.name=="string"&&P.name.length>0&&(N.name=P.name),N.args+=B,y({type:"response.function_call_arguments.delta",event_id:O("event"),item_id:L,response_id:l,output_index:N.outputIndex,call_id:L,name:N.name??"",delta:B});continue}if(P.type==="response.completed"){A=P.response??null;continue}}}catch($){if($ instanceof Tn)this.operatorLog(`[realtime] turn ${l} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault($,l);return}}if(this.cancelled)return;this.closeOpenItems(l,x,c),b(),this.send({type:"response.done",event_id:O("event"),response:this.doneResponse(l,c,A)})}finally{this.inFlight=null,this.activeResponseId=null,this.activeRequestId=null,this.turnCancelled=null,this.wakeTurnCancelled=null}})()}}compositeTurnAsk(e){return{output_modalities:[...Array.isArray(e.output_modalities)?e.output_modalities:Array.isArray(e.modalities)?e.modalities:this.config.outputModalities]}}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Ll(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(W({type:"invalid_request_error",code:"out_of_turn_audio",message:"the runtime produced voice OUT outside a response turn; this adapter delivers output audio only within response.output_audio.delta of an open turn \u2014 wire server-driven turns (VAD) upstream or keep speech inside response turns"})));return}this.responseFlushed||(this.send({type:"response.created",event_id:O("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:O("event"),response:this.responseObject(e,"in_progress")}),this.responseFlushed=!0);let r=`${e}_msg_0`;this.messageItemOpenForAudio||(this.beginAudioMessageItem(e),this.messageItemOpenForAudio=!0),this.send({type:"response.output_audio.delta",event_id:O("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;turnLastAnnouncedItemId=null;turnOutputIsAudio(){return this.config.outputModalities.includes("audio")||this.messageItemOpenForAudio}emitAssistantItemAdded(e){let n=this.turnLastAnnouncedItemId;this.turnLastAnnouncedItemId=typeof e.id=="string"?e.id:null,this.send({type:"conversation.item.added",event_id:O("event"),previous_item_id:n,item:e})}beginMessageItem(e,n){let r=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let o={id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:O("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;if(!this.messageItemAdded){this.messageItemAdded=!0;let r={id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]};this.send({type:"response.output_item.added",event_id:O("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:O("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio,i=this.config.outputModalities.includes("text"),u=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),this.send({type:"response.output_audio.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0})):n.transcriptDelta&&this.send({type:"response.output_audio_transcript.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:u}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,text:n.messageText}),this.send({type:"response.content_part.done",event_id:O("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:u}:{type:"output_text",text:n.messageText}});let a=[];s&&a.push({type:"output_audio",transcript:u}),n.messageText.length>0&&a.push({type:"output_text",text:n.messageText});let l={id:o,type:"message",role:"assistant",content:a};this.pushItem(l),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:0,item:this.itemToProtocol(l)}),this.emitItemDone(l.id)}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:O("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let u={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(u),this.send({type:"response.output_item.done",event_id:O("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(u)}),this.emitItemDone(u.id)}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=Oe(n);r===null&&this.operatorLog(`[caller-message-boundary] realtime upstream error event carried no safe caller message (conn ${this.id}, session ${this.sessionId}); full event withheld from the caller: ${JSON.stringify(e)}`);let o=r??xe(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&ke(e.message)?e.message:null;n===null&&this.operatorLog(`[caller-message-boundary] realtime session-gone close (conn ${this.id}, session ${this.sessionId}) withheld its cause's raw text: ${we(e)}`);let r=this.binding.composite===!0?n===null?"a pinned leg of this composite realtime connection is gone \u2014 the connection is closing":`a pinned leg of this composite realtime connection is gone \u2014 ${n}`:n===null?"this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone; the connection is closing":`this realtime connection's pooled session \u2014 the one its audio bridge and every turn ride \u2014 is gone: ${n}`;this.fail(Be("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof J){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof mi.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=Be(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(W(r)):this.send({type:"response.failed",event_id:O("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(W(X("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.wakeTurnCancelled?.();let n=this.activeRequestId,r=this.binding.session;n!==null&&typeof r=="object"&&r!==null&&"cancelTurn"in r&&typeof r.cancelTurn=="function"&&r.cancelTurn(n),this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let o=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,o?.();let s=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:O("event"),response:this.responseObject(s,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Cr&&this.items.shift()}forwardImageFrames(e){for(let n of e.content??[]){if(n.type!=="input_image")continue;let r=n.imageUrl.indexOf(","),o=r>=0?Buffer.from(n.imageUrl.slice(r+1),"base64"):Buffer.alloc(0);if(o.byteLength===0){this.send(W(X("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>xt){this.send(W(X("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${xt}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(W(X("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(W(Be(null,s instanceof Error?s.message:String(s)))))}}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:o.type==="input_image"?{type:"input_image",image_url:o.imageUrl,...o.detail?{detail:o.detail}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Pr){this.ws.close(Ol,Nr("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=fe(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${we(e)}`),r.message}fail(e,n){this.send(W(e)),this.ws.close(Pl,Nr(n)),this.teardown(n)}teardown(e){if(this.closed)return;this.closed=!0,this.turnLaneAbort?.abort(new Error("the realtime connection closed \u2014 the turn lane consumer is gone")),this.turnLaneAbort=null,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.turnLaneIterator;if(this.turnLaneIterator=null,r!==null){let o=r.return?.();o&&o.catch(()=>{})}this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(o=>Dr(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),Dr(this.id,e)}},Ur=[];function Dr(t,e){Ur.push({id:t,reason:e}),Ur.length>256&&Ur.shift()}var qr="/v1/realtime",gi="urun.admission",hi=t=>t.slice(0,120);function Nl(t,e,n){let r=e===401||e===403?"Unauthorized":e===402?"Payment Required":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
27
27
|
Connection: close\r
|
|
28
28
|
Content-Type: text/plain\r
|
|
29
29
|
\r
|
|
30
|
-
${
|
|
31
|
-
`),t.destroy()}function
|
|
32
|
-
`}function
|
|
33
|
-
`)}}}),d({stage:"admit",conn:a,model:l,...Ur(_)===void 0?{}:{session:Ur(_)}}),N()}catch(J){j(J)}};if(f!==null){let D=y??[];y=null,U(f,D);return}n.handleUpgrade(o,s,i,D=>U(D,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,E).then(async _=>{if(c.signal.aborted){S();let R=Ur(_);try{await _.release?.()}catch(k){w({while:"queued",...R===void 0?{}:{session:R},reason:p??"client socket closed",release_failed:k instanceof Error?k.message:String(k)});return}w({while:"queued",...R===void 0?{}:{session:R},reason:p??"client socket closed",released:!0}),s.destroy();return}S(),await I(_)}).catch(_=>{let R=_ instanceof Dr.SessionFailedError?vn(_):null,k=null;if(_!==null&&typeof _=="object"&&"status"in _){let U=_.status;typeof U=="number"&&(k=U)}let C=k??R?.status??502,N=_ instanceof Error?_.message:String(_),j=k!==null?N:R!==null?Ut(R,_ instanceof Dr.SessionFailedError&&_.status.sessionId?`session ${_.status.sessionId}`:void 0):fe(_).message;if(w({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:N,status:C}}),f!==null&&!c.signal.aborted){let U=JSON.stringify({type:mi,event_id:T("event"),status:C<500?"rejected":"failed",reason:j});f.readyState===Bt.WebSocket.OPEN&&f.send(U),f.close(1011,gi(j));return}s.destroyed||Ll(s,C,j)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var vi=require("crypto");var qr="x-urun-profile",jt="voice";var de=class extends Error{status=400},Fl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Bl=/\s/;function jl(t){return Fl.test(t)}function jr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new de(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function hi(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new de(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new de(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new de(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function yi(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new de(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new de(`the ${qr} header is empty \u2014 the only profile this lane accepts is "${jt}" (omit the header for the ordinary lane)`);if(l!==jt)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${jt}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==jt)throw new de(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${jt}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new de("the voice profile is streaming-only \u2014 send stream: true");let u=o?.voice;if(u!==void 0&&(typeof u!="object"||u===null||Array.isArray(u)))throw new de("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let a=u??{};return{flushMaxChars:hi(a,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:hi(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:jr(a,"sentence_flush",!0),includeReasoning:jr(a,"include_reasoning",!1),metadata:jr(a,"metadata",!1)}}var gt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&jl(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(Bl.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var $e=(t,e)=>Object.assign(new Error(e),{status:t}),Gl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Gr=(t,e,n)=>new V(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Hr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof G?$e(404,n.message):n}};async function wi(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw $e(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Gl}`);if(o==="transcription")throw $e(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw $e(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw $e(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof G?$e(404,m.message):m}if(!p)throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof G?$e(404,m.message):m}if(p!=="stt")throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Hr(t,n.stt),i=await Hr(t,e),u=await Hr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Vl({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{a.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof V?Gr("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function _i(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var On=class extends Error{};async function*Vl(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:u,companions:a}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,g=null,v=null,x=[],S=null,w=new Promise((R,k)=>{n&&n.addEventListener("abort",()=>k(new On),{once:!0})}),f=()=>m||n?.aborted===!0,h=async R=>{if(f())return;let k;try{k=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:R}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(N){throw N instanceof V?Gr("tts",a.tts,N):N}let C=k[Symbol.asyncIterator]();v=C;try{for(;;){let N=C.next(),j;try{j=await Promise.race([N,w])}catch(D){if(N.catch(()=>{}),D instanceof On)return;throw D}if(j.done)return;let U=j.value;if(U.type==="error"){let D=U.error&&typeof U.error.message=="string"?U.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${D}`)}if(U.type==="response.completed")return}}finally{v===C&&(v=null)}},y=async()=>{for(;x.length>0&&!f();){let R=x.shift();await h(R)}},b=R=>{if(R===""||f()||(x.push(R),S!==null))return;let k=y();S=k,k.then(()=>{S===k&&(S=null)},C=>{S===k&&(S=null),g??=C})},E=()=>{m=!0,x.length=0;let R=v;if(v=null,R){let k=R.return?.();k&&k.catch(()=>{})}},I=async()=>{for(;x.length>0||S!==null;){let R=S;if(R===null){await h(x.shift());continue}await R}},O=p?new gt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},R=>b(R)):null,_=null;try{let R;try{R=await o.createResponseOn(s,d)}catch(k){throw k instanceof V?Gr("chat",u,k):k}for await(let k of R){if(f())return;let C=k;if(C.type==="error"){yield k;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield k,O?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){O?.flush(),yield k;continue}if(C.type==="response.completed"){_=k.response;continue}}O?.flush(),O?.dispose(),p&&await I(),_!==null&&(yield{type:"response.completed",response:_})}finally{O?.dispose(),E();try{if(g instanceof V)throw g}finally{r?.()}}}var me=(t,e)=>Object.assign(new Error(e),{status:t});function Jl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Wl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var Kl='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function zl(t,e,n,r,o){if(!t.supportsAudio)throw me(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(m){throw m instanceof G?me(404,m.message):m}if(!s){let m=null;if(t.realtimeCompanionsFor)try{m=await t.realtimeCompanionsFor(e)}catch(g){throw g instanceof G?me(404,g.message):g}if(m!==null)return await wi(t,e,m,n,r);throw me(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw me(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(m){throw m instanceof G?me(404,m.message):m}if(i&&!t.openTurnsOn)throw me(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let m;try{m=await t.transcriptStreamFor(e)}catch(g){throw g instanceof G?me(404,g.message):g}if(m!=="stt")throw me(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw me(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Kl}`);if(r==="transcription"&&!i)throw me(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let u;try{u=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(m){throw m instanceof ce?me(503,m.message):m}let a=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,vi.randomUUID)()}`,c={audio:await t.openAudioOn(u,n,l,o).catch(m=>{throw t.releaseSessionHandle?.(u),m})},p={clients:{createResponse:async m=>await t.createResponseOn(u,m,l)},voice:s,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(u,n)),i&&(p.turns=m=>t.openTurnsOn(u,m)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(u)),e!==void 0&&(p.model=e),a!==null&&(p.catalog=a),p}function bi(t,e,n){let r=_i(t,n);return{resolve:async(o,s,i)=>{if(e!==void 0){let u=o.headers.authorization,a=typeof u=="string"?u.trim():"",l=a.startsWith("Bearer ")?a.slice(7).trim():"";if(l===""||l!==e)throw me(401,"invalid local proxy api key")}return zl(r,Jl(o),s,Wl(o),i)}}}var L=class extends Error{},_e=class extends Error{};function se(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Tn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function ht(t,e){if(t!=null)throw new L(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Vr(t){let e=Tn(t);return e!==null&&e<=1?e:null}function Si(t,e){if(!se(t))throw new L("decisions requires a JSON object body");ht(t.prompt_cache_key,"prompt_cache_key"),ht(t.prompt_cache_options,"prompt_cache_options"),ht(t.safety_identifier,"safety_identifier");let n=[],r=Yl(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new L("decisions requires a questions array of 1 to 400 questions");let s={},i=[],u=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=ed(o[l],l,o.length,n);if(u.has(c.key))throw new L(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);u.add(c.key),s[c.key]=d,i.push(c)}let a={model:e,state:r,questions:s};return n.length>0&&(a.media=n),{systemone:a,specs:i}}function Yl(t,e){if(typeof t=="string")return t;if(!se(t)&&!Array.isArray(t))throw new L("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)Ql(o,r,e);return Xl(r)}function Xl(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
30
|
+
${hi(n)}\r
|
|
31
|
+
`),t.destroy()}function Ul(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
32
|
+
`}function Dl(t){Re(process.stdout,t)}function Fl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Fr(t){return t.audioSession?.audio.sessionId??void 0}function jr(t,e){let n=new jt.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==qr)return;r.add(s),s.on("close",()=>{r.delete(s)});let a=O("rtup"),l=Fl(o),d=_=>{(e.log??Dl)(Ul(_))};d({stage:"accept",conn:a,model:l}),s.resume();let c=new AbortController,p=null,m=_=>{p??=_,c.abort(new Error(p))},h=()=>m("client socket closed"),v=()=>m("client socket closed (half-close)"),k=_=>m(`client socket error: ${_.message}`);s.once("close",h),s.once("end",v),s.once("error",k);let S=()=>{s.removeListener("close",h),s.removeListener("end",v),s.removeListener("error",k)},w=_=>{d({stage:"close",conn:a,model:l,..._})},f=null,g=!1,y=null,b=_=>JSON.stringify({type:gi,event_id:O("event"),..._}),x=_=>{if(f!==null){f.readyState===jt.WebSocket.OPEN&&f.send(b(_));return}g||(g=!0,n.handleUpgrade(o,s,i,R=>{f=R,y=[],R.on("message",T=>{y?.push(String(T))}),d({stage:"waiting",conn:a,model:l,status:_.status}),R.send(b(_))}))},A=_=>{let R=_,T=R.session!=null&&typeof R.session.sendResponseCreate=="function",$=R.clients!=null&&typeof R.clients.createResponse=="function";if(!T&&!$)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((P,B)=>{let L=(N,ne)=>{try{let V=Date.now();new qt({ws:N,binding:_,operatorLog:e.operatorLog,...ne.length>0?{replayFrames:ne}:{},onClosed:(re,U)=>{w({while:"live",reason:U.reason});try{e.onSessionEnded?.({req:o,binding:_,connected_ms:Math.max(0,Date.now()-V),reason:U.reason})}catch(H){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${H instanceof Error?H.message:String(H)}
|
|
33
|
+
`)}}}),d({stage:"admit",conn:a,model:l,...Fr(_)===void 0?{}:{session:Fr(_)}}),P()}catch(V){B(V)}};if(f!==null){let N=y??[];y=null,L(f,N);return}n.handleUpgrade(o,s,i,N=>L(N,[]))})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o,c.signal,x).then(async _=>{if(c.signal.aborted){S();let R=Fr(_);try{await _.release?.()}catch(T){w({while:"queued",...R===void 0?{}:{session:R},reason:p??"client socket closed",release_failed:T instanceof Error?T.message:String(T)});return}w({while:"queued",...R===void 0?{}:{session:R},reason:p??"client socket closed",released:!0}),s.destroy();return}S(),await A(_)}).catch(_=>{let R=_ instanceof Br.SessionFailedError?bn(_):null,T=null;if(_!==null&&typeof _=="object"&&"status"in _){let L=_.status;typeof L=="number"&&(T=L)}let $=T??R?.status??502,P=_ instanceof Error?_.message:String(_),B=T!==null?P:R!==null?Ft(R,_ instanceof Br.SessionFailedError&&_.status.sessionId?`session ${_.status.sessionId}`:void 0):fe(_).message;if(w({while:"queued",...c.signal.aborted?{reason:p??"client socket closed"}:{reason:P,status:$}}),f!==null&&!c.signal.aborted){let L=JSON.stringify({type:gi,event_id:O("event"),status:$<500?"rejected":"failed",reason:B});f.readyState===jt.WebSocket.OPEN&&f.send(L),f.close(1011,hi(B));return}s.destroyed||Nl(s,$,B)}).finally(()=>{r.delete(s)})}),async()=>{let o=Date.now()+5e3;for(;r.size>0&&Date.now()<o;)await new Promise(s=>setTimeout(s,25));await new Promise(s=>n.close(()=>s()))}}var bi=require("crypto");var Gr="x-urun-profile",Ht="voice";var de=class extends Error{status=400},Bl=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,ql=/\s/;function jl(t){return Bl.test(t)}function Hr(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new de(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function yi(t,e,n,r={}){let o=t[e];if(o===void 0)return n;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new de(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(o)})`);if(r.min!==void 0&&o<r.min)throw new de(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(o)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&o>r.max)throw new de(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(o)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return o}function wi(t,e){let n=Array.isArray(t)?t[0]:t,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new de(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let o=r,s=o?.profile,i=!1;if(n!=null){let l=n.trim();if(l==="")throw new de(`the ${Gr} header is empty \u2014 the only profile this lane accepts is "${Ht}" (omit the header for the ordinary lane)`);if(l!==Ht)throw new de(`unknown profile "${l}" \u2014 the only profile this lane accepts is "${Ht}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==Ht)throw new de(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${Ht}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new de("the voice profile is streaming-only \u2014 send stream: true");let u=o?.voice;if(u!==void 0&&(typeof u!="object"||u===null||Array.isArray(u)))throw new de("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let a=u??{};return{flushMaxChars:yi(a,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:yi(a,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Hr(a,"sentence_flush",!0),includeReasoning:Hr(a,"include_reasoning",!1),metadata:Hr(a,"metadata",!1)}}var gt=class{constructor(e,n){this.config=e;this.sink=n}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let n=this.boundedCut();this.sink(this.buffer.slice(0,n)),this.buffer=this.buffer.slice(n)}(this.buffer.length>=e||this.config.sentenceFlush&&jl(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let o=e-1;o>0;o--)if(ql.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};var $e=(t,e)=>Object.assign(new Error(e),{status:t}),Vl='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Jr=(t,e,n)=>new J(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Vr=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof G?$e(404,n.message):n}};async function _i(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw $e(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Vl}`);if(o==="transcription")throw $e(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw $e(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!t.openTurnsOn)throw $e(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let p;try{p=await t.supportsTranscription(n.stt)}catch(m){throw m instanceof G?$e(404,m.message):m}if(!p)throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let p;try{p=await t.transcriptStreamFor(n.stt)}catch(m){throw m instanceof G?$e(404,m.message):m}if(p!=="stt")throw $e(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Vr(t,n.stt),i=await Vr(t,e),u=await Vr(t,n.tts),a=await t.openAudioOn(s,r),l=await t.openAudioOn(u,r),d=null,c={clients:{createResponse:p=>{let m=new AbortController;return d=m,Jl({clients:t,chatHandle:i,ttsHandle:u,chatModel:e,companions:n},p,m.signal,()=>{d===m&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{a.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*t.openTurnsOn(s,p)}catch(m){throw m instanceof J?Jr("stt",n.stt,m):m}},composite:!0};return e!==void 0&&(c.model=e),c}function vi(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Gt=class extends Error{};async function*Jl(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:u,companions:a}=t;if(n?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),m=!1,h=null,v=null,k=[],S=null,w=new Promise((R,T)=>{n&&n.addEventListener("abort",()=>T(new Gt),{once:!0})}),f=()=>m||n?.aborted===!0,g=async R=>{if(f())return;let T;try{T=await o.createResponseOn(i,{model:a.tts,input:[{role:"user",content:[{type:"input_text",text:R}]}],stream:!1,...a.voice!==void 0?{voice:a.voice}:{}})}catch(P){throw P instanceof J?Jr("tts",a.tts,P):P}let $=T[Symbol.asyncIterator]();v=$;try{for(;;){let P=$.next(),B;try{B=await Promise.race([P,w])}catch(N){if(P.catch(()=>{}),N instanceof Gt)return;throw N}if(B.done)return;let L=B.value;if(L.type==="error"){let N=L.error&&typeof L.error.message=="string"?L.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(a.tts)}) errored: ${N}`)}if(L.type==="response.completed")return}}finally{v===$&&(v=null)}},y=async()=>{for(;k.length>0&&!f();){let R=k.shift();await g(R)}},b=R=>{if(R===""||f()||(k.push(R),S!==null))return;let T=y();S=T,T.then(()=>{S===T&&(S=null)},$=>{S===T&&(S=null),h??=$})},x=()=>{m=!0,k.length=0;let R=v;if(v=null,R){let T=R.return?.();T&&T.catch(()=>{})}},A=async()=>{for(;k.length>0||S!==null;){let R=S;if(R===null){await g(k.shift());continue}await R}},E=p?new gt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},R=>b(R)):null,_=null;try{let R;try{R=await o.createResponseOn(s,d)}catch($){throw $ instanceof J?Jr("chat",u,$):$}let T=R[Symbol.asyncIterator]();try{for(;;){let $=T.next(),P;try{P=await Promise.race([$,w])}catch(N){if($.catch(()=>{}),N instanceof Gt)break;throw N}if(P.done)break;let B=P.value;if(f())return;let L=B;if(L.type==="error"){yield B;return}if(L.type==="response.output_text.delta"&&typeof L.delta=="string"){yield B,E?.push(L.delta);continue}if(L.type==="response.function_call_arguments.delta"){E?.flush(),yield B;continue}if(L.type==="response.completed"){_=B.response;continue}}}finally{Promise.resolve(T.return?.()).catch(()=>{})}E?.flush(),E?.dispose(),p&&await A(),_!==null&&(yield{type:"response.completed",response:_})}finally{E?.dispose(),x();try{if(h instanceof J)throw h}finally{r?.()}}}var me=(t,e)=>Object.assign(new Error(e),{status:t});function Wl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Kl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}var zl='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Yl(t,e,n,r,o){if(!t.supportsAudio)throw me(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await t.supportsAudio(e)}catch(m){throw m instanceof G?me(404,m.message):m}if(!s){let m=null;if(t.realtimeCompanionsFor)try{m=await t.realtimeCompanionsFor(e)}catch(h){throw h instanceof G?me(404,h.message):h}if(m!==null)return await _i(t,e,m,n,r);throw me(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!t.openAudioOn)throw me(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let i=!1;if(t.supportsTranscription)try{i=await t.supportsTranscription(e)}catch(m){throw m instanceof G?me(404,m.message):m}if(i&&!t.openTurnsOn)throw me(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(i&&t.transcriptStreamFor){let m;try{m=await t.transcriptStreamFor(e)}catch(h){throw h instanceof G?me(404,h.message):h}if(m!=="stt")throw me(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(m)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw me(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${zl}`);if(r==="transcription"&&!i)throw me(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let u;try{u=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(m){throw m instanceof ce?me(503,m.message):m}let a=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,l=`conn_${(0,bi.randomUUID)()}`,c={audio:await t.openAudioOn(u,n,l,o).catch(m=>{throw t.releaseSessionHandle?.(u),m})},p={clients:{createResponse:async m=>await t.createResponseOn(u,m,l)},voice:s,audioSession:c};return t.openVideoOn&&(p.video=()=>t.openVideoOn(u,n)),i&&(p.turns=m=>t.openTurnsOn(u,m)),r==="transcription"&&(p.intent="transcription"),t.releaseSessionHandle&&(p.release=()=>t.releaseSessionHandle(u)),t.endDedicatedSession&&(p.endSession=()=>t.endDedicatedSession(u)),e!==void 0&&(p.model=e),a!==null&&(p.catalog=a),p}function Si(t,e,n){let r=vi(t,n);return{resolve:async(o,s,i)=>{if(e!==void 0){let u=o.headers.authorization,a=typeof u=="string"?u.trim():"",l=a.startsWith("Bearer ")?a.slice(7).trim():"";if(l===""||l!==e)throw me(401,"invalid local proxy api key")}return Yl(r,Wl(o),s,Kl(o),i)}}}var D=class extends Error{},_e=class extends Error{};function se(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function On(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function ht(t,e){if(t!=null)throw new D(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Wr(t){let e=On(t);return e!==null&&e<=1?e:null}function ki(t,e){if(!se(t))throw new D("decisions requires a JSON object body");ht(t.prompt_cache_key,"prompt_cache_key"),ht(t.prompt_cache_options,"prompt_cache_options"),ht(t.safety_identifier,"safety_identifier");let n=[],r=Xl(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new D("decisions requires a questions array of 1 to 400 questions");let s={},i=[],u=new Set;for(let l=0;l<o.length;l++){let{entry:d,spec:c}=td(o[l],l,o.length,n);if(u.has(c.key))throw new D(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);u.add(c.key),s[c.key]=d,i.push(c)}let a={model:e,state:r,questions:s};return n.length>0&&(a.media=n),{systemone:a,specs:i}}function Xl(t,e){if(typeof t=="string")return t;if(!se(t)&&!Array.isArray(t))throw new D("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)Zl(o,r,e);return Ql(r)}function Ql(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
34
34
|
|
|
35
|
-
`)}function
|
|
35
|
+
`)}function Zl(t,e,n){if(!se(t))throw new D("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){ed(t,r,e,n);return}switch(o){case"function_call":case"custom_tool_call":{e.push({text:JSON.stringify({type:o,name:t.name,call_id:t.call_id,arguments:t.arguments,input:t.input})});return}case"function_call_output":case"custom_tool_call_output":{let s=t.output;if(typeof s=="string"){e.push({text:s});return}if(Array.isArray(s)){xi(s,e,n,void 0,!1);return}throw new D(`${o} output must be a string or an array of parts`)}default:throw new D(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function ed(t,e,n,r){e==="assistant"&&ht(t.phase,"assistant message phase");let o=t.content;if(typeof o=="string"){n.push({role:e,text:o});return}if(!Array.isArray(o))throw new D(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!se(s))throw new D("decisions assistant message parts must be JSON objects");if(s.type==="output_text"&&typeof s.text=="string")n.push({role:e,text:s.text});else if(s.type==="refusal"&&typeof s.refusal=="string")n.push({role:e,text:`[refusal] ${s.refusal}`});else throw new D(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}xi(o,n,r,e)}function xi(t,e,n,r,o=!0){for(let s of t){if(!se(s))throw new D("decisions content parts must be JSON objects");switch(ht(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new D("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new D("input_json is not supported in tool output parts \u2014 the tool output parts union is input_text/input_image only (use input_text)");let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new D("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Ri(s));break}default:throw new D(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Ri(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new D("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new D("input_image requires a base64 data URL (data:<mime>;base64,<data>) \u2014 hosted image URLs are not fetched by this endpoint");let[,r,o]=n;if(o==="")throw new D("input_image data URL carries no image data");let s=o.includes("=");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(o)||(s?o.length%4!==0:o.length%4===1))throw new D("input_image data URL payload is not valid base64 (data:<mime>;base64,<base64>)");let i=t.detail;if(i!=null&&i!=="low"&&i!=="high"&&i!=="auto"&&i!=="original")throw new D("input_image detail must be low, high, auto, or original");let u={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(u.detail=i),u}function td(t,e,n,r){if(!se(t))throw new D(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new D(`questions[${e}] type must be predicate, choice, or score (got ${JSON.stringify(o??null)})`);let s=t.name;if(s!==void 0&&typeof s!="string")throw new D(`questions[${e}] name must be a string`);let i=s??null,u=i??`q${e}`,a=nd(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:a,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:u,name:i}};case"choice":{let l=t.choices;if(!Array.isArray(l)||l.length<2||l.length>255)throw new D(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,p=[];for(let v of l){if(!se(v))throw new D(`questions[${e}] choices must be JSON objects`);let k=v.value;if(typeof k!="string"&&typeof k!="boolean")throw new D(`questions[${e}] choice value must be a string or boolean`);let S=String(k);if(c.has(S))throw new D(`questions[${e}] has duplicate choice value ${JSON.stringify(S)} (choices must be unique)`);c.add(S);let w=v.description;if(w!==void 0&&typeof w!="string")throw new D(`questions[${e}] choice description must be a string`);d.push(k),p.push(w)}let m=l.map((v,k)=>({name:String(d[k]),description:p[k]??String(d[k])}));return{entry:{kind:"choice",prompt:a,options:m},spec:{type:o,key:u,name:i,choiceValues:d}}}case"score":{let l=t.levels;if(!Array.isArray(l)||l.length<2||l.length>10)throw new D(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let m of l){if(!se(m)||typeof m.label!="string")throw new D(`questions[${e}] score levels must carry a string label`);if(d.includes(m.label))throw new D(`questions[${e}] has duplicate level label ${JSON.stringify(m.label)}`);d.push(m.label);let h=m.description;if(h!==void 0&&typeof h!="string")throw new D(`questions[${e}] score level description must be a string`);let v=h!==void 0?`${m.label}: ${h}`:m.label;if(c.includes(v))throw new D(`questions[${e}] has duplicate score criterion ${JSON.stringify(v)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(v)}return{entry:{kind:"score",prompt:a,criteria:c},spec:{type:o,key:u,name:i,levelLabels:d}}}}}function nd(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new D(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!se(s))throw new D(`questions[${e}] instruction parts must be JSON objects`);switch(ht(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new D(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new D(`questions[${e}] input_image requires a single-question request \u2014 media is request-wide, so the image-to-question binding cannot be translated`);r.push(Ri(s));break}case"input_json":{let i=s.data;if(!se(i)&&!(Array.isArray(i)&&i.every(se)))throw new D(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new D(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
|
|
36
36
|
|
|
37
|
-
`)}function Ri(t,e){if(!se(e))throw new _e("decision answer was not a JSON object");let n=e.answers;if(!se(n))throw new _e("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!se(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=se(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=Vr(s.noul);if(u===null)throw new _e(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let u=o.choiceValues??[],a=s.choice;if(typeof a!="string")throw new _e(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new _e(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=Tn(s.confidence);if(d===null)throw new _e(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let m=Vr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:u[l],confidence:d,probabilities:c});continue}case"score":{let u=o.levelLabels??[],a=Tn(s.score);if(a===null)throw new _e(`the score answer for "${o.key}" carries no numeric score to translate`);let l=Tn(s.confidence);if(l===null)throw new _e(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<u.length;c++){let p=Vr(i[String(c)]);p!==null&&d.push({value:c,label:u[c],probability:p})}r.push({type:"score",name:o.name,score:a,confidence:l,probabilities:d});continue}}}return r}var ie=class extends Error{};async function Pn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ie(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new ie(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Cn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new ie(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Ei="/v1/images/generations",$n="/v1/images/edits";function Ai(t){return t===Ei||t===$n}var Ii="/v1/images/models";async function Oi(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var q=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},nd=16*1024*1024,Ti=64*1024*1024;function Pi(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 qt(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 Ci(t,e,n,r,o,s){let i=s??(g=>console.error(g)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),a=null;for await(let g of u){if(g.type==="error"){let v=g.error??{},x=typeof v.message=="string"&&v.message.length>0&&ke(v.message)?v.message:null;throw x===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(g)}`),new q(502,"the image upstream failed while serving this request")):new q(502,`image upstream error: ${x}`)}if(g.type==="response.completed"){a=g.response??null;break}}if(a===null)throw new q(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ce(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new q(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Pi(p)===null)throw new q(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function $i(t,e){if(t instanceof q)return t;if(t instanceof Ie)throw t;return t instanceof G?new q(404,t.message):new q(502,pt("image",t,e))}async function Mi(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 qt(r,new q(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 Li(t,e){t&&(t.outputUnits=e.images.length)}function Ni(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 rd={model:!0,prompt:!0,response_format:!0,n:!0};async function Ui(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Ti;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${Ei}`);let s;try{s=JSON.parse((await Pn(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new q(413,p.message):new q(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new q(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!rd[p])throw new q(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let u=i.prompt;if(typeof u!="string"||u.trim().length===0)throw new q(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new q(400,"model must be a string","model");await Oi(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new q(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new q(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",u.length,u.length),!await Mi(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await Ci(n.clients,a,c,n.turn?he(n.turn):void 0,n.turn,r);Li(n.turn,p),Ni(e,p)}catch(p){throw $i(p,r)}}catch(s){if(s instanceof ie){qt(e,new q(413,s.message));return}if(s instanceof q){qt(e,s);return}throw s}}var od={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Di(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ti,s=n.maxImagePartBytes??nd;try{if(t.method!=="POST")throw new q(405,`${String(t.method)} is not supported on ${$n}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new q(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Cn(t,o)}catch(g){throw g instanceof ie?new q(413,g.message):new q(400,String(g instanceof Error?g.message:g))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new q(400,"prompt is required and must be a non-empty string field","prompt");let l=u.get("model");if(l!==null&&typeof l!="string")throw new q(400,"model must be a string field","model");let d=l===null?void 0:l;await Oi(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new q(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let g of u.keys())if(!od[g])throw new q(400,`form field "${g}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,g);let p=[];for(let g of["image","image[]"])for(let v of u.getAll(g)){if(!(v instanceof File))throw new q(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",g);if(v.size>s)throw new q(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,g);let x=new Uint8Array(await v.arrayBuffer()),S=Pi(x);if(S===null)throw new q(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",g);p.push({bytes:x,mime:S})}if(p.length===0)throw new q(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Mi(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:g,mime:v}of p)m.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(g).toString("base64")}`});try{let g=await Ci(n.clients,d,m,n.turn?he(n.turn):void 0,n.turn,r);Li(n.turn,g),Ni(e,g)}catch(g){throw $i(g,r)}}catch(i){if(i instanceof ie){qt(e,new q(413,i.message));return}if(i instanceof q){qt(e,i);return}throw i}}var Ht="/v1/audio/speech";function Wi(t){return t===Ht}var Fi=4096,Bi=18e4,ji=5e3,sd=64*1024*1024,qi=8,Hi=5,Gi=1024*1024,yt="voice_applied",Ln="X-Urun-Voice-Applied",F=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Jr(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 Nn=class extends F{constructor(e){super(502,e)}};function Ki(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function zi(t){return new F(502,`the runtime's ${yt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Ln} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function id(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Yi(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var ad=2;function ud(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>ad)return!1;return!0}function ld(t){let e=24e3,n=2,r=1,o=Buffer.alloc(44);return o.write("RIFF",0,"ascii"),o.writeUInt32LE(36+t,4),o.write("WAVE",8,"ascii"),o.write("fmt ",12,"ascii"),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(e,24),o.writeUInt32LE(e*r*n,28),o.writeUInt16LE(r*n,32),o.writeUInt16LE(16,34),o.write("data",36,"ascii"),o.writeUInt32LE(t,40),o}var Vi=new WeakMap,Mn=new WeakMap;function dd(t,e){let n=Mn.get(t)??0;if(n>=qi)throw new F(503,`this model's speech queue is full \u2014 ${qi} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Hi}s`,void 0,Hi);Mn.set(t,n+1);let r=Vi.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Vi.set(t,s),(async()=>{await r;try{return await e()}finally{Mn.set(t,(Mn.get(t)??1)-1),o()}})()}async function cd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new F(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof V))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{clearTimeout(s)})}function Qe(t,e){if(t instanceof F)return t;if(t instanceof Ie)throw t;return t instanceof G?new F(404,t.message):new F(502,pt("speech",t,e))}async function Ji(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return dd(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,g=!1,v,x=new Promise(R=>{v=R}),S=[],w,f=!1,h=null,y=()=>{h!==null&&(clearTimeout(w),w=setTimeout(()=>{f=!0,h?.()},o.capMs))},b=()=>{m&&!g&&S.length>=o.quietRunFrames&&(g=!0,v())},E=e.onOutputAudio(R=>{let k=Buffer.from(R,"base64");if(k.byteLength===0)return;y();let C=ud(k);if(!p){if(C)return;p=!0}if(C){S.push(k),b();return}for(let N of S)c(N);S.length=0,c(k),b()}),I=null,O,_;try{_=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let k=()=>(clearTimeout(O),new Promise(U=>{O=setTimeout(U,s.capMs)})),C=k(),N=!1;for(;;){let U=_.next(),D=await Promise.race([U,C]);if(D===void 0){N=!0,U.catch(()=>{});break}if(D.done)break;let oe=D.value;if(C=k(),oe.type==="error"){let J=oe.error??{};await _.return?.();let ne=typeof J.message=="string"&&J.message.length>0&&ke(J.message)?J.message:null;throw ne===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(oe)}`),new F(502,"the speech upstream failed while serving this request")):new F(502,`speech upstream error: ${ne}`)}if(oe.type==="response.completed"){I=oe.response??null,m=!0,a?.(I),b(),await _.return?.();break}}if(clearTimeout(O),N)throw new F(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(I===null)throw new F(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let j=new Promise(U=>{h=U});if(y(),await Promise.race([x,j]),clearTimeout(w),w=void 0,h=null,r.voice!==void 0){let U=I[yt];if(typeof U!="string"||U!==r.voice){let D=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof U=="string"?`${yt} ${JSON.stringify(U)}`:`no ${yt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw g?new Nn(D):new F(502,D)}}if(!p)throw new F(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(f&&!g&&S.length<1)throw new F(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return I}catch(R){throw R instanceof Nn||await cd(t,n,_,s.returnBoundMs),R}finally{clearTimeout(w),clearTimeout(O),E()}})}function pd(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Ln)),t.write(u,a=>{a||(s+=u.byteLength,Yi(e,s))}),t.writableLength>Gi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Gi} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[yt];if(typeof a=="string"){if(!Ki(a))throw zi(a);t.addTrailers({[Ln]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function fd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Qe(s,r)}return o?!0:(Jr(n,new F(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var md={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},gd="wav, pcm";async function Xi(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??sd,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${Ht}`);let u;try{u=JSON.parse((await Pn(t,o)).toString("utf8")||"{}")}catch(h){throw h instanceof ie?new F(413,h.message):new F(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new F(400,"request body must be a JSON object");let a=u;for(let h of Object.keys(a))if(!md[h])throw new F(400,`request field "${h}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,h);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new F(400,"input is required and must be a non-empty string","input");if(l.length>Fi)throw new F(400,`input is ${l.length} chars \u2014 over the ${Fi}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new F(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new F(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new F(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Ht} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(h){throw Qe(h,r)}if(p.defect!==null)throw new F(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new F(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let g=a.response_format??"wav";if(g!=="wav"&&g!=="pcm")throw new F(400,`response_format ${JSON.stringify(g)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${gd} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new F(400,"stream_format, when present, must be a string","stream_format");let v=a.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new F(400,"speed, when present, must be a number","speed");if(v!==1)throw new F(400,`speed=${JSON.stringify(v)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let x=a.instructions;if(x!==void 0){if(typeof x!="string")throw new F(400,"instructions, when present, must be a string","instructions");if(x.trim().length>0)throw new F(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await id(n.turn,n.clients,d);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await fd(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new F(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new F(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new F(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let w;try{w=await n.clients.speechSessionHandle(d)}catch(h){throw Qe(h,r)}let f;try{f=await n.clients.openAudioOn(w)}catch(h){throw Qe(h,r)}n.turn&&(n.turn.sessionId=f.sessionId);try{if(g==="wav"){let h=[],y=await Ji(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Bi,returnBoundMs:n.turnReturnBoundMs??ji},i,E=>h.push(E),E=>{n.turn&&(n.turn.outputSeconds=Ce(E))},r);if(y===null||i())return;let b=Buffer.concat(h);if(m===void 0){let E=y[yt];if(typeof E=="string"){if(!Ki(E))throw zi(E);e.setHeader(Ln,E)}}Yi(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([ld(b.byteLength),b]))}else{let h=pd(e,n.turn,i,m===void 0),y;try{y=await Ji(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Bi,returnBoundMs:n.turnReturnBoundMs??ji},i,h.sink,b=>{n.turn&&(n.turn.outputSeconds=Ce(b))},r)}catch(b){let E=Qe(b,r);if(!h.started())throw E;n.turn&&(n.turn.streamError=!0),h.fail(E);return}if(y===null)return;try{await h.finish(y)}catch(b){let E=Qe(b,r);n.turn&&(n.turn.streamError=!0),h.fail(E);return}}}catch(h){throw Qe(h,r)}}catch(u){if(u instanceof ie){Jr(e,new F(413,u.message));return}if(u instanceof F){Jr(e,u);return}throw u}}var Un="/v1/audio/transcriptions";function Qi(t){return t===Un}var Zi="/v1/audio/models",hd=16*1024*1024,yd=64*1024*1024,Z=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Wr(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 ea(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 wd(t){if(!ea(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,l=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,d=t[u+14]|t[u+15]<<8;n={sampleRate:l,channels:a,bitsPerSample:d}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function _d(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function vd(t,e){t&&(t.outputUnits=e.seconds)}async function bd(t,e,n,r,o,s,i){let u=i??(c=>console.error(c)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of a){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",g=typeof p.message=="string"&&p.message.length>0&&ke(p.message)?p.message:null;throw g===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Z(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Z(m==="invalid_request_error"?400:502,`transcription upstream error: ${g}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Z(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Ce(d)),dt(l,d)}function ta(t,e){if(t instanceof Z)return t;if(t instanceof Ie)throw t;return t instanceof G?new Z(404,t.message):new Z(502,pt("transcription",t,e))}async function Sd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw ta(s,r)}return o?!0:(Wr(n,new Z(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 kd=new Set(["file","model","language","response_format"]);async function na(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??yd,s=n.maxAudioPartBytes??hd;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${Un}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Z(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Cn(t,o)}catch(w){throw w instanceof ie?new Z(413,w.message):new Z(400,String(w instanceof Error?w.message:w))}let a=new Map;for(let w of u.keys()){if(!kd.has(w))throw new Z(400,`form field "${w}" 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.`,w);a.set(w,(a.get(w)??0)+1)}for(let[w,f]of a)if(f>1)throw new Z(400,`form field "${w}" appears ${f} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,w);let l=u.get("model");if(l!==null&&typeof l!="string")throw new Z(400,"model must be a string field","model");let d=l===null?void 0:l,c=u.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Z(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=u.get("response_format")??"json";if(m!=="json")throw new Z(400,`response_format ${JSON.stringify(m)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let g=u.get("file");if(!(g instanceof File))throw new Z(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(g.size>s)throw new Z(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await g.arrayBuffer());if(!ea(v))throw new Z(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let x=wd(v);if(x===null)throw new Z(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 _d(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await Sd(n.transcriptionModels,d,e,r))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let w=await bd(n.clients,d,S,p,n.turn?he(n.turn):void 0,n.turn,r);vd(n.turn,x),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:w}))}catch(w){throw ta(w,r)}}catch(i){if(i instanceof ie){Wr(e,new Z(413,i.message));return}if(i instanceof Z){Wr(e,i);return}throw i}}var oa="/v1/usage/requests",ra=1e4,xd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,je=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},wt=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var sa=1024*1024;function Kr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new je(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new je(`"${e}" must be an array of uuid strings`);if(n.length>ra)throw new je(`"${e}" carries ${n.length} ids; at most ${ra} 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"||!xd.test(s))throw new je(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function ia(t){return Kr(t,"inference_ids")}function Dn(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 wt(`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 wt(`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 qn=require("@urun-sh/core");var zr="/partners/huggingface/v1/billing/requests";function Rd(t){return Kr(t,"requestIds")}function Ed(t){return t>=200&&t<=399}function Ad(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ed(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function aa(t,e){let n=Rd(t),r=await e(n);return Dn(r,n),Ad(r)}var Id={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function Od(t){return Id[t]??null}var ca=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Td(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Pd(t){return t==="surface"}function Cd(t){let e=t?.ledgerFailureReason;return ca.includes(e)?e:"unknown"}var $d=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],ua=["priced","unpriced"],Md={written:ua,already_written:ua,skipped:$d,failed:ca},Zm=Object.entries(Md).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Ld(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Nd(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 Ud=256,la=4096,Vt=12e4,Dd=250,Fd=8e3,Jt=[],da=new Set,Wt=0,Gt=!1;var Bd=new Set;function jd(){return Wt===0&&Jt.length===0}function qd(){if(jd()){Gt=!1;for(let t of[...Bd])t()}}function pa(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
38
|
-
`}function Hd(t){Re(process.stdout,t)}function fa(t,e){try{t(e)}catch{}}function ma(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Hd,o=Od(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),fa(r,pa("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let u=e.catalog;if(u.kind==="unresolved"){i("model_unresolved",u.reason);return}let a;if(u.kind==="catalog")a={model_id:u.model_id,identity_kind:"catalog_model",variant:u.variant};else{if(u.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}a={model_id:u.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:Nd(e),completed_at:e.ts,billable_outcome:Ld(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(Jt.length>=la){i("queue_full",`${Jt.length} ledger writes are already waiting (capacity ${la}, ${Wt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Jt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Wt<Ud&&(Wt+=1,Gd())}async function Gd(){try{for(;;){let t=Vd();if(t===void 0)return;da.add(t);try{await Jd(t)}finally{da.delete(t)}}}finally{Wt-=1,qd()}}function Vd(){let t=Date.now();for(;;){let e=Jt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Vt)return e;_t(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 ${Vt}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 Jd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);_t(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=Td(o);if(s!==null){_t(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=Cd(o),u=Date.now()-t.queuedAt;if(Gt){_t(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:u,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Pd(i)&&u<Vt){if(await Kd(Wd(t.attempts)),Gt||Date.now()-t.queuedAt>=Vt){let a=Date.now()-t.queuedAt;_t(t,{outcome:"failed",reason:Gt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Gt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${Vt}ms dwell bound (waited ${a}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}_t(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:u,error:o instanceof Error?o.message:String(o)});return}}}function Wd(t){return Math.min(Fd,Dd*2**Math.max(0,t-1))}function Kd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function _t(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;fa(t.report,pa(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Qr(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function zd(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ae(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function K(t,e,n,r="invalid_request_error",o){ae(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Zr(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Te(r),u=i??xe(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let a=r?.code??null,l=o==="invalid_request_error"?400:a==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),ae(t,l,{error:{message:u,type:o,code:a}})}function Ee(t,e,n,r){ae(t,e,{type:"error",error:{type:n,message:r}})}function vt(t,e,n){if(e==="anthropic"){ae(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ae(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Yd=64*1024*1024,Kt=class extends Error{};async function ga(t,e=Yd){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Kt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ze(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function wa(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:null,o=r(n.input_tokens),s=r(n.output_tokens),i=a=>a??0,u=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let a={input_tokens:i(o),output_tokens:i(s),total_tokens:u};return o===null||s===null?{kind:"partial",usage:a}:{kind:"counts",usage:a}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:u}}}function Fn(t){let e=wa(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ha(t){let e=Fn(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Xd(t)},completion_tokens_details:{reasoning_tokens:0}}}function Xd(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function Qd(t,e){let n=wa(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function Zd(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let l=n[a];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),u=r("total_ms");return o===null||s===null||i===null||u===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:u}}function ec(t,e){let n=Zd(e);n&&(t.timing=n),t.outputSeconds=Ce(e)}function et(t,e){Qd(t,e),ec(t,e)}async function Hn(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 _a(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 tc(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 Bn=class extends Error{};function nc(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 Bn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function rc(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:nc(n.role,n.content)})}return e}function Yr(t){return ut(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 oc(t,e,n,r,o,s,i){let u=Mt(s.id),a=t.stream===!0;if(s.model=ue(t),s.stream=a,await Hn(s,e,typeof t.model=="string"?t.model:void 0),a){let w;try{w=await Nt({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(f){if(f instanceof G){vt(r,"openai",f);return}if(f instanceof ye){K(r,f.status,f.message);return}if(f instanceof be||f instanceof ce){r.setHeader("retry-after","2"),K(r,503,f.message,"capacity_error");return}throw f}Qr(r);for await(let f of w.events){if(f.type==="error"){s.streamError=!0;let h=f.error,y=Te(h),b=y??xe(s.id);y===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(f)}`),r.write(`event: error
|
|
39
|
-
data: ${JSON.stringify({error:{message:b,type:
|
|
37
|
+
`)}function Ei(t,e){if(!se(e))throw new _e("decision answer was not a JSON object");let n=e.answers;if(!se(n))throw new _e("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!se(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=se(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let u=Wr(s.noul);if(u===null)throw new _e(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:u});continue}case"choice":{let u=o.choiceValues??[],a=s.choice;if(typeof a!="string")throw new _e(`the choice answer for "${o.key}" carries no string choice`);let l=u.findIndex(p=>String(p)===a);if(l===-1)throw new _e(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(a)})`);let d=On(s.confidence);if(d===null)throw new _e(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let p of u){let m=Wr(i[String(p)]);m!==null&&c.push({value:p,probability:m})}r.push({type:"choice",name:o.name,choice:u[l],confidence:d,probabilities:c});continue}case"score":{let u=o.levelLabels??[],a=On(s.score);if(a===null)throw new _e(`the score answer for "${o.key}" carries no numeric score to translate`);let l=On(s.confidence);if(l===null)throw new _e(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<u.length;c++){let p=Wr(i[String(c)]);p!==null&&d.push({value:c,label:u[c],probability:p})}r.push({type:"score",name:o.name,score:a,confidence:l,probabilities:d});continue}}}return r}var ie=class extends Error{};async function Pn(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ie(`request body exceeds the ${e}-byte limit`);let r=[],o=0;for await(let s of t){let i=s;if(o+=i.length,o>e)throw new ie(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Cn(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let u=await n.next();if(u.done){i.close();return}if(r+=u.value.length,r>e){i.error(new ie(`request body exceeds the ${e}-byte limit`));return}i.enqueue(u.value)}catch(u){i.error(u)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[l,d]of Object.entries(t.headers))if(typeof d=="string")i.set(l,d);else if(Array.isArray(d))for(let c of d)i.append(l,c);let u={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,u).formData()}catch(i){throw i instanceof ie?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Ai="/v1/images/generations",$n="/v1/images/edits";function Ii(t){return t===Ai||t===$n}var Ti="/v1/images/models";async function Oi(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var j=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},rd=16*1024*1024,Pi=64*1024*1024;function Ci(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 Vt(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 $i(t,e,n,r,o,s){let i=s??(h=>console.error(h)),u=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),a=null;for await(let h of u){if(h.type==="error"){let v=h.error??{},k=typeof v.message=="string"&&v.message.length>0&&ke(v.message)?v.message:null;throw k===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(h)}`),new j(502,"the image upstream failed while serving this request")):new j(502,`image upstream error: ${k}`)}if(h.type==="response.completed"){a=h.response??null;break}}if(a===null)throw new j(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Ce(a));let l=a.images;if(!Array.isArray(l)||l.length!==1||typeof l[0]!="string"||l[0].length===0)throw new j(502,`image upstream returned ${Array.isArray(l)?l.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let d=[],c=l[0].startsWith("data:")?l[0].slice(l[0].indexOf(";base64,")+8):l[0],p=Buffer.from(c,"base64");if(Ci(p)===null)throw new j(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${p.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Mi(t,e){if(t instanceof j)return t;if(t instanceof Ie)throw t;return t instanceof G?new j(404,t.message):new j(502,pt("image",t,e))}async function Li(t,e,n,r){if(await t(e,n))return!0;let o=n==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return Vt(r,new j(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 Ni(t,e){t&&(t.outputUnits=e.images.length)}function Ui(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 od={model:!0,prompt:!0,response_format:!0,n:!0};async function Di(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Pi;try{if(t.method!=="POST")throw new j(405,`${String(t.method)} is not supported on ${Ai}`);let s;try{s=JSON.parse((await Pn(t,o)).toString("utf8")||"{}")}catch(p){throw p instanceof ie?new j(413,p.message):new j(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new j(400,"request body must be a JSON object");let i=s;for(let p of Object.keys(i))if(!od[p])throw new j(400,`request field "${p}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,p);let u=i.prompt;if(typeof u!="string"||u.trim().length===0)throw new j(400,"prompt is required and must be a non-empty string","prompt");let a=i.model===void 0?void 0:i.model;if(a!==void 0&&typeof a!="string")throw new j(400,"model must be a string","model");await Oi(n.turn,n.clients,a);let l=i.n??1;if(l!==1)throw new j(400,`n=${JSON.stringify(l)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new j(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",u.length,u.length),!await Li(n.imageModels,a,"generation",e))return;let c=[{type:"input_text",text:u}];try{let p=await $i(n.clients,a,c,n.turn?he(n.turn):void 0,n.turn,r);Ni(n.turn,p),Ui(e,p)}catch(p){throw Mi(p,r)}}catch(s){if(s instanceof ie){Vt(e,new j(413,s.message));return}if(s instanceof j){Vt(e,s);return}throw s}}var sd={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Fi(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Pi,s=n.maxImagePartBytes??rd;try{if(t.method!=="POST")throw new j(405,`${String(t.method)} is not supported on ${$n}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new j(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Cn(t,o)}catch(h){throw h instanceof ie?new j(413,h.message):new j(400,String(h instanceof Error?h.message:h))}let a=u.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new j(400,"prompt is required and must be a non-empty string field","prompt");let l=u.get("model");if(l!==null&&typeof l!="string")throw new j(400,"model must be a string field","model");let d=l===null?void 0:l;await Oi(n.turn,n.clients,d);let c=u.get("response_format")??"b64_json";if(c!=="b64_json")throw new j(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let h of u.keys())if(!sd[h])throw new j(400,`form field "${h}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,h);let p=[];for(let h of["image","image[]"])for(let v of u.getAll(h)){if(!(v instanceof File))throw new j(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",h);if(v.size>s)throw new j(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,h);let k=new Uint8Array(await v.arrayBuffer()),S=Ci(k);if(S===null)throw new j(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",h);p.push({bytes:k,mime:S})}if(p.length===0)throw new j(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",a.length,a.length),!await Li(n.imageModels,d,"edit",e))return;let m=[{type:"input_text",text:a}];for(let{bytes:h,mime:v}of p)m.push({type:"input_image",image_url:`data:${v};base64,${Buffer.from(h).toString("base64")}`});try{let h=await $i(n.clients,d,m,n.turn?he(n.turn):void 0,n.turn,r);Ni(n.turn,h),Ui(e,h)}catch(h){throw Mi(h,r)}}catch(i){if(i instanceof ie){Vt(e,new j(413,i.message));return}if(i instanceof j){Vt(e,i);return}throw i}}var Jt="/v1/audio/speech";function Ki(t){return t===Jt}var Bi=4096,qi=18e4,ji=5e3,id=64*1024*1024,Hi=8,Gi=5,Vi=1024*1024,yt="voice_applied",Ln="X-Urun-Voice-Applied",F=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Kr(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 Nn=class extends F{constructor(e){super(502,e)}};function zi(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n!==9&&!(n>=32&&n<=126)&&!(n>=128&&n<=255))return!1}return!0}function Yi(t){return new F(502,`the runtime's ${yt} receipt ${JSON.stringify(t)} cannot be relayed as the ${Ln} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function ad(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Xi(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var ud=2;function ld(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>ud)return!1;return!0}function dd(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 Ji=new WeakMap,Mn=new WeakMap;function cd(t,e){let n=Mn.get(t)??0;if(n>=Hi)throw new F(503,`this model's speech queue is full \u2014 ${Hi} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${Gi}s`,void 0,Gi);Mn.set(t,n+1);let r=Ji.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ji.set(t,s),(async()=>{await r;try{return await e()}finally{Mn.set(t,(Mn.get(t)??1)-1),o()}})()}async function pd(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new F(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await t.evictSpeechSession(e)}catch(i){if(!(i instanceof J))throw i}if(n?.return===void 0)return;let o=Promise.resolve(n.return()).then(()=>{},()=>{}),s;await Promise.race([o,new Promise(i=>{s=setTimeout(i,r)})]).finally(()=>{clearTimeout(s)})}function Ze(t,e){if(t instanceof F)return t;if(t instanceof Ie)throw t;return t instanceof G?new F(404,t.message):new F(502,pt("speech",t,e))}async function Wi(t,e,n,r,o,s,i,u,a,l){let d=l??(p=>console.error(p)),c=u??(()=>{});return cd(e,async()=>{if(i?.()===!0)return null;let p=!1,m=!1,h=!1,v,k=new Promise(R=>{v=R}),S=[],w,f=!1,g=null,y=()=>{g!==null&&(clearTimeout(w),w=setTimeout(()=>{f=!0,g?.()},o.capMs))},b=()=>{m&&!h&&S.length>=o.quietRunFrames&&(h=!0,v())},x=e.onOutputAudio(R=>{let T=Buffer.from(R,"base64");if(T.byteLength===0)return;y();let $=ld(T);if(!p){if($)return;p=!0}if($){S.push(T),b();return}for(let P of S)c(P);S.length=0,c(T),b()}),A=null,E,_;try{_=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let T=()=>(clearTimeout(E),new Promise(L=>{E=setTimeout(L,s.capMs)})),$=T(),P=!1;for(;;){let L=_.next(),N=await Promise.race([L,$]);if(N===void 0){P=!0,L.catch(()=>{});break}if(N.done)break;let ne=N.value;if($=T(),ne.type==="error"){let V=ne.error??{};await _.return?.();let re=typeof V.message=="string"&&V.message.length>0&&ke(V.message)?V.message:null;throw re===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(ne)}`),new F(502,"the speech upstream failed while serving this request")):new F(502,`speech upstream error: ${re}`)}if(ne.type==="response.completed"){A=ne.response??null,m=!0,a?.(A),b(),await _.return?.();break}}if(clearTimeout(E),P)throw new F(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(A===null)throw new F(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let B=new Promise(L=>{g=L});if(y(),await Promise.race([k,B]),clearTimeout(w),w=void 0,g=null,r.voice!==void 0){let L=A[yt];if(typeof L!="string"||L!==r.voice){let N=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof L=="string"?`${yt} ${JSON.stringify(L)}`:`no ${yt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw h?new Nn(N):new F(502,N)}}if(!p)throw new F(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(f&&!h&&S.length<1)throw new F(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return A}catch(R){throw R instanceof Nn||await pd(t,n,_,s.returnBoundMs),R}finally{clearTimeout(w),clearTimeout(E),x()}})}function fd(t,e,n,r){let o=!1,s=0,i=u=>{t.destroy(u instanceof Error?u:new Error(String(u)))};return{sink(u){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",Ln)),t.write(u,a=>{a||(s+=u.byteLength,Xi(e,s))}),t.writableLength>Vi&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Vi} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(u){if(!n()){if(r){let a=u[yt];if(typeof a=="string"){if(!zi(a))throw Yi(a);t.addTrailers({[Ln]:a})}}await new Promise(a=>{t.end(()=>a())})}},fail:i}}async function md(t,e,n,r){let o;try{o=await t(e)}catch(s){throw Ze(s,r)}return o?!0:(Kr(n,new F(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var gd={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},hd="wav, pcm";async function Qi(t,e,n){let r=n.operatorLog??(u=>console.error(u)),o=n.maxBodyBytes??id,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new F(405,`${String(t.method)} is not supported on ${Jt}`);let u;try{u=JSON.parse((await Pn(t,o)).toString("utf8")||"{}")}catch(g){throw g instanceof ie?new F(413,g.message):new F(400,"request body is not valid JSON")}if(u===null||typeof u!="object"||Array.isArray(u))throw new F(400,"request body must be a JSON object");let a=u;for(let g of Object.keys(a))if(!gd[g])throw new F(400,`request field "${g}" 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.`,g);let l=a.input;if(typeof l!="string"||l.trim().length===0)throw new F(400,"input is required and must be a non-empty string","input");if(l.length>Bi)throw new F(400,`input is ${l.length} chars \u2014 over the ${Bi}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new F(400,"model must be a string","model");let c=a.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new F(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new F(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${Jt} against a stale copy of the list`);let p;try{p=await n.clients.speechVoices(d)}catch(g){throw Ze(g,r)}if(p.defect!==null)throw new F(500,`the voice set for this model cannot be resolved: ${p.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let m=typeof c=="string"?c:void 0;if(m!==void 0&&p.published.length>0&&!p.published.includes(m))throw new F(400,`voice ${JSON.stringify(m)} is not one of the voices this model publishes \u2014 accepted voices: ${p.published.join(", ")}`,"voice");let h=a.response_format??"wav";if(h!=="wav"&&h!=="pcm")throw new F(400,`response_format ${JSON.stringify(h)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${hd} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new F(400,"stream_format, when present, must be a string","stream_format");let v=a.speed;if(v!==void 0){if(typeof v!="number"||!Number.isFinite(v))throw new F(400,"speed, when present, must be a number","speed");if(v!==1)throw new F(400,`speed=${JSON.stringify(v)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let k=a.instructions;if(k!==void 0){if(typeof k!="string")throw new F(400,"instructions, when present, must be a string","instructions");if(k.trim().length>0)throw new F(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await ad(n.turn,n.clients,d);let S=Buffer.byteLength(JSON.stringify(a));if(n.stats?.request("audio_speech",S,S),!await md(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new F(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof n.clients.speechSessionHandle!="function")throw new F(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof n.clients.evictSpeechSession!="function")throw new F(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let w;try{w=await n.clients.speechSessionHandle(d)}catch(g){throw Ze(g,r)}let f;try{f=await n.clients.openAudioOn(w)}catch(g){throw Ze(g,r)}n.turn&&(n.turn.sessionId=f.sessionId);try{if(h==="wav"){let g=[],y=await Wi(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??qi,returnBoundMs:n.turnReturnBoundMs??ji},i,x=>g.push(x),x=>{n.turn&&(n.turn.outputSeconds=Ce(x))},r);if(y===null||i())return;let b=Buffer.concat(g);if(m===void 0){let x=y[yt];if(typeof x=="string"){if(!zi(x))throw Yi(x);e.setHeader(Ln,x)}}Xi(n.turn,b.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([dd(b.byteLength),b]))}else{let g=fd(e,n.turn,i,m===void 0),y;try{y=await Wi(n.clients,f,w,{model:d,text:l,...m!==void 0?{voice:m}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??qi,returnBoundMs:n.turnReturnBoundMs??ji},i,g.sink,b=>{n.turn&&(n.turn.outputSeconds=Ce(b))},r)}catch(b){let x=Ze(b,r);if(!g.started())throw x;n.turn&&(n.turn.streamError=!0),g.fail(x);return}if(y===null)return;try{await g.finish(y)}catch(b){let x=Ze(b,r);n.turn&&(n.turn.streamError=!0),g.fail(x);return}}}catch(g){throw Ze(g,r)}}catch(u){if(u instanceof ie){Kr(e,new F(413,u.message));return}if(u instanceof F){Kr(e,u);return}throw u}}var Un="/v1/audio/transcriptions";function Zi(t){return t===Un}var ea="/v1/audio/models",yd=16*1024*1024,wd=64*1024*1024,Z=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function zr(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 ta(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 _d(t){if(!ta(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,u=e+8;if(s==="fmt "&&u+16<=t.length){let a=t[u+2]|t[u+3]<<8,l=(t[u+4]|t[u+5]<<8|t[u+6]<<16|t[u+7]<<24)>>>0,d=t[u+14]|t[u+15]<<8;n={sampleRate:l,channels:a,bitsPerSample:d}}else if(s==="data"){let a=t.length-u;r=Math.min(i===0||i===4294967295?a:i,a)}e=u+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function vd(t,e,n){if(t){if(t.model=ue({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function bd(t,e){t&&(t.outputUnits=e.seconds)}async function Sd(t,e,n,r,o,s,i){let u=i??(c=>console.error(c)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),l=[],d=null;for await(let c of a){if(l.push(c),c.type==="error"){let p=c.error??{},m=typeof p.type=="string"?p.type:"upstream_error",h=typeof p.message=="string"&&p.message.length>0&&ke(p.message)?p.message:null;throw h===null?(u(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new Z(m==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new Z(m==="invalid_request_error"?400:502,`transcription upstream error: ${h}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new Z(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Ce(d)),dt(l,d)}function na(t,e){if(t instanceof Z)return t;if(t instanceof Ie)throw t;return t instanceof G?new Z(404,t.message):new Z(502,pt("transcription",t,e))}async function kd(t,e,n,r){let o;try{o=await t(e)}catch(s){throw na(s,r)}return o?!0:(zr(n,new Z(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 xd=new Set(["file","model","language","response_format"]);async function ra(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??wd,s=n.maxAudioPartBytes??yd;try{if(t.method!=="POST")throw new Z(405,`${String(t.method)} is not supported on ${Un}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new Z(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let u;try{u=await Cn(t,o)}catch(w){throw w instanceof ie?new Z(413,w.message):new Z(400,String(w instanceof Error?w.message:w))}let a=new Map;for(let w of u.keys()){if(!xd.has(w))throw new Z(400,`form field "${w}" 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.`,w);a.set(w,(a.get(w)??0)+1)}for(let[w,f]of a)if(f>1)throw new Z(400,`form field "${w}" appears ${f} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,w);let l=u.get("model");if(l!==null&&typeof l!="string")throw new Z(400,"model must be a string field","model");let d=l===null?void 0:l,c=u.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new Z(400,"language, when present, must be a non-empty string","language");let p=c===null?void 0:c,m=u.get("response_format")??"json";if(m!=="json")throw new Z(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 h=u.get("file");if(!(h instanceof File))throw new Z(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(h.size>s)throw new Z(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let v=new Uint8Array(await h.arrayBuffer());if(!ta(v))throw new Z(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let k=_d(v);if(k===null)throw new Z(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 vd(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",v.length,v.length),!await kd(n.transcriptionModels,d,e,r))return;let S=[{type:"input_audio",input_audio:{data:Buffer.from(v).toString("base64"),format:"wav"}}];try{let w=await Sd(n.clients,d,S,p,n.turn?he(n.turn):void 0,n.turn,r);bd(n.turn,k),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:w}))}catch(w){throw na(w,r)}}catch(i){if(i instanceof ie){zr(e,new Z(413,i.message));return}if(i instanceof Z){zr(e,i);return}throw i}}var sa="/v1/usage/requests",oa=1e4,Rd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,qe=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},wt=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}};var ia=1024*1024;function Yr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new qe(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new qe(`"${e}" must be an array of uuid strings`);if(n.length>oa)throw new qe(`"${e}" carries ${n.length} ids; at most ${oa} 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"||!Rd.test(s))throw new qe(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function aa(t){return Yr(t,"inference_ids")}function Dn(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 wt(`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 wt(`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 jn=require("@urun-sh/core");var Xr="/partners/huggingface/v1/billing/requests";function Ed(t){return Yr(t,"requestIds")}function Ad(t){return t>=200&&t<=399}function Id(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ad(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function ua(t,e){let n=Ed(t),r=await e(n);return Dn(r,n),Id(r)}var Td={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/decisions":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text","/v1/realtime":"realtime"};function Od(t){return Td[t]??null}var pa=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Pd(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Cd(t){return t==="surface"}function $d(t){let e=t?.ledgerFailureReason;return pa.includes(e)?e:"unknown"}var Md=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],la=["priced","unpriced"],Ld={written:la,already_written:la,skipped:Md,failed:pa},eg=Object.entries(Ld).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Nd(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Ud(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 Dd=256,da=4096,Kt=12e4,Fd=250,Bd=8e3,zt=[],ca=new Set,Yt=0,Wt=!1;var qd=new Set;function jd(){return Yt===0&&zt.length===0}function Hd(){if(jd()){Wt=!1;for(let t of[...qd])t()}}function fa(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
38
|
+
`}function Gd(t){Re(process.stdout,t)}function ma(t,e){try{t(e)}catch{}}function ga(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Gd,o=Od(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),ma(r,fa("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:d,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let u=e.catalog;if(u.kind==="unresolved"){i("model_unresolved",u.reason);return}let a;if(u.kind==="catalog")a={model_id:u.model_id,identity_kind:"catalog_model",variant:u.variant};else{if(u.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}a={model_id:u.model,identity_kind:"caller_org_app",variant:null}}let l={inference_id:e.inference_id,...a,task:o,http_status:e.status,started_at:Ud(e),completed_at:e.ts,billable_outcome:Nd(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,output_seconds:e.output_seconds,session_seconds:e.session_seconds,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(zt.length>=da){i("queue_full",`${zt.length} ledger writes are already waiting (capacity ${da}, ${Yt} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}zt.push({entry:l,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),Yt<Dd&&(Yt+=1,Vd())}async function Vd(){try{for(;;){let t=Jd();if(t===void 0)return;ca.add(t);try{await Wd(t)}finally{ca.delete(t)}}}finally{Yt-=1,Hd()}}function Jd(){let t=Date.now();for(;;){let e=zt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<Kt)return e;_t(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 ${Kt}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 Wd(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);_t(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=Pd(o);if(s!==null){_t(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=$d(o),u=Date.now()-t.queuedAt;if(Wt){_t(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:u,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Cd(i)&&u<Kt){if(await zd(Kd(t.attempts)),Wt||Date.now()-t.queuedAt>=Kt){let a=Date.now()-t.queuedAt;_t(t,{outcome:"failed",reason:Wt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:Wt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:a,error:`this row's backoff outlived the ${Kt}ms dwell bound (waited ${a}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}_t(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:u,error:o instanceof Error?o.message:String(o)});return}}}function Kd(t){return Math.min(Bd,Fd*2**Math.max(0,t-1))}function zd(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function _t(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;ma(t.report,fa(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function eo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Yd(t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),t.flushHeaders(),t.socket?.setNoDelay(!0)}function ae(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function K(t,e,n,r="invalid_request_error",o){ae(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function to(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Oe(r),u=i??xe(n?.inferenceId??null);i===null&&s(`[caller-message-boundary] upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(e)}`);let a=r?.code??null,l=o==="invalid_request_error"?400:a==="queue_timeout"?429:502;l===429&&t.setHeader("retry-after","30"),ae(t,l,{error:{message:u,type:o,code:a}})}function Ee(t,e,n,r){ae(t,e,{type:"error",error:{type:n,message:r}})}function vt(t,e,n){if(e==="anthropic"){ae(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}ae(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Xd=64*1024*1024,Xt=class extends Error{};async function ha(t,e=Xd){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new Xt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function et(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 _a(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:null,o=r(n.input_tokens),s=r(n.output_tokens),i=a=>a??0,u=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let a={input_tokens:i(o),output_tokens:i(s),total_tokens:u};return o===null||s===null?{kind:"partial",usage:a}:{kind:"counts",usage:a}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:u}}}function Fn(t){let e=_a(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ya(t){let e=Fn(t);return{prompt_tokens:e?.input_tokens??0,completion_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,prompt_tokens_details:{cached_tokens:Qd(t)},completion_tokens_details:{reasoning_tokens:0}}}function Qd(t){let e=t?.usage;if(!e||typeof e!="object")return 0;let n=e.input_tokens_details;if(!n||typeof n!="object")return 0;let r=n.cached_tokens;return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:0}function Zd(t,e){let n=_a(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function ec(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=a=>{let l=n[a];return typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),u=r("total_ms");return o===null||s===null||i===null||u===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:u}}function tc(t,e){let n=ec(e);n&&(t.timing=n),t.outputSeconds=Ce(e)}function tt(t,e){Zd(t,e),tc(t,e)}async function Hn(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 va(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 nc(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 Bn=class extends Error{};function rc(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 Bn(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function oc(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:rc(n.role,n.content)})}return e}function Qr(t){return ut(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 sc(t,e,n,r,o,s,i){let u=Nt(s.id),a=t.stream===!0;if(s.model=ue(t),s.stream=a,await Hn(s,e,typeof t.model=="string"?t.model:void 0),a){let w;try{w=await Dt({body:t,clients:e,store:n,stats:o,responseId:u,turn:s})}catch(f){if(f instanceof G){vt(r,"openai",f);return}if(f instanceof ye){K(r,f.status,f.message);return}if(f instanceof be||f instanceof ce){r.setHeader("retry-after","2"),K(r,503,f.message,"capacity_error");return}throw f}eo(r);for await(let f of w.events){if(f.type==="error"){s.streamError=!0;let g=f.error,y=Oe(g),b=y??xe(s.id);y===null&&i(`[caller-message-boundary] /v1/responses stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(f)}`),r.write(`event: error
|
|
39
|
+
data: ${JSON.stringify({error:{message:b,type:g?.type??"upstream_error",code:g?.code??null}})}
|
|
40
40
|
|
|
41
|
-
`),r.end();return}f.type==="response.completed"&&
|
|
41
|
+
`),r.end();return}f.type==="response.completed"&&tt(s,f.response),r.write(`event: ${String(f.type??"message")}
|
|
42
42
|
data: ${JSON.stringify(f)}
|
|
43
43
|
|
|
44
44
|
`)}r.write(`data: [DONE]
|
|
45
45
|
|
|
46
|
-
`),r.end();return}let l;try{l=ct(n,t)}catch(w){if(w instanceof ye){K(r,w.status,w.message);return}throw w}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ue(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await vr(e,t,l,!1,he(s))}catch(w){if(w instanceof G){vt(r,"openai",w);return}if(w instanceof ye){K(r,w.status,w.message);return}if(w instanceof be||w instanceof ce){r.setHeader("retry-after","2"),K(r,503,w.message,"capacity_error");return}throw w}let
|
|
46
|
+
`),r.end();return}let l;try{l=ct(n,t)}catch(w){if(w instanceof ye){K(r,w.status,w.message);return}throw w}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(l))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=ue(t);o.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await vr(e,t,l,!1,he(s))}catch(w){if(w instanceof G){vt(r,"openai",w);return}if(w instanceof ye){K(r,w.status,w.message);return}if(w instanceof be||w instanceof ce){r.setHeader("retry-after","2"),K(r,503,w.message,"capacity_error");return}throw w}let h=[],v=null;for await(let w of o.track(m,c,s)){if(h.push(w),w.type==="error"){to(r,w,{inferenceId:s.id,operatorError:i});return}w.type==="response.completed"&&(v=w.response)}if(v==null){K(r,502,"upstream produced no response.completed event","upstream_error");return}tt(s,v);let k=dt(h,v),S=Qe(p,ut(v).length,k);if(S){K(r,502,Xe(c,S),"upstream_error");return}d&&n.remember(u,l,_r(v,k),d),ae(r,200,{...v,id:u})}async function ic(t,e,n,r,o,s,i){let u=t.messages;if(!Array.isArray(u)){K(n,400,"chat/completions requires a messages array");return}let a;try{a=wi(s,t)}catch(_){if(_ instanceof de){K(n,_.status,_.message);return}throw _}let l=String(t.model??"urun"),d=Ms(o.id),c;try{c=oc(u)}catch(_){if(_ instanceof Bn){K(n,400,_.message);return}throw _}let p=ue(t);r.model(p),o.model=p,o.stream=t.stream===!0,await Hn(o,e,typeof t.model=="string"?t.model:void 0);let m=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:c,stream:!0,tools:nc(t.tools),tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_completion_tokens??t.max_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{},...t.response_format!==void 0?{response_format:t.response_format}:{}},he(o))}catch(_){if(_ instanceof G){vt(n,"openai",_);return}if(_ instanceof be||_ instanceof ce){n.setHeader("retry-after","2"),K(n,503,_.message,"capacity_error");return}throw _}if(t.stream===!0){a?Yd(n):eo(n);let _=[],R=new De,T="",$=a?new gt(a,B=>{n.write(`data: ${JSON.stringify(et(d,l,{content:B},null))}
|
|
47
47
|
|
|
48
|
-
`)}):null,
|
|
48
|
+
`)}):null,P=B=>{$?.flush(),n.write(B),n.end()};try{a?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:l,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
|
|
49
49
|
|
|
50
|
-
`),n.write(`data: ${JSON.stringify(
|
|
50
|
+
`),n.write(`data: ${JSON.stringify(et(d,l,{role:"assistant"},null))}
|
|
51
51
|
|
|
52
|
-
`);for await(let
|
|
52
|
+
`);for await(let V of r.track(h,p,o)){_.push(V);let re=lt(V);if(V.type==="response.output_text.delta"&&typeof V.delta=="string")T+=V.delta,$?$.push(V.delta):n.write(`data: ${JSON.stringify(et(d,l,{content:V.delta},null))}
|
|
53
53
|
|
|
54
|
-
`);else if(
|
|
54
|
+
`);else if(V.type==="response.reasoning_text.delta"&&typeof V.delta=="string")(!a||a.includeReasoning)&&n.write(`data: ${JSON.stringify(et(d,l,{reasoning_content:V.delta},null))}
|
|
55
55
|
|
|
56
|
-
`);else if(
|
|
56
|
+
`);else if(re){$?.flush();let{call:U,isNew:H}=R.add(re),z=H?{index:re.tool_index,id:U.id??`call_${re.tool_index}`,type:"function",function:{name:U.name??"",arguments:re.delta}}:{index:re.tool_index,function:{arguments:re.delta}};n.write(`data: ${JSON.stringify(et(d,l,{tool_calls:[z]},null))}
|
|
57
57
|
|
|
58
|
-
`)}else if(
|
|
58
|
+
`)}else if(V.type==="error"){o.streamError=!0;let U=V.error??{},H=Oe(U),z=H??xe(o.id);H===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(V)}`),P(`data: ${JSON.stringify({error:{message:z,type:U.type??"upstream_error",code:U.code??null}})}
|
|
59
59
|
|
|
60
|
-
`);return}}let
|
|
60
|
+
`);return}}let B=Qr(Te(_)),L=Qe(m,R.size+B.length,T);if(L){o.streamError=!0,P(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:Xe(p,L)}})}
|
|
61
61
|
|
|
62
|
-
`);return}
|
|
62
|
+
`);return}$?.flush(),R.size===0&&B.length>0&&n.write(`data: ${JSON.stringify(et(d,l,{tool_calls:B},null))}
|
|
63
63
|
|
|
64
|
-
`);let
|
|
64
|
+
`);let N=R.size>0||B.length>0;n.write(`data: ${JSON.stringify(et(d,l,{},N?"tool_calls":"stop"))}
|
|
65
65
|
|
|
66
|
-
`);let
|
|
66
|
+
`);let ne=Fn(Te(_));tt(o,Te(_)),ne&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:l,choices:[],usage:ya(Te(_))})}
|
|
67
67
|
|
|
68
68
|
`),n.write(`data: [DONE]
|
|
69
69
|
|
|
70
|
-
`),n.end();return}finally{
|
|
71
|
-
data: ${JSON.stringify({type:
|
|
70
|
+
`),n.end();return}finally{$?.flush(),$?.dispose()}}let v="",k="",S=[],w=new De;for await(let _ of r.track(h,p,o)){S.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(v+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(k+=_.delta);let R=lt(_);if(R&&w.add(R),_.type==="error"){to(n,_,{inferenceId:o.id,operatorError:i});return}}let f=Te(S);tt(o,f);let g=Qr(f),y=g.length>0?g:Qr({output:w.items()}),b=Qe(m,y.length,v);if(b){K(n,502,Xe(p,b),"upstream_error");return}let x=y.map(({index:_,...R})=>R),A={role:"assistant",content:v||null},E=k||va(f);E&&(A.reasoning_content=E),x.length>0&&(A.tool_calls=x),ae(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:l,choices:[{index:0,message:A,finish_reason:x.length>0?"tool_calls":"stop"}],usage:ya(f)})}var ba="sense-latest";async function ac(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:ba,u=ue({model:i});if(o.model=u,o.stream=!1,t.state===void 0||t.state===null){K(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){K(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){K(n,400,"systemone media, when present, must be an array");return}let l=await Sa(t,i,u,e,n,r,o,s);l!==null&&ae(n,200,l.answer)}async function Sa(t,e,n,r,o,s,i,u){let a={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=a;let l=performance.now();s.model(n),await Hn(i,r,e),a.resolve_ms=Math.round(performance.now()-l);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},he(i))}catch(S){if(S instanceof G)return vt(o,"openai",S),null;if(S instanceof be||S instanceof ce)return o.setHeader("retry-after","2"),K(o,503,S.message,"capacity_error"),null;throw S}a.dial_ms=Math.round(performance.now()-c);let p=[],m=null;try{for await(let S of s.track(d,n,i))if(m===null&&(m=performance.now(),a.first_event_ms=Math.round(m-c)),p.push(S),S.type==="error")return to(o,S,{inferenceId:i.id,operatorError:u}),null}catch(S){if(S instanceof G)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),vt(o,"openai",S),null;if(S instanceof be||S instanceof ce)return m!==null&&(a.stream_ms=Math.round(performance.now()-m)),o.setHeader("retry-after","2"),K(o,503,S.message,"capacity_error"),null;throw m!==null&&(a.stream_ms=Math.round(performance.now()-m)),S}m!==null&&(a.stream_ms=Math.round(performance.now()-m));let h=Te(p);if(h==null)return K(o,502,"upstream produced no response.completed event","upstream_error"),null;tt(i,h);let v=dt(p,h),k;try{k=JSON.parse(v)}catch{return K(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(k===null||typeof k!="object"||Array.isArray(k))return K(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof k=="object"&&k!==null&&!Array.isArray(k)&&"timing"in k){let S=k.timing;if(typeof S=="object"&&S!==null&&!Array.isArray(S)&&"question_fwd_ms"in S&&"head_ms"in S){let w=f=>typeof f=="number"&&Number.isFinite(f)&&f>=0?Math.round(f):null;a.question_fwd_ms=w(S.question_fwd_ms),a.head_ms=w(S.head_ms)}}return{answer:k,completed:h}}async function uc(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){K(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:ba,u=ue({model:i});o.model=u,o.stream=!1;let a;try{a=ki(t,i)}catch(p){if(p instanceof D){K(n,400,p.message);return}throw p}let l=await Sa(a.systemone,i,u,e,n,r,o,s);if(l===null)return;let d;try{d=Ei(a.specs,l.answer)}catch(p){if(p instanceof _e){K(n,502,p.message,"upstream_error");return}throw p}let c=l.completed.usage;ae(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function lc(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Qt=class extends Error{};function qn(t){return new Qt(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function dc(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 cc(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 Qt(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function pc(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw qn(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw qn(`tool_result > ${r}`);e+=String(n.text??"")}return e}function fc(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 qn(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let u=String(i.type??"");if(u==="text")o+=String(i.text??"");else if(u==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(u==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:pc(i.content)});else{if(u==="thinking"||u==="redacted_thinking")continue;throw qn(u)}}return s(),r}function Zr(t){return ut(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 mc(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ee(n,400,"invalid_request_error","messages requires a messages array");return}if(typeof t.max_tokens!="number"||!Number.isInteger(t.max_tokens)||t.max_tokens<1){Ee(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ee(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(A=>typeof A!="string"))){Ee(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let u=String(t.model??"urun"),a=Ls(o.id),l=[],d;try{t.system&&l.push({role:"system",content:lc(t.system)});for(let A of i)l.push(...fc(A));d=cc(t.tool_choice)}catch(A){if(A instanceof Qt){Ee(n,400,"invalid_request_error",A.message);return}throw A}let c=ue(t);r.model(c),o.model=c,o.stream=t.stream===!0,await Hn(o,e,typeof t.model=="string"?t.model:void 0);let p=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:l,stream:!0,tools:dc(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},he(o))}catch(A){if(A instanceof G){vt(n,"anthropic",A);return}if(A instanceof be||A instanceof ce){n.setHeader("retry-after","2"),Ee(n,503,"capacity_error",A.message);return}throw A}let h=(A,E)=>{n.destroyed||n.write(`event: ${A}
|
|
71
|
+
data: ${JSON.stringify({type:A,...E})}
|
|
72
72
|
|
|
73
|
-
`)};if(t.stream===!0){let I=r.track(m,c,o);Qr(n),g("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let O=0,_="",R=0,k="none",C=()=>k,N=-1,j=-1,U=new De,D=[],oe=()=>{k!=="none"&&(k="none",g("content_block_stop",{index:N}))},J=(Y,ee)=>{oe(),k=Y,N=R++,g("content_block_start",{index:N,content_block:ee})};for await(let Y of I){if(n.destroyed)break;D.push(Y);let ee=lt(Y);if(Y.type==="response.reasoning_text.delta"&&typeof Y.delta=="string")C()!=="thinking"&&J("thinking",{type:"thinking",thinking:""}),g("content_block_delta",{index:N,delta:{type:"thinking_delta",thinking:Y.delta}});else if(Y.type==="response.output_text.delta"&&typeof Y.delta=="string")C()!=="text"&&J("text",{type:"text",text:""}),O+=1,_+=Y.delta,g("content_block_delta",{index:N,delta:{type:"text_delta",text:Y.delta}});else if(ee){let{call:ve}=U.add(ee);(C()!=="tool"||ee.tool_index!==j)&&(j=ee.tool_index,J("tool",{type:"tool_use",id:ve.id??`call_${ee.tool_index}`,name:ve.name??"",input:{}})),ee.delta&&g("content_block_delta",{index:N,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(Y.type==="error"){o.streamError=!0;let ve=Y.error,He=Te(ve);He===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Y)}`),g("error",{error:{type:"api_error",message:He??xe(o.id)}}),n.end();return}}if(n.destroyed)return;let ne=Oe(D),M=ut(ne),H=Xe(p,U.size+M.length,_);if(H){o.streamError=!0,g("error",{error:{type:"api_error",message:Ye(c,H)}}),n.end();return}oe();let z=[];if(U.size===0)try{z=Xr(ne)}catch(Y){o.streamError=!0;let ee=fe(Y,{inferenceId:o.id});ee.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Y instanceof Error?Y.message:Y)}`),g("error",{error:{type:"api_error",message:ee.message}}),n.end();return}R===0&&z.length===0&&(J("text",{type:"text",text:""}),oe()),z.forEach(Y=>{let ee=R++;g("content_block_start",{index:ee,content_block:{...Y,input:{}}}),g("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(Y.input??{})}}),g("content_block_stop",{index:ee})});let qe=U.size>0||z.length>0,tt=Fn(ne);et(o,ne),g("message_delta",{delta:{stop_reason:qe?"tool_use":"end_turn"},usage:tt?{input_tokens:tt.input_tokens,output_tokens:tt.output_tokens}:{output_tokens:O}}),g("message_stop",{}),n.end();return}let v="",x="",S=[],w=new De;for await(let I of r.track(m,c,o)){S.push(I),I.type==="response.output_text.delta"&&typeof I.delta=="string"&&(v+=I.delta),I.type==="response.reasoning_text.delta"&&typeof I.delta=="string"&&(x+=I.delta);let O=lt(I);if(O&&w.add(O),I.type==="error"){let _=I.error,R=_?.type==="invalid_request_error",k=Te(_);k===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(I)}`),Ee(n,R?400:502,R?"invalid_request_error":"api_error",k??xe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let f=Oe(S);et(o,f);let h;try{h=Xr(f),h.length===0&&w.size>0&&(h=Xr({output:w.items()}))}catch(I){let O=fe(I,{inferenceId:o.id});O.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(I instanceof Error?I.message:I)}`),Ee(n,502,"api_error",O.message);return}let y=Xe(p,h.length,v);if(y){Ee(n,502,"api_error",Ye(c,y));return}let b=[],E=x||_a(f);E&&b.push({type:"thinking",thinking:E}),(v||h.length===0)&&b.push({type:"text",text:v}),b.push(...h),ae(n,200,{id:a,type:"message",role:"assistant",content:b,model:u,stop_reason:h.length>0?"tool_use":"end_turn",usage:Fn(f)??{input_tokens:0,output_tokens:0}})}function mc(t){Re(process.stdout,t)}function gc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??mc,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new Ke;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),g=(f,h,y,b,E)=>m?Ee(c,f,b,h):K(c,f,h,y,E),v=wr(p.pathname),x=p.pathname.startsWith("/partners/"),S=v||x?{id:$t(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;S&&(c.setHeader(Os,S.id),c.once("close",()=>{let f=$s({turn:S,method:d.method??"",path:p.pathname,res:c});i(Ms(f)),a?.(f),ma({record:f,ledger:t.ledger??null,req:d})}));let w=()=>Ts(p.pathname,S);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ae(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ae(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){g(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=p.pathname===oa?"canonical":p.pathname===zr?"huggingface":null;if(f){if(d.method!=="POST"){g(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let E=t.usage;if(!E){g(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let I=E.authorize(d),O;try{O=await ga(d,sa)}catch(k){if(k instanceof Kt){g(413,k.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=k=>E.lookup(I,k),R;try{if(f==="canonical"){let k=ia(O),C=await _(k);Dn(C,k),R={requests:C}}else R=await aa(O,_)}catch(k){if(k instanceof je){g(k.status,k.message,"invalid_request_error","invalid_request_error");return}throw k}ae(c,200,R);return}if(d.method==="GET"&&p.pathname===At){let E=await s(d);if(S&&(S.org=E.tenant??null),!E.openRouterModels){g(501,`GET ${At} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ae(c,200,await E.openRouterModels());return}if(p.pathname.startsWith("/partners/")){g(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${zr} and GET ${At}`,"invalid_request_error","not_found_error");return}let h=await s(d);if(S&&(S.org=h.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:At}),c.end();return}ae(c,200,await h.listModels());return}if(d.method==="GET"&&p.pathname===Ii){if(!h.listImageModels){g(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ae(c,200,await h.listImageModels());return}if(Ai(p.pathname)){if(!h.supportsImages){g(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let E={clients:h,imageModels:h.supportsImages,stats:l,turn:w(),operatorLog:u};p.pathname===$n?await Di(d,c,E):await Ui(d,c,E);return}if(d.method==="GET"&&p.pathname===Zi){if(!h.listSpeechToTextModels){g(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ae(c,200,await h.listSpeechToTextModels());return}if(Qi(p.pathname)){if(!h.supportsTranscription){g(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Un}`,"not_implemented","not_implemented_error");return}let E={clients:h,transcriptionModels:h.supportsTranscription,stats:l,turn:w(),operatorLog:u};await na(d,c,E);return}if(Wi(p.pathname)){if(!h.supportsSpeech){g(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Ht}`,"not_implemented","not_implemented_error");return}let E={clients:h,speechModels:h.supportsSpeech,stats:l,turn:w(),operatorLog:u};await Xi(d,c,E);return}if(d.method!=="POST"){g(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await ga(d)}catch(E){if(E instanceof Kt){g(413,E.message,"request_too_large","request_too_large");return}g(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=Buffer.byteLength(JSON.stringify(y));if(p.pathname==="/v1/responses"){l.request("responses",b,b),await oc(y,h,Lt(h),c,l,w(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",b,b),await sc(y,h,c,l,w(),d.headers[qr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",b,b),await ic(y,h,c,l,w(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",b,b),await ac(y,h,c,l,w(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",b,b),await fc(y,h,c,l,w(),u);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",b,b),Ee(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}g(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let h=String(f instanceof Error?f.message:f);if(!c.headersSent){let E=o?.(f)??null;if(E){E.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${E.operatorDetail}`),g(E.status,h,E.openaiType,E.anthropicType,E.code);return}if(f instanceof qn.SessionAllocationError){let O=_n(f.code);if(O){let _=f.retryAfterSeconds??(O.status===429?30:void 0);_!==void 0&&c.setHeader("Retry-After",String(_)),g(O.status,Ut(O,f.code??void 0),O.openaiType,O.anthropicType,O.code);return}}if(f instanceof qn.SessionFailedError){let O=vn(f);if(O){let _=O.status===429?30:void 0;_!==void 0&&c.setHeader("Retry-After",String(_)),g(O.status,Ut(O,f.status.sessionId?`session ${f.status.sessionId}`:void 0),O.openaiType,O.anthropicType,O.code);return}}if(f instanceof wt){g(502,h,"upstream_error","api_error");return}if(f instanceof Se){f.retryable&&c.setHeader("Retry-After","1");let O=fe(f,{inferenceId:S?.id??null});O.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),g(502,O.message,"upstream_error","api_error",f.code);return}if(f instanceof Ue){c.setHeader("Retry-After",String(f.retryAfterSeconds)),g(f.status,h,f.status===429?"capacity_error":"upstream_error",f.status===429?"rate_limit_error":"overloaded_error",f.code);return}let I=fe(f,{inferenceId:S?.id??null});I.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),g(500,I.message,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let y=f instanceof Se?f.code:null,b=fe(f,{inferenceId:S?.id??null});b.redacted&&u(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),c.destroyed||(m?c.write(`event: error
|
|
73
|
+
`)};if(t.stream===!0){let A=r.track(m,c,o);eo(n),h("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:u,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let E=0,_="",R=0,T="none",$=()=>T,P=-1,B=-1,L=new De,N=[],ne=()=>{T!=="none"&&(T="none",h("content_block_stop",{index:P}))},V=(Y,ee)=>{ne(),T=Y,P=R++,h("content_block_start",{index:P,content_block:ee})};for await(let Y of A){if(n.destroyed)break;N.push(Y);let ee=lt(Y);if(Y.type==="response.reasoning_text.delta"&&typeof Y.delta=="string")$()!=="thinking"&&V("thinking",{type:"thinking",thinking:""}),h("content_block_delta",{index:P,delta:{type:"thinking_delta",thinking:Y.delta}});else if(Y.type==="response.output_text.delta"&&typeof Y.delta=="string")$()!=="text"&&V("text",{type:"text",text:""}),E+=1,_+=Y.delta,h("content_block_delta",{index:P,delta:{type:"text_delta",text:Y.delta}});else if(ee){let{call:ve}=L.add(ee);($()!=="tool"||ee.tool_index!==B)&&(B=ee.tool_index,V("tool",{type:"tool_use",id:ve.id??`call_${ee.tool_index}`,name:ve.name??"",input:{}})),ee.delta&&h("content_block_delta",{index:P,delta:{type:"input_json_delta",partial_json:ee.delta}})}else if(Y.type==="error"){o.streamError=!0;let ve=Y.error,He=Oe(ve);He===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Y)}`),h("error",{error:{type:"api_error",message:He??xe(o.id)}}),n.end();return}}if(n.destroyed)return;let re=Te(N),U=ut(re),H=Qe(p,L.size+U.length,_);if(H){o.streamError=!0,h("error",{error:{type:"api_error",message:Xe(c,H)}}),n.end();return}ne();let z=[];if(L.size===0)try{z=Zr(re)}catch(Y){o.streamError=!0;let ee=fe(Y,{inferenceId:o.id});ee.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Y instanceof Error?Y.message:Y)}`),h("error",{error:{type:"api_error",message:ee.message}}),n.end();return}R===0&&z.length===0&&(V("text",{type:"text",text:""}),ne()),z.forEach(Y=>{let ee=R++;h("content_block_start",{index:ee,content_block:{...Y,input:{}}}),h("content_block_delta",{index:ee,delta:{type:"input_json_delta",partial_json:JSON.stringify(Y.input??{})}}),h("content_block_stop",{index:ee})});let je=L.size>0||z.length>0,nt=Fn(re);tt(o,re),h("message_delta",{delta:{stop_reason:je?"tool_use":"end_turn"},usage:nt?{input_tokens:nt.input_tokens,output_tokens:nt.output_tokens}:{output_tokens:E}}),h("message_stop",{}),n.end();return}let v="",k="",S=[],w=new De;for await(let A of r.track(m,c,o)){S.push(A),A.type==="response.output_text.delta"&&typeof A.delta=="string"&&(v+=A.delta),A.type==="response.reasoning_text.delta"&&typeof A.delta=="string"&&(k+=A.delta);let E=lt(A);if(E&&w.add(E),A.type==="error"){let _=A.error,R=_?.type==="invalid_request_error",T=Oe(_);T===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(A)}`),Ee(n,R?400:502,R?"invalid_request_error":"api_error",T??xe(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let f=Te(S);tt(o,f);let g;try{g=Zr(f),g.length===0&&w.size>0&&(g=Zr({output:w.items()}))}catch(A){let E=fe(A,{inferenceId:o.id});E.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(A instanceof Error?A.message:A)}`),Ee(n,502,"api_error",E.message);return}let y=Qe(p,g.length,v);if(y){Ee(n,502,"api_error",Xe(c,y));return}let b=[],x=k||va(f);x&&b.push({type:"thinking",thinking:x}),(v||g.length===0)&&b.push({type:"text",text:v}),b.push(...g),ae(n,200,{id:a,type:"message",role:"assistant",content:b,model:u,stop_reason:g.length>0?"tool_use":"end_turn",usage:Fn(f)??{input_tokens:0,output_tokens:0}})}function gc(t){Re(process.stdout,t)}function hc(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??gc,u=t.operatorLog??(d=>console.error(d)),a=t.observe,l=new ze;return(d,c)=>{let p=new URL(d.url??"/","http://localhost"),m=p.pathname==="/v1/messages"||p.pathname.startsWith("/v1/messages/"),h=(f,g,y,b,x)=>m?Ee(c,f,b,g):K(c,f,g,y,x),v=wr(p.pathname),k=p.pathname.startsWith("/partners/"),S=v||k?{id:Lt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;S&&(c.setHeader(Cs,S.id),c.once("close",()=>{let f=Ns({turn:S,method:d.method??"",path:p.pathname,res:c});i(Us(f)),a?.(f),ga({record:f,ledger:t.ledger??null,req:d})}));let w=()=>$s(p.pathname,S);(async()=>{if(d.method==="GET"&&p.pathname==="/healthz"){ae(c,200,{ok:!0});return}if(d.method==="GET"&&p.pathname==="/stats"){ae(c,200,r?{identity:r,...l.snapshot()}:l.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){h(401,"invalid local proxy api key","authentication_error","authentication_error");return}let f=p.pathname===sa?"canonical":p.pathname===Xr?"huggingface":null;if(f){if(d.method!=="POST"){h(405,`${p.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let x=t.usage;if(!x){h(501,`${p.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let A=x.authorize(d),E;try{E=await ha(d,ia)}catch(T){if(T instanceof Xt){h(413,T.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let _=T=>x.lookup(A,T),R;try{if(f==="canonical"){let T=aa(E),$=await _(T);Dn($,T),R={requests:$}}else R=await ua(E,_)}catch(T){if(T instanceof qe){h(T.status,T.message,"invalid_request_error","invalid_request_error");return}throw T}ae(c,200,R);return}if(d.method==="GET"&&p.pathname===It){let x=await s(d);if(S&&(S.org=x.tenant??null),!x.openRouterModels){h(501,`GET ${It} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}ae(c,200,await x.openRouterModels());return}if(p.pathname.startsWith("/partners/")){h(404,`no partner adapter for ${d.method} ${p.pathname} \u2014 the partner surface currently carries ${Xr} and GET ${It}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(S&&(S.org=g.tenant??null),d.method==="GET"&&p.pathname==="/v1/models"){if(p.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:It}),c.end();return}ae(c,200,await g.listModels());return}if(d.method==="GET"&&p.pathname===Ti){if(!g.listImageModels){h(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}ae(c,200,await g.listImageModels());return}if(Ii(p.pathname)){if(!g.supportsImages){h(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${p.pathname}`,"not_implemented","not_implemented_error");return}let x={clients:g,imageModels:g.supportsImages,stats:l,turn:w(),operatorLog:u};p.pathname===$n?await Fi(d,c,x):await Di(d,c,x);return}if(d.method==="GET"&&p.pathname===ea){if(!g.listSpeechToTextModels){h(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}ae(c,200,await g.listSpeechToTextModels());return}if(Zi(p.pathname)){if(!g.supportsTranscription){h(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${Un}`,"not_implemented","not_implemented_error");return}let x={clients:g,transcriptionModels:g.supportsTranscription,stats:l,turn:w(),operatorLog:u};await ra(d,c,x);return}if(Ki(p.pathname)){if(!g.supportsSpeech){h(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${Jt}`,"not_implemented","not_implemented_error");return}let x={clients:g,speechModels:g.supportsSpeech,stats:l,turn:w(),operatorLog:u};await Qi(d,c,x);return}if(d.method!=="POST"){h(404,`no route for ${d.method} ${p.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await ha(d)}catch(x){if(x instanceof Xt){h(413,x.message,"request_too_large","request_too_large");return}h(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let b=Buffer.byteLength(JSON.stringify(y));if(p.pathname==="/v1/responses"){l.request("responses",b,b),await sc(y,g,Ut(g),c,l,w(),u);return}if(p.pathname==="/v1/chat/completions"){l.request("chat_completions",b,b),await ic(y,g,c,l,w(),d.headers[Gr],u);return}if(p.pathname==="/v1/systemone"){l.request("systemone",b,b),await ac(y,g,c,l,w(),u);return}if(p.pathname==="/v1/decisions"){l.request("decisions",b,b),await uc(y,g,c,l,w(),u);return}if(p.pathname==="/v1/messages"){l.request("messages",b,b),await mc(y,g,c,l,w(),u);return}if(p.pathname==="/v1/messages/count_tokens"){l.request("count_tokens",b,b),Ee(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}h(404,`no route for POST ${p.pathname}`,"invalid_request_error","not_found_error")})().catch(f=>{let g=String(f instanceof Error?f.message:f);if(!c.headersSent){let x=o?.(f)??null;if(x){x.operatorDetail!==void 0&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} classified failure; detail withheld from the caller: ${x.operatorDetail}`),h(x.status,g,x.openaiType,x.anthropicType,x.code);return}if(f instanceof jn.SessionAllocationError){let E=vn(f.code);if(E){let _=f.retryAfterSeconds??(E.status===429?30:void 0);_!==void 0&&c.setHeader("Retry-After",String(_)),h(E.status,Ft(E,f.code??void 0),E.openaiType,E.anthropicType,E.code);return}}if(f instanceof jn.SessionFailedError){let E=bn(f);if(E){let _=E.status===429?30:void 0;_!==void 0&&c.setHeader("Retry-After",String(_)),h(E.status,Ft(E,f.status.sessionId?`session ${f.status.sessionId}`:void 0),E.openaiType,E.anthropicType,E.code);return}}if(f instanceof wt){h(502,g,"upstream_error","api_error");return}if(f instanceof Se){f.retryable&&c.setHeader("Retry-After","1");let E=fe(f,{inferenceId:S?.id??null});E.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} pre-head decision stream failure; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),h(502,E.message,"upstream_error","api_error",f.code);return}if(f instanceof Ue){c.setHeader("Retry-After",String(f.retryAfterSeconds)),h(f.status,g,f.status===429?"capacity_error":"upstream_error",f.status===429?"rate_limit_error":"overloaded_error",f.code);return}let A=fe(f,{inferenceId:S?.id??null});A.redacted&&u(`[caller-message-boundary] ${d.method??""} ${p.pathname} failed; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),h(500,A.message,"proxy_error","api_error","proxy_error");return}S&&(S.streamError=!0);let y=f instanceof Se?f.code:null,b=fe(f,{inferenceId:S?.id??null});b.redacted&&u(`[caller-message-boundary] the stream for ${p.pathname} failed after the head went out; raw error withheld from the caller: ${f instanceof Error?`${f.name}: ${f.message}`:we(f)}`),c.destroyed||(m?c.write(`event: error
|
|
74
74
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:b.message}})}
|
|
75
75
|
|
|
76
76
|
`):c.write(`data: ${JSON.stringify({error:{message:b.message,type:"upstream_error",code:y}})}
|
|
77
77
|
|
|
78
|
-
`)),c.end()})}}function
|
|
79
|
-
`),null):{catalogUrl:r,anonKey:o}}function
|
|
80
|
-
`),o(127)})})}function
|
|
81
|
-
`)}async function
|
|
82
|
-
`)),setInterval(()=>s.reap(),5e3).unref());let i=null,u=d=>{if(i===null){let c=a.address();if(c===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");i=
|
|
83
|
-
`),
|
|
84
|
-
`),0):(
|
|
85
|
-
`),1)}if(n==="proxy"){let o=e??Ar(t),s=await
|
|
86
|
-
`):u.reason&&
|
|
87
|
-
`);let d=null,c=null,p=null,m=null;u.mode!=="reuse"&&(a=await
|
|
88
|
-
`)}),
|
|
89
|
-
`),d=
|
|
90
|
-
`),w(127)})});v?.();let S=null;try{a&&await a.close()}catch(w){S=w}finally{d?.(),d=null,c?.(),c=null,p?.end()}return S!==null&&Re(
|
|
91
|
-
`),
|
|
92
|
-
`),
|
|
78
|
+
`)),c.end()})}}function ka(t){let{clients:e,apiKey:n}=t,r=(0,wa.createServer)(hc(t)),o=Hs(r,{clients:e,apiKey:n,statusOf:t.statusOf,operatorLog:t.operatorLog}),s=jr(r,{resolver:Si(e,n,t.realtimeCompanions),operatorLog:t.operatorLog}),i=r.close.bind(r);return r.close=(u=>(o.close(),s(),i(u))),Os(r,{clients:e,apiKey:n}),r}var Gn=require("@urun-sh/core/internal");var yc={ensureWebRTC:Gn.ensureNodeWebRTC,webrtcUnavailableReason:Gn.nodeWebRTCUnavailableReason,audioBackend:nn};async function xa(t=yc){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 _c(t,e){let n=(t.URUN_CATALOG_URL??"").trim(),r=n?Sn(n,"URUN_CATALOG_URL"):"",o=(t.URUN_CATALOG_ANON_KEY??"").trim();return!r||!o?(e(`urun compat: catalog oracle off (URUN_CATALOG_URL/URUN_CATALOG_ANON_KEY unset) \u2014 an undeployed uRun CATALOG model name falls through to the default app instead of a loud 404; deployed apps still resolve exactly, and /stats.models records every mapping
|
|
79
|
+
`),null):{catalogUrl:r,anonKey:o}}function vc(t){let e={baseUrl:t.baseUrl,orgId:t.orgId,defaultApp:t.appId,fnName:t.fnName,apiUrl:t.apiUrl,auth:t.auth,catalog:_c(q.default.env,r=>q.default.stderr.write(r)),decisionPool:rs(q.default.env,q.default.env.HOSTNAME)??void 0},n=as(e);return{router:n,decision:e.decisionPool?us(e,n):null}}async function Ra(t,e,n){let r=(0,no.spawn)(t,e,{stdio:"inherit",env:n});return new Promise(o=>{r.once("exit",s=>o(s??1)),r.once("error",s=>{q.default.stderr.write(`failed to launch ${t}: ${String(s)}
|
|
80
|
+
`),o(127)})})}function Ea(){return ti(q.default.env,M,Ae.existsSync)}function Ia(t){for(let[e,n]of Object.entries(Er(t)))q.default.stdout.write(`export ${e}=${n}
|
|
81
|
+
`)}async function Aa(t,e){let n=ft(q.default.env),r=e?Ir(n):void 0,{router:o,decision:s}=vc(n);s&&(s.boot().then(()=>s.reap()).catch(c=>q.default.stderr.write(`[decision-pool] boot FAILED: ${String(c instanceof Error?c.message:c)}
|
|
82
|
+
`)),setInterval(()=>s.reap(),5e3).unref());let i=null,u=d=>{if(i===null){let c=a.address();if(c===null)throw new Error("urun compat: a /v1 request was recorded before the proxy socket was listening");i=Or(c.port),(0,Ae.mkdirSync)(ro.default.dirname(i),{recursive:!0})}(0,Ae.appendFileSync)(i,d)},a=ka({clients:ls(o,void 0,void 0,s??void 0,os(q.default.env)),identity:r,...e?{requestLog:u}:{}});try{await new Promise((d,c)=>{a.once("error",c),a.listen(t,"127.0.0.1",d)})}catch(d){throw await o.closeAll().catch(()=>{}),s&&await s.close().catch(()=>{}),d.code==="EADDRINUSE"?new Error(ci(t,await Tr(t))):d}let l=a.address().port;return e&&(q.default.stdout.write(`urun openai proxy listening on http://127.0.0.1:${l}/v1
|
|
83
|
+
`),Ia(l)),{port:l,close:async()=>{s&&await s.drain(5e3).catch(()=>{});let d=new Promise(c=>a.close(()=>c()));a.closeAllConnections(),await d,await o.closeAll(),s&&await s.close()}}}async function bc(){let t=q.default.argv.slice(2),e=ri(t),n=t.shift()??"proxy";if(n==="env")return Ia(oi(e??Ar(t))),0;if(n==="selftest"){let{ok:o,reason:s}=await xa();return o?(q.default.stdout.write(`urun-openai selftest: OK \u2014 werift WebRTC peer globals installed and the werift/opus audio backend constructed from this artifact
|
|
84
|
+
`),0):(q.default.stderr.write(`urun-openai selftest: FAIL \u2014 ${s}
|
|
85
|
+
`),1)}if(n==="proxy"){let o=e??Ar(t),s=await Aa(o,!0);return await new Promise(i=>{q.default.once("SIGINT",i),q.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(kn).join("|")}) or \`-- <cmd>\``);if(r==="pi"){let w=ft(q.default.env);return Ra("pi",["-e",Ea(),...Zs(w.appId,t)],q.default.env)}if(r==="omp"){let w=ft(q.default.env);return Ra("omp",["-e",Ea(),...ei(w.appId,t)],q.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 w=kn[r];if(!w)throw new Error(`unknown command/agent ${r}; commands: proxy | env; agents: ${Object.keys(kn).join(" | ")} \u2014 or \`-- <cmd>\``);o=w.bin,s=[...w.args??[],...t],i=w.env}let u=await ii(e,Ir(ft(q.default.env))),a=null,l=u.port;u.mode==="reuse"?q.default.stdout.write(`reusing the running urun openai proxy on http://127.0.0.1:${l} (app ${u.identity.app}, fn ${u.identity.fn}, v${u.identity.proxy_version})
|
|
86
|
+
`):u.reason&&q.default.stderr.write(`urun compat: ${u.reason}
|
|
87
|
+
`);let d=null,c=null,p=null,m=null;u.mode!=="reuse"&&(a=await Aa(u.port,!1),l=a.port,m=Or(l),(0,Ae.mkdirSync)(ro.default.dirname(m),{recursive:!0}),p=(0,Ae.createWriteStream)(m,{flags:"a"}),c=li({streams:q.default,note:w=>(0,Ae.appendFileSync)(m,w)}).uninstall,p.on("error",w=>{d?.(),d=null,Re(q.default.stderr,`urun compat: proxy log ${m} failed: ${String(w)} \u2014 proxy output continues on the terminal
|
|
88
|
+
`)}),q.default.stdout.write(`urun openai proxy on http://127.0.0.1:${l}/v1 \u2014 proxy logs: ${m}
|
|
89
|
+
`),d=ai(p)),r==="codex"&&(s=Qs(l,ft(q.default.env).appId,s));let h=(0,no.spawn)(o,s,{stdio:"inherit",env:Xs(q.default.env,l,i)}),v=m!==null?di({logPath:m,appendSync:Ae.appendFileSync,restore:()=>{d?.(),d=null},writeStderr:w=>q.default.stderr.write(w),killChild:()=>h.kill("SIGTERM"),exit:w=>q.default.exit(w),proc:q.default}):null,k=await new Promise(w=>{h.once("exit",f=>w(f??1)),h.once("error",f=>{d?.(),d=null,Re(q.default.stderr,`failed to launch ${o}: ${String(f)}
|
|
90
|
+
`),w(127)})});v?.();let S=null;try{a&&await a.close()}catch(w){S=w}finally{d?.(),d=null,c?.(),c=null,p?.end()}return S!==null&&Re(q.default.stderr,`urun compat: proxy teardown failed after the harness exited (harness exit code ${k} preserved): ${String(S instanceof Error?S.message:S)}
|
|
91
|
+
`),k}}bc().then(t=>q.default.exit(t),t=>{q.default.stderr.write(`${String(t instanceof Error?t.message:t)}
|
|
92
|
+
`),q.default.exit(1)});
|