@urun-sh/openai 0.6.43 → 0.6.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ResponsesClient-2EsjJUz1.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
- package/dist/{ResponsesClient-BIcQ6p6Z.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
- package/dist/chunk-64VO62LW.js +1 -0
- package/dist/chunk-7KRHHEKZ.js +1 -0
- package/dist/chunk-BA3NCMS5.js +6 -0
- package/dist/chunk-DMRZZTYI.js +4 -0
- package/dist/chunk-FNAZ2XBE.js +20 -0
- package/dist/chunk-G6AFKOVS.js +1 -0
- package/dist/{chunk-FF3RWDFM.js → chunk-HB5KNEY5.js} +1 -1
- package/dist/{chunk-ZCF6EV4Y.js → chunk-VQSCBUKT.js} +20 -19
- package/dist/{chunk-JMSVHETI.js → chunk-X5BLQXHK.js} +1 -1
- package/dist/chunk-XNRPTMSL.js +1 -0
- package/dist/chunk-Y774TOE7.js +2 -0
- package/dist/{composite-BoS9-74g.d.cts → composite-DM2sT1Sp.d.cts} +1 -1
- package/dist/{composite-D4_XPSas.d.ts → composite-DNNAm0PY.d.ts} +1 -1
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +4 -4
- package/dist/gemini-live.d.ts +4 -4
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +48 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +43 -42
- package/dist/hosted/index.d.cts +4 -4
- package/dist/hosted/index.d.ts +4 -4
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.d.cts +2 -2
- package/dist/pi-extension/index.d.ts +2 -2
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +41 -41
- package/dist/pooler/bin.cjs +25 -25
- package/dist/pooler/bin.js +24 -24
- package/dist/proxy/cli.cjs +48 -47
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +19 -18
- package/dist/proxy/index.d.cts +5 -5
- package/dist/proxy/index.d.ts +5 -5
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-PsmsZT62.d.cts → translator-C6MpaZS-.d.cts} +1 -1
- package/dist/{translator-BemK1Of5.d.ts → translator-CaOqL-V8.d.ts} +1 -1
- package/dist/{types-CxWQ84Ew.d.cts → types-DiYzfHYN.d.cts} +2 -5
- package/dist/{types-CxWQ84Ew.d.ts → types-DiYzfHYN.d.ts} +1 -1
- package/dist/{video-out-DPLqpGbQ.d.cts → video-out-A8qMuI36.d.cts} +1 -1
- package/dist/{video-out-DkMqKSOi.d.ts → video-out-IoTqIbAw.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-27HP3RMZ.js +0 -6
- package/dist/chunk-2NKCALKY.js +0 -22
- package/dist/chunk-2RO722HS.js +0 -2
- package/dist/chunk-7DUSLXPG.js +0 -1
- package/dist/chunk-BFIKVTQB.js +0 -1
- package/dist/chunk-GDH2D3S6.js +0 -1
- package/dist/chunk-MOX5FG2R.js +0 -1
- package/dist/chunk-YRBUHHI3.js +0 -2
package/dist/hosted/index.cjs
CHANGED
|
@@ -1,94 +1,95 @@
|
|
|
1
|
-
"use strict";var Vu=Object.create;var Dn=Object.defineProperty;var Ku=Object.getOwnPropertyDescriptor;var zu=Object.getOwnPropertyNames;var Yu=Object.getPrototypeOf,Xu=Object.prototype.hasOwnProperty;var Qu=(t,e)=>{for(var n in e)Dn(t,n,{get:e[n],enumerable:!0})},zs=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zu(e))!Xu.call(t,o)&&o!==n&&Dn(t,o,{get:()=>e[o],enumerable:!(r=Ku(e,o))||r.enumerable});return t};var fe=(t,e,n)=>(n=t!=null?Vu(Yu(t)):{},zs(e||!t||!t.__esModule?Dn(n,"default",{value:t,enumerable:!0}):n,t)),Zu=t=>zs(Dn({},"__esModule",{value:!0}),t);var Qm={};Qu(Qm,{ANONYMOUS_KEY_ID:()=>Br,BIND_HOST:()=>Uu,BUCKET_DOMAIN:()=>ys,BoundedLabel:()=>Wt,ControlPlaneUnavailableError:()=>Le,ConversationBackhauls:()=>Zt,ConversationCapacityError:()=>Qt,DEFAULT_PORT:()=>$s,EDGE_IDENTITY_PORT:()=>wu,EDGE_KEY_FINGERPRINT_HEADER:()=>hs,EDGE_KEY_ID_HEADER:()=>gs,InferenceMetrics:()=>Jt,LEDGER_FUNCTION_PATH:()=>js,LEDGER_WRITE_TIMEOUT_MS:()=>qs,LedgerClient:()=>tn,LedgerDuplicateError:()=>en,LedgerSurfaceError:()=>ae,MAX_CACHED_KEYS:()=>Rs,MAX_CONVERSATIONS:()=>Kr,MAX_CONVERSATION_HANDLES:()=>Ns,MAX_MODEL_LABELS:()=>ds,MAX_ORG_LABELS:()=>cs,MAX_TENANTS:()=>Ms,METRICS_PATH:()=>Dr,METRICS_PORT:()=>hu,NO_MODEL_LABEL:()=>us,ORG_BINDING_TTL_MS:()=>ks,OTHER_LABEL:()=>Gt,OrgResolver:()=>ht,ProxyAuthError:()=>J,READINESS_TIMEOUT_MS:()=>Js,READINESS_TTL_MS:()=>Ws,SERVE_FUNCTION:()=>Nn,TIER_DOMAIN:()=>ws,TenantRegistry:()=>Xt,bearerFrom:()=>Kt,bearerTokenOf:()=>bs,createEdgeIdentityServer:()=>Hr,createHostedProxy:()=>Ju,createMetricsServer:()=>Fr,edgeBucketId:()=>_s,edgeTierFingerprint:()=>vs,laneOf:()=>ps,parseLedgerRecorded:()=>Gs,resolveHostedConfig:()=>Du,statusClassOf:()=>fs,tenantSubject:()=>Yt});module.exports=Zu(Qm);var qu=require("http");var Xs="audio",Zr=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 Qs(t,e,n=1e4){try{return await ed(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function ed(t,e,n){let r=new Zr(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(Xs);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await td(t,n);return await r.startInbound(i),r}function td(t,e){let n=t.stream(Xs);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var Ys="rt-video-in",rn=256e3;function to(t){let e=t.stream(Ys),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Ys}') 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>rn)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${rn}-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 nd=24e3,nn=480,rd=111,od=50,Fn=null;async function sd(){if(Fn)return;let t=await import("opusscript");Fn=t.default??t}function id(){if(!Fn)throw new Error("[opus-guard] opusscript module not loaded");return new Fn(nd,1,2048)}var eo=class{constructor(e=id){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>=od}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 Zs(){let t=await import("werift");await sd();let e=new eo;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=nn;){let d=l.subarray(u,u+nn);u+=nn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,nn);if(f===null){i=l.slice(u);break}o=o+1&65535,s=s+nn>>>0;let h=new t.RtpHeader({version:2,payloadType:rd,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(h,f);n.writeRtp(m)}i=l.slice(u)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch(l){if(e.wedged)throw l;return}let a=new Int16Array(i.length/2);for(let l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r},dispose:()=>e.dispose()}}var Bn=require("@urun-sh/core"),no="rt-video-out";var ad="h264";function ld(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 ud(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;ld(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 ei="urun.videoOut.v2-ws";function ti(t){let e=t.stream(no);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${no}') 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=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${no}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=ud(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:ad,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var Gn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",dd=1007,ri=1008,Ue=1011,Wn=1008,C=class extends Error{constructor(n,r=dd){super(n);this.closeCode=r}closeCode},ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,Hn=["setup","clientContent","realtimeInput","toolResponse"];function oi(t){let e;try{e=JSON.parse(t)}catch{throw new C("client message is not valid JSON")}let n=ie(e);if(!n)throw new C("client message must be a JSON object");let r=Hn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!Hn.includes(a));if(o.length>0)throw new C(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${Hn.join(", ")}`);if(r.length!==1)throw new C(`client message must contain exactly one of ${Hn.join(", ")} (got ${r.length})`);let s=r[0],i=ie(n[s]);if(!i)throw new C(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function si(t,e){if(typeof t=="string")return t;let n=ie(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new C(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ie(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new C(`${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 C(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new C(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
2
|
-
`)}var cd={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},Qe="urun.videoOut";function ii(t){return{framing:ei,codec:t}}function ai(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[Qe]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var pd={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},fd=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",Qe],ni=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function md(t){let e=ie(t);if(!e)throw new C("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new C(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new C("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new C(`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 C("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(!ni.includes(e.activityHandling))throw new C(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ni.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var gd=["temperature","maxOutputTokens","responseModalities"];function li(t){for(let[c,f]of Object.entries(pd))if(t[c]!==void 0)throw new C(f);for(let c of Object.keys(t))if(!fd.includes(c))throw new C(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new C('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new C("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!gd.includes(c))throw new C(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new C("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new C("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let f of c){let h=String(f).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new C(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:si(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new C("setup.tools must be an array");a=[];for(let c of t.tools){let f=ie(c);if(!f)throw new C("setup.tools entries must be objects");for(let h of Object.keys(f))if(h!=="functionDeclarations")throw new C(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new C("tool.functionDeclarations must be an array");for(let h of f.functionDeclarations){let m=ie(h);if(!m||typeof m.name!="string")throw new C("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ie(t.sessionResumption);if(!c)throw new C("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new C(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new C("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?cd:md(t.realtimeInputConfig),d=!1;if(t[Qe]!==void 0){if(!ie(t[Qe]))throw new C(`setup["${Qe}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function ui(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function di(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function ci(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new C(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new C("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new C("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 C(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:si(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var jn=16e3,pi=24e3,hd=`audio/pcm;rate=${pi}`,fi=Buffer.alloc(960).toString("base64");function yd(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function wd(t){let e=ie(t);if(!e)throw new C("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new C(`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 C("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 C("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function _d(t){let e=ie(t);if(!e)throw new C("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new C(`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])!==jn)throw new C(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${jn} Hz (audio/pcm;rate=${jn})`);if(typeof e.data!="string"||e.data.length===0)throw new C("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 C(`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=yd(o,jn,pi);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function mi(t){if(t.mediaChunks!==void 0)throw new C('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 C("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new C(`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 C(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new C(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:_d(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:wd(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new C("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new C("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function gi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new C(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new C("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new C("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 hi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function yi(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:hd,data:t}}]}}}}function wi(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=ie(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=ie(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=ie(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new C(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,Ue);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new C(`upstream function_call arguments are not valid JSON: ${c}`,Ue)}r.push({id:d.call_id,name:d.name,args:f}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var Gi=require("crypto"),Wi=require("ws");var Bi=require("crypto");var Z=class extends Error{},vd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function bd(t){if(typeof t!="string")return!1;let e=vd.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function Sd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new Z(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new Z(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new Z(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new Z(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new Z(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new Z(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new Z(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",bd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new Z(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new Z(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new Z(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new Z(`catalog "shared" block compliance carries "${l}" 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 wt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function _i(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=a=>new Z(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} 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 ro(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new Z(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function vi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Z(`catalog read failed: GET ${n} \u2192 ${r.status}`);return Sd(await r.json())}function ye(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var _e=class extends Error{name="ModelPriceError"},oo="per_million_input_tokens",so="per_million_output_tokens",Si="model_id,variant,unit,price_usd,effective_at,expires_at",bi={per_request:!0,per_minute:!0,per_output_unit:!0},kd=5e3;function Rd(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new _e(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function ki(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new _e(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function Ed(t,e,n){return t===null?null:ki(t,e,n)}function xd(t,e){if(t===oo)return"input";if(t===so)return"output";if(typeof t=="string"&&Object.hasOwn(bi,t))return null;throw new _e(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${oo} | ${so}) nor a known GPU-time unit (${Object.keys(bi).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 Ad(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 io(t,e){return`${t}\0${e}`}function Id(t){if(!Array.isArray(t))throw new _e(`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 _e(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of Si.split(","))if(!Object.hasOwn(s,u))throw new _e(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=xd(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new _e(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new _e(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Rd(s.price_usd,o),effective_at:ki(s.effective_at,o,"effective_at"),expires_at:Ed(s.expires_at,o,"expires_at")})}return e}function Ri(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let _=f&&f.length>0?f:d?.[h];if(!_||_.length===0)return null;let R=Ad(_,h);return"reason"in R?R:R.rate.usd===0?h==="output"&&m!==null&&n?.has(io(l,m))?R.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:R.rate};for(let[f,h]of o.get(l)){let m=u.get(f),_=c(m?.input,"input",h),R=c(m?.output,"output",h);if(_!==null&&"reason"in _){i.push({model_id:l,variant:h,reason:_.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:l,variant:h,reason:R.reason});continue}_===null||R===null||s.push({model_id:l,variant:h,pricing:{input:_.usd,output:R.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function on(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 sn={prices:[],refusals:[]};async function Ei(t){let e=t.fetchImpl??fetch,n=`${oo},${so}`,r=await e(`${t.catalogUrl}/model_prices?select=${Si}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(kd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Id(await r.json())}var et="/partners/openrouter/models",Od={chat:!0,code:!0,agent:!0,vl:!0},xi={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Td(t){let e=t.toLowerCase();return Object.hasOwn(xi,e)?xi[e]:null}var Ai={"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 Pd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ai,o)?Ai[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Ii={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Oi={2:"Llama2",3:"Llama3"};function Cd(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(Ii,s))return Ii[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Oi,i))return Oi[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var Ld=["context_length","max_model_len"];function $d(t){let e=Ld.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 Jn(t){let e=t.map($d),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Md(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function ao(t){if(t.length===0)return null;let e=t.map(Md),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function lo(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 Nd(t,e){let n=e.filter(s=>ye(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return an(n);let r=e.filter(s=>ye(s.model_id)===t);if(r.length>0)return an(r);let o=lo(t,e);return o.length>0?an(o):null}function an(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Ud(t),matches:t}:null}function Ud(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 He=class extends Error{name="ModelCreatedError"};function _t(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 He(`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 He(`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 He(`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]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new He(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function Ze(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 Vn(t,e,n){let r=Nd(t,e);if(!r)return Ze({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Jn(s),a=_t(s),l=on(o.model_id,o.variant,n),u=Ci(o,s),d=ao(s);return Ze({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var Dd=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Ci(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...Dd],defect:o}:{published:[],defect:o}}function uo(t){let e=t.length>0?an(t):null;return e===null?{published:[],defect:null}:Ci(e.row,e.matches)}function Ti(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 Pi(t){return{input:[{type:"prompt",unit:"token",cost_usd:Ti(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Ti(t.output)}]}}function Fd(t,e,n,r){if(e.length===0)return null;let o=an(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Od[s.task]!==!0)return null;let a=Jn(i),l=on(s.model_id,s.variant,n),u=Cd(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 a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:_t(i),quantization:Td(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Pi(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Pi(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function Li(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?wt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.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:Pd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=Fd(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var $i={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},vt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Mi(t){let e=t.t;if(typeof e!="string"||!(e in $i))throw new vt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys($i).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 Bd(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new vt(`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 vt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Mi(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new vt(`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 Mi(t)}function Ni(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function Hd(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 Ui(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 Ni(e);let s=o.next();if(e!==void 0&&await Hd(s,e)==="aborted")throw s.catch(()=>{}),Ni(e);let i=await s;if(i.done)return;yield Bd(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var W=class extends Error{},q=class extends Error{},po="urs1.";function dn(t,e){return po+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function cn(t){if(!t.startsWith(po))return null;try{let e=JSON.parse(Buffer.from(t.slice(po.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 Hi(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 Di(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Gd(t);return e===null?[]:[e]}function jd(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)}
|
|
1
|
+
"use strict";var Ku=Object.create;var Fn=Object.defineProperty;var zu=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var Xu=Object.getPrototypeOf,Qu=Object.prototype.hasOwnProperty;var Zu=(t,e)=>{for(var n in e)Fn(t,n,{get:e[n],enumerable:!0})},Ys=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yu(e))!Qu.call(t,o)&&o!==n&&Fn(t,o,{get:()=>e[o],enumerable:!(r=zu(e,o))||r.enumerable});return t};var fe=(t,e,n)=>(n=t!=null?Ku(Xu(t)):{},Ys(e||!t||!t.__esModule?Fn(n,"default",{value:t,enumerable:!0}):n,t)),ed=t=>Ys(Fn({},"__esModule",{value:!0}),t);var tg={};Zu(tg,{ANONYMOUS_KEY_ID:()=>Hr,BIND_HOST:()=>Du,BUCKET_DOMAIN:()=>_s,BoundedLabel:()=>Kt,ControlPlaneUnavailableError:()=>$e,ConversationBackhauls:()=>en,ConversationCapacityError:()=>Un,DEFAULT_PORT:()=>Ms,EDGE_IDENTITY_PORT:()=>Su,EDGE_KEY_FINGERPRINT_HEADER:()=>ws,EDGE_KEY_ID_HEADER:()=>ys,InferenceMetrics:()=>zt,LEDGER_FUNCTION_PATH:()=>qs,LEDGER_WRITE_TIMEOUT_MS:()=>Gs,LedgerClient:()=>nn,LedgerDuplicateError:()=>tn,LedgerSurfaceError:()=>ae,MAX_CACHED_KEYS:()=>xs,MAX_CONVERSATIONS:()=>zr,MAX_CONVERSATION_HANDLES:()=>Us,MAX_MODEL_LABELS:()=>ps,MAX_ORG_LABELS:()=>fs,MAX_TENANTS:()=>Ns,METRICS_PATH:()=>Fr,METRICS_PORT:()=>vu,NO_MODEL_LABEL:()=>cs,ORG_BINDING_TTL_MS:()=>Es,OTHER_LABEL:()=>Vt,OrgResolver:()=>_t,ProxyAuthError:()=>J,READINESS_TIMEOUT_MS:()=>Vs,READINESS_TTL_MS:()=>Js,SERVE_FUNCTION:()=>Nn,TIER_DOMAIN:()=>vs,TenantRegistry:()=>Zt,bearerFrom:()=>Xt,bearerTokenOf:()=>ks,createEdgeIdentityServer:()=>jr,createHostedProxy:()=>Vu,createMetricsServer:()=>Br,edgeBucketId:()=>bs,edgeTierFingerprint:()=>Ss,laneOf:()=>ms,parseLedgerRecorded:()=>Ws,resolveHostedConfig:()=>Fu,statusClassOf:()=>gs,tenantSubject:()=>Qt});module.exports=ed(tg);var Gu=require("http");var Qs="audio",eo=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 Zs(t,e,n=1e4){try{return await td(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function td(t,e,n){let r=new eo(e,{sampleRate:24e3}),o=await r.startOutbound(),s=t.stream(Qs);await s.attach(o),typeof s.emit=="function"&&r.setDataEmit(a=>s.emit(a));let i=await nd(t,n);return await r.startInbound(i),r}function nd(t,e){let n=t.stream(Qs);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=l=>{l!=null&&(clearTimeout(i),s?.(),r(l))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var Xs="rt-video-in",on=256e3;function no(t){let e=t.stream(Xs),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${Xs}') 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>on)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${on}-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 rd=24e3,rn=480,od=111,sd=50,Bn=null;async function id(){if(Bn)return;let t=await import("opusscript");Bn=t.default??t}function ad(){if(!Bn)throw new Error("[opus-guard] opusscript module not loaded");return new Bn(rd,1,2048)}var to=class{constructor(e=ad){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>=sd}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 ei(){let t=await import("werift");await id();let e=new to;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let l=new Int16Array(i.length+a.length);l.set(i,0),l.set(a,i.length);let u=0;for(;l.length-u>=rn;){let d=l.subarray(u,u+rn);u+=rn;let c=Buffer.from(d.buffer,d.byteOffset,d.byteLength),f=e.encode(c,rn);if(f===null){i=l.slice(u);break}o=o+1&65535,s=s+rn>>>0;let h=new t.RtpHeader({version:2,payloadType:od,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),m=new t.RtpPacket(h,f);n.writeRtp(m)}i=l.slice(u)}}},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(l){if(e.wedged)throw l;return}let a=new Int16Array(i.length/2);for(let l=0;l<a.length;l++)a[l]=i.readInt16LE(l*2);r.onframe?.({samples:a})}),r},dispose:()=>e.dispose()}}var Hn=require("@urun-sh/core"),ro="rt-video-out";var ld="h264";function ud(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 dd(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;ud(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 ti="urun.videoOut.v2-ws";function ni(t){let e=t.stream(ro);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${ro}') 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=l=>{for(let u of r)u(l)},i=!1,a=async()=>{for await(let l of e.messages()){if(!(l instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${ro}" delivered a non-BINARY \xA75 payload (${typeof l}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let u;try{u=dd(l)}catch(d){s(d instanceof Error?d:new Error(String(d)));continue}for(let d of n)d(u)}for(let l of o)l()};return{codec:ld,onOutputFrame:l=>(n.add(l),i||(i=!0,a().catch(u=>s(u instanceof Error?u:new Error(String(u))))),()=>n.delete(l)),onLaneError:l=>(r.add(l),()=>r.delete(l)),onEnd:l=>(o.add(l),()=>o.delete(l))}}var Wn="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",cd=1007,oi=1008,De=1011,Jn=1008,C=class extends Error{constructor(n,r=cd){super(n);this.closeCode=r}closeCode},ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,jn=["setup","clientContent","realtimeInput","toolResponse"];function si(t){let e;try{e=JSON.parse(t)}catch{throw new C("client message is not valid JSON")}let n=ie(e);if(!n)throw new C("client message must be a JSON object");let r=jn.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!jn.includes(a));if(o.length>0)throw new C(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${jn.join(", ")}`);if(r.length!==1)throw new C(`client message must contain exactly one of ${jn.join(", ")} (got ${r.length})`);let s=r[0],i=ie(n[s]);if(!i)throw new C(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function ii(t,e){if(typeof t=="string")return t;let n=ie(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new C(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=ie(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new C(`${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 C(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new C(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
2
|
+
`)}var pd={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},et="urun.videoOut";function ai(t){return{framing:ti,codec:t}}function li(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[et]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var fd={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},md=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",et],ri=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function gd(t){let e=ie(t);if(!e)throw new C("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new C(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=ie(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new C("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new C(`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 C("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(!ri.includes(e.activityHandling))throw new C(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${ri.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var hd=["temperature","maxOutputTokens","responseModalities"];function ui(t){for(let[c,f]of Object.entries(fd))if(t[c]!==void 0)throw new C(f);for(let c of Object.keys(t))if(!md.includes(c))throw new C(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new C('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=ie(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new C("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!hd.includes(c))throw new C(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new C("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new C("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let f of c){let h=String(f).toUpperCase();if(h==="AUDIO"){o=!0;continue}if(h!=="TEXT")throw new C(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:ii(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new C("setup.tools must be an array");a=[];for(let c of t.tools){let f=ie(c);if(!f)throw new C("setup.tools entries must be objects");for(let h of Object.keys(f))if(h!=="functionDeclarations")throw new C(`unsupported tool "${h}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new C("tool.functionDeclarations must be an array");for(let h of f.functionDeclarations){let m=ie(h);if(!m||typeof m.name!="string")throw new C("functionDeclarations entries require a string name");a.push({type:"function",name:m.name,description:m.description,parameters:m.parameters})}}a.length===0&&(a=void 0)}let l={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=ie(t.sessionResumption);if(!c)throw new C("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(c))if(f!=="handle")throw new C(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new C("sessionResumption.handle must be a non-empty string when present");l={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let u=t.realtimeInputConfig===void 0?pd:gd(t.realtimeInputConfig),d=!1;if(t[et]!==void 0){if(!ie(t[et]))throw new C(`setup["${et}"] must be an object (the v1 opt-in is {})`);d=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:u,sessionResumption:l,videoOut:d}}function di(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function ci(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function pi(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new C(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new C("clientContent.turns must be an array");let n=[];for(let r of e){let o=ie(r);if(!o)throw new C("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 C(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:ii(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var qn=16e3,fi=24e3,yd=`audio/pcm;rate=${fi}`,mi=Buffer.alloc(960).toString("base64");function wd(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let l=a*s,u=Math.floor(l);if(u>=i){o[a]=t[i];continue}let d=l-u;o[a]=Math.round(t[u]+(t[u+1]-t[u])*d)}return o}function _d(t){let e=ie(t);if(!e)throw new C("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new C(`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 C("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 C("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function vd(t){let e=ie(t);if(!e)throw new C("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new C(`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])!==qn)throw new C(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${qn} Hz (audio/pcm;rate=${qn})`);if(typeof e.data!="string"||e.data.length===0)throw new C("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 C(`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=wd(o,qn,fi);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function gi(t){if(t.mediaChunks!==void 0)throw new C('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 C("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=ie(t[o]);if(!s||Object.keys(s).length!==0)throw new C(`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 C(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new C(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:vd(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:_d(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new C("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new C("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function hi(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new C(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new C("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=ie(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new C("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 yi(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function wi(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:yd,data:t}}]}}}}function _i(t){let e=ie(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let u of n){let d=ie(u);if(!(d?.type!=="message"||!Array.isArray(d.content)))for(let c of d.content){let f=ie(c);f?.type==="output_text"&&typeof f.text=="string"&&(s+=f.text)}}s&&o.push({role:"assistant",content:s});for(let u of n){let d=ie(u);if(d?.type!=="function_call")continue;if(typeof d.call_id!="string"||typeof d.name!="string")throw new C(`upstream function_call item is missing call_id/name: ${JSON.stringify(u)}`,De);let c=typeof d.arguments=="string"&&d.arguments.length>0?d.arguments:"{}",f;try{f=JSON.parse(c)}catch{throw new C(`upstream function_call arguments are not valid JSON: ${c}`,De)}r.push({id:d.call_id,name:d.name,args:f}),o.push({type:"function_call",call_id:d.call_id,name:d.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=ie(e.usage),l={serverContent:{turnComplete:!0}};if(a){let u={};typeof a.input_tokens=="number"&&(u.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(u.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(u.totalTokenCount=a.total_tokens),Object.keys(u).length>0&&(l.usageMetadata=u)}return i.push(l),{messages:i,assistantItems:o}}var Wi=require("crypto"),Ji=require("ws");var Hi=require("crypto");var Z=class extends Error{},bd=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Sd(t){if(typeof t!="string")return!1;let e=bd.exec(t);if(!e)return!1;let[,n,r,o,s,i,a]=e.map(Number);if(!Number.isFinite(Date.parse(t)))return!1;let l=new Date(Date.UTC(n,r-1,o,s,i,a));return l.getUTCFullYear()===n&&l.getUTCMonth()===r-1&&l.getUTCDate()===o&&l.getUTCHours()===s&&l.getUTCMinutes()===i&&l.getUTCSeconds()===a}function kd(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new Z(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r,regions:o,compliance:s}=e;if(typeof n!="string"||n==="")throw new Z(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new Z(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let i=r.map((a,l)=>{if(a===null||typeof a!="object")throw new Z(`catalog shared endpoints[${l}] is not an object: ${JSON.stringify(a)}`);let u=a;for(let c of["model_id","variant","app_slug","function"])if(typeof u[c]!="string"||u[c].length===0)throw new Z(`catalog shared endpoints[${l}] (${JSON.stringify(u)}) has no valid "${c}"`);if(u.app_id!==void 0&&u.app_id!==null&&(typeof u.app_id!="string"||u.app_id===""))throw new Z(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "app_id": ${JSON.stringify(u.app_id)}`);let d=(c,f)=>{if(u[c]!==void 0&&u[c]!==null&&!f)throw new Z(`catalog shared endpoints[${l}] (${u.model_id}:${u.variant}) carries a malformed "${c}": ${JSON.stringify(u[c])}`)};d("ready",typeof u.ready=="boolean"),d("ready_runtimes",typeof u.ready_runtimes=="number"&&Number.isInteger(u.ready_runtimes)&&u.ready_runtimes>=0),d("ready_since",Sd(u.ready_since));for(let c of["model_id","variant"]){let f=u[c];if(f.includes(":"))throw new Z(`catalog shared endpoints[${l}] has "${c}" containing ":" (${JSON.stringify(f)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return d("output_free",typeof u.output_free=="boolean"),u});if(o!=null&&(!Array.isArray(o)||!o.every(a=>typeof a=="string"&&a.length>0)))throw new Z(`catalog "shared" block regions is malformed: ${JSON.stringify(o)}`);if(s!=null){let a=s;if(typeof s!="object"||typeof a.zdr!="boolean"||typeof a.hipaa!="boolean")throw new Z(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(s)}`);for(let l of Object.keys(a))if(l!=="zdr"&&l!=="hipaa")throw new Z(`catalog "shared" block compliance carries "${l}" 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 bt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function vi(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=a=>new Z(`catalog rows[${s}] (${o.model_id}:${o.variant}) shared row is malformed: ${a}`);if(o.shared_org_id!==n)throw i(`shared_org_id ${JSON.stringify(o.shared_org_id)} disagrees with ${JSON.stringify(n)}`);for(let a of["model_id","variant"]){let l=o[a];if(typeof l!="string"||l===""||l.includes(":"))throw i(`"${a}" ${JSON.stringify(l)} 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 oo(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(u=>u.model_id===o);if(a.length===0)return null;if(s!==void 0){let u=a.find(d=>d.variant===s);return u?{shared_org_id:t.shared_org_id,endpoint:u}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let l=a.filter(u=>u.compat_default===!0);if(l.length!==1)throw new Z(`shared model "${o}" has ${l.length} compat_default rows (exactly one required) among variants ${a.map(u=>u.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:l[0]}}async function bi(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new Z(`catalog read failed: GET ${n} \u2192 ${r.status}`);return kd(await r.json())}function ye(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var _e=class extends Error{name="ModelPriceError"},so="per_million_input_tokens",io="per_million_output_tokens",ki="model_id,variant,unit,price_usd,effective_at,expires_at",Si={per_request:!0,per_minute:!0,per_output_unit:!0},Rd=5e3;function Ed(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new _e(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Ri(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new _e(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function xd(t,e,n){return t===null?null:Ri(t,e,n)}function Ad(t,e){if(t===so)return"input";if(t===io)return"output";if(typeof t=="string"&&Object.hasOwn(Si,t))return null;throw new _e(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${so} | ${io}) nor a known GPU-time unit (${Object.keys(Si).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 Id(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 ao(t,e){return`${t}\0${e}`}function Od(t){if(!Array.isArray(t))throw new _e(`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 _e(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let u of ki.split(","))if(!Object.hasOwn(s,u))throw new _e(`${o} has no "${u}" column: ${JSON.stringify(s)}`);let i=Ad(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new _e(`${o} has no model_id (${JSON.stringify(s)})`);let l=s.variant;if(!(l===null||typeof l=="string"&&l!==""))throw new _e(`${o} has a non-string variant (${JSON.stringify(l)})`);e.push({model_id:a,variant:l,side:i,usd:Ed(s.price_usd,o),effective_at:Ri(s.effective_at,o,"effective_at"),expires_at:xd(s.expires_at,o,"expires_at")})}return e}function Ei(t,e=Date.now(),n){let r=new Map,o=new Map;for(let l of t){if(l.effective_at>e||l.expires_at!==null&&l.expires_at<=e)continue;let u=r.get(l.model_id);u||(u=new Map,r.set(l.model_id,u),o.set(l.model_id,new Map));let d=l.variant??"",c=u.get(d);c||(c={input:[],output:[]},u.set(d,c),o.get(l.model_id).set(d,l.variant)),c[l.side].push({effective_at:l.effective_at,usd:l.usd})}let s=[],i=[];for(let[l,u]of r){let d=u.get(""),c=(f,h,m)=>{let _=f&&f.length>0?f:d?.[h];if(!_||_.length===0)return null;let R=Id(_,h);return"reason"in R?R:R.rate.usd===0?h==="output"&&m!==null&&n?.has(ao(l,m))?R.rate:{reason:`the ${h} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:R.rate};for(let[f,h]of o.get(l)){let m=u.get(f),_=c(m?.input,"input",h),R=c(m?.output,"output",h);if(_!==null&&"reason"in _){i.push({model_id:l,variant:h,reason:_.reason});continue}if(R!==null&&"reason"in R){i.push({model_id:l,variant:h,reason:R.reason});continue}_===null||R===null||s.push({model_id:l,variant:h,pricing:{input:_.usd,output:R.usd}})}}let a=(l,u)=>l.model_id.localeCompare(u.model_id)||(l.variant===null?1:0)-(u.variant===null?1:0)||(l.variant??"").localeCompare(u.variant??"");return{prices:s.sort(a),refusals:i.sort(a)}}function sn(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 an={prices:[],refusals:[]};async function xi(t){let e=t.fetchImpl??fetch,n=`${so},${io}`,r=await e(`${t.catalogUrl}/model_prices?select=${ki}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(Rd)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return Od(await r.json())}var nt="/partners/openrouter/models",Td={chat:!0,code:!0,agent:!0,vl:!0},Ai={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Pd(t){let e=t.toLowerCase();return Object.hasOwn(Ai,e)?Ai[e]:null}var Ii={"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 Cd(t,e){if(!t||t.length===0)return[];let n=[],r=[];for(let o of t){let s=Object.hasOwn(Ii,o)?Ii[o]:null;if(s===null){r.push(o);continue}n.some(a=>a.region===o)||n.push({country_code:s,region:o})}return r.length>0&&e(`urun openrouter doc: shared block region(s) ${r.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),n}var Oi={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},Ti={2:"Llama2",3:"Llama3"};function Ld(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(Oi,s))return Oi[s];let i=r[o+1];if(s==="llama"&&i!==void 0&&Object.hasOwn(Ti,i))return Ti[i];if(s==="phi"&&i!==void 0&&/^\d/.test(i))return"Phi"}return null}var $d=["context_length","max_model_len"];function Md(t){let e=$d.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 Vn(t){let e=t.map(Md),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function Nd(t){let e=t.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function lo(t){if(t.length===0)return null;let e=t.map(Nd),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function uo(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 Ud(t,e){let n=e.filter(s=>ye(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return ln(n);let r=e.filter(s=>ye(s.model_id)===t);if(r.length>0)return ln(r);let o=uo(t,e);return o.length>0?ln(o):null}function ln(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:Dd(t),matches:t}:null}function Dd(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 je=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 je(`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 je(`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 je(`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]),a=Number(o[3]),l=Date.UTC(s,i-1,a),u=new Date(l);if(u.getUTCFullYear()!==s||u.getUTCMonth()!==i-1||u.getUTCDate()!==a)throw new je(`model "${e}" carries a malformed created_at ("${r}") \u2014 not a real calendar date`);return l/1e3}function tt(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 Kn(t,e,n){let r=Ud(t,e);if(!r)return tt({id:t,object:"model",created:0,owned_by:"urun"});let{row:o,matches:s}=r,i=Vn(s),a=St(s),l=sn(o.model_id,o.variant,n),u=Li(o,s),d=lo(s);return tt({id:t,object:"model",created:a,owned_by:"urun",...i!==null?{context_length:i}:{},...l!==null?{pricing:l}:{},...u.published.length>0?{voices:[...u.published]}:{},...d!==null?{capabilities:{reasoning:d}}:{}})}var Fd=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function Li(t,e){if((t.task??void 0)!=="tts")return{published:[],defect:null};let n=e.map(s=>s.engine_args?.voices),r=n[0];if(Array.isArray(r)&&r.length>0&&r.every(s=>typeof s=="string")&&n.every(s=>Array.isArray(s)&&s.length===r.length&&s.every((i,a)=>i===r[a])))return{published:[...r],defect:null};let o=n.some(s=>s!=null)?`the catalog's engine_args.voices for ${t.model_id}:${t.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return t.model_id==="qwen3-tts-customvoice"?{published:[...Fd],defect:o}:{published:[],defect:o}}function co(t){let e=t.length>0?ln(t):null;return e===null?{published:[],defect:null}:Li(e.row,e.matches)}function Pi(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 Ci(t){return{input:[{type:"prompt",unit:"token",cost_usd:Pi(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Pi(t.output)}]}}function Bd(t,e,n,r){if(e.length===0)return null;let o=ln(e);if(!o)return null;let{row:s,matches:i}=o;if(!s.task||Td[s.task]!==!0)return null;let a=Vn(i),l=sn(s.model_id,s.variant,n),u=Ld(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 a!==null&&(d.max_tokens={type:"integer",min:1,max:a,unit:"token"}),{schema_version:"2.4",id:`${s.model_id}:${s.variant}`,name:`${s.model_id}:${s.variant}`,created:St(i),quantization:Pd(s.variant),...u!==null?{tokenizer:u}:{},description:s.description??"",hugging_face_id:s.hf_repo?s.hf_repo.split("@")[0]??s.hf_repo:"",is_ready:t.ready===!0&&l!==null,is_free:!1,input_modalities:[{type:"text",...a!==null?{supported_inputs:{max_context_length:{value:a,unit:"token"}}}:{},...l?{pricing:Ci(l).input}:{}},...s.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:d,...l?{pricing:Ci(l).output}:{}}],...r.datacenters.length>0?{datacenters:r.datacenters}:{},...r.compliance?{compliance:r.compliance}:{}}}function $i(t,e,n,r){let o=r??(u=>console.warn(u.trimEnd())),s=t?bt(t):[];if(s.length>0){let u=s.filter(d=>d.ready===void 0);if(u.length===s.length)o("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(u.length>0){let d=u.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:Cd(t?.regions,o),compliance:t?.compliance??null},a=[],l=new Set;for(let u of s){let d=`${u.model_id}:${u.variant}`;if(l.has(d))continue;l.add(d);let c=Bd(u,e.filter(f=>f.model_id===u.model_id&&f.variant===u.variant),n,i);c&&a.push(c)}return{data:a}}var Mi={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},kt=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function Ni(t){let e=t.t;if(typeof e!="string"||!(e in Mi))throw new kt(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(Mi).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 Hd(t){if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch(n){throw new kt(`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 kt(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return Ni(e)}if(t===null||typeof t!="object"||Array.isArray(t))throw new kt(`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 Ni(t)}function Ui(t){return t.reason instanceof Error?t.reason:new Error("the turn-lane consumer aborted")}async function jd(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 Di(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 Ui(e);let s=o.next();if(e!==void 0&&await jd(s,e)==="aborted")throw s.catch(()=>{}),Ui(e);let i=await s;if(i.done)return;yield Hd(i.value)}}finally{let s=o.return?.();s&&s.catch(()=>{})}}return r()}var W=class extends Error{},q=class extends Error{},fo="urs1.";function cn(t,e){return fo+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function Rt(t){if(!t.startsWith(fo))return null;try{let e=JSON.parse(Buffer.from(t.slice(fo.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 ji(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 Fi(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Wd(t);return e===null?[]:[e]}function qd(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 a=typeof i=="number"?i:typeof i=="string"?Number.parseInt(i,10):NaN;if(!Number.isInteger(a)||a<s){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(o)}=${JSON.stringify(i)})
|
|
4
|
-
`),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function
|
|
5
|
-
`),
|
|
6
|
-
`);return r}outputFreeKeys(e){let n=new Set;if(!e)return n;for(let r of e.endpoints)r.output_free===!0&&n.add(
|
|
7
|
-
`);let l=(n?wt(n):[]).map(u=>{let d=s.filter(v=>v.model_id===u.model_id&&v.variant===u.variant),c=Jn(d),f=_t(d),h=ao(d),m=on(u.model_id,u.variant,i),_=uo(d);return Ze({id:`${u.model_id}:${u.variant}`,object:"model",created:f,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},..._.published.length>0?{voices:[..._.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>Vn(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return Li(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=co(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Fi(`${r.modelId}:${r.variant}`,s).includes(n)}return Di(fo(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?je(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:je(ln(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?je(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":je(ln(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?je(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":je(ln(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):ln(n,r);return Jd(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):ln(n,r);return uo(o)}async imageModelList(){let e=await this.catalogRows(),n=sn,r=[];for(let s of await this.availableIds()){let i=Di(fo(s,e));i.length!==0&&r.push(Ze({...Vn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of wt(o)){let i=co(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Fi(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=Ze({id:`${s.model_id}:${s.variant}`,object:"model",created:_t(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=sn,r=[];for(let s of await this.availableIds())je(qi(s,e))==="stt"&&r.push(Vn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of wt(o)){let i=co(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(je(i)!=="stt")continue;let a=Ze({id:`${s.model_id}:${s.variant}`,object:"model",created:_t(i),owned_by:"urun"});r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Vd=256,go=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Vd;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Kd="local",pn=t=>t.slice(0,120),ho=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 W){this.ws.close(ri,pn(e.message));return}if(e instanceof q){this.ws.close(Wn,pn(e.message));return}if(e instanceof C){this.ws.close(e.closeCode,pn(e.message));return}this.ws.close(Ue,pn(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=oi(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 C(`"${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}=ci(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=mi(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:fi);return}this.transcript.push(...gi(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new C("setup may only be sent once, as the first client message");let n=li(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new C("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 C(`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 C("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 C(`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),a=i.onOutputFrame(u=>this.send(ai(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[Qe]=ii(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 C("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new C("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Ue);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(yi(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 C("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new C("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Ue);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 C(`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 C("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 C("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,Gi.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(ui(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(di(e.timeLeftMs)),this.ws.close(Ue,pn(`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 l of r){if(n.interrupted)break;let u=l;if(u.type==="error")throw new C(`upstream error: ${JSON.stringify(u)}`,Ue);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=hi(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new C("upstream produced no response.completed event",Ue);let{messages:i,assistantItems:a}=wi(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},nt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function zd(t,e,n){let r=new Set;(l=>{if(typeof l=="string")l!==""&&r.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&r.add(u)})(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 nt(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 nt(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let l of r)a=l;if(a===void 0&&n)throw new nt(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function yo(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 Wi.WebSocketServer({noServer:!0}),o=new go;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Gn&&(a.on("error",()=>{}),(async()=>{let d=zd(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new nt(401,"invalid local proxy api key");c={clients:e.clients,scope:Kd}}r.handleUpgrade(i,a,l,f=>{new ho(f,c,o)})})().catch(d=>{let c=502;(d instanceof nt||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let f=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${f}\r
|
|
4
|
+
`),r=!0;break}e[o]=a}return r||Object.keys(e).length===0?null:e}function go(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||ye(`${r.model_id}-${r.variant}`)===e.appSlug||ye(r.model_id)===e.appSlug)),n?qd(n.engine_args?.pool):null}function po(t,e,n,r,o){if(!o)throw new Z(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new Z(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new Z(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function Bi(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new Z(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var qi="shared:",Et="speech:",ot="realtime:";function Ge(t){return t.sharedApp?qi+t.appSlug:t.appSlug}function dn(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 mo(t,e){let n=e.filter(s=>ye(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>ye(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function Gd(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Wd(t){let e=t.map(Gd),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var Jd={stt:"stt",tts:"tts"};function qe(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:Jd[e];return r!==void 0?n?r:null:n&&t.every(o=>o.engine_args?.realtime===!0)?"decision":null}function Gi(t,e){let n=mo(t,e);return n.length>0?n:uo(t,e)}function un(t,e){return Gi(t.appSlug,e)}function Vd(t){let e=t.map(r=>r.engine_args?.transcript_stream).filter(r=>r!=null);if(e.length===0)return"stt";let n=e[0];if(typeof n!="string"||n.length===0||!e.every(r=>r===n))throw new Z(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return n}var zn=6e4,Yn=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??zn):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??zn):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??zn):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??zn;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 _e)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
|
+
`),an}let r=Ei(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(ao(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(qi)||o.startsWith(Et)||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 W(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=oo(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,a=ye(s),l=n.endpoints.filter(c=>ye(c.model_id)===a&&(i===void 0||c.variant===i)),u=new Set(l.map(c=>c.model_id)),d=[...u][0];return d===void 0||u.size!==1?null:oo(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=ye(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(),a=this.servable(i);if(a.includes(o))return{appSlug:o};let l=a.filter(d=>d.startsWith(`${o}-`));if(l.length===1)return{appSlug:l[0]};if(l.length>1)throw new W(`model "${n}" is ambiguous across deployed apps ${l.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new W(`model "${n}" maps to app "${u.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let a=(await this.opts.listCatalog()).find(l=>n===l.model_id||n===`${l.model_id}:${l.variant}`||o===ye(l.model_id)||o===ye(`${l.model_id}-${l.variant}`));if(a)throw new W(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${a.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=dn(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async poolTuningFor(e){return go(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ge(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Ge(n))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return dn(await this.resolveTarget(e))}async speechSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,Et+Ge(n))}async dedicatedSessionFor(e){let n=await this.resolveTarget(e);return this.acquire(n,ot+(0,Hi.randomUUID)())}async evictHandle(e){let n=Rt(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:dn(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:cn(n,this.keyOf(r))}}async speechHandleFor(e){let{app:n,entry:r}=await this.speechSessionFor(e);return{app:n,handle:cn(n,this.keyOf(r))}}async sessionForHandle(e){let n=Rt(e);if(!n)throw new q(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:r,key:o}=n,s=this.pool.get(r),i=s?await s.then(a=>a,()=>null):null;if(i===null)throw new q(`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 q(`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(u=>({ok:!0,rows:u}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(n))]),s=r.rows,i=r.ok?o:an;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 l=(n?bt(n):[]).map(u=>{let d=s.filter(v=>v.model_id===u.model_id&&v.variant===u.variant),c=Vn(d),f=St(d),h=lo(d),m=sn(u.model_id,u.variant,i),_=co(d);return tt({id:`${u.model_id}:${u.variant}`,object:"model",created:f,owned_by:"urun",...c!==null?{context_length:c}:{},...m!==null?{pricing:m}:{},..._.published.length>0?{voices:[..._.published]}:{},...h!==null?{capabilities:{reasoning:h}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?l:[...e.map(u=>Kn(u,s,i)),...l]}}async openRouterModels(){let e=await this.sharedBlock(),[n,r]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return $i(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=po(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return Bi(`${r.modelId}:${r.variant}`,s).includes(n)}return Fi(mo(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?qe(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:qe(un(n,r))!==null}async supportsSpeech(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?qe(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="tts":qe(un(n,r))==="tts"}async supportsTranscription(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?qe(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))==="stt":qe(un(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):un(n,r);return Vd(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):un(n,r);return co(o)}async imageModelList(){let e=await this.catalogRows(),n=an,r=[];for(let s of await this.availableIds()){let i=Fi(mo(s,e));i.length!==0&&r.push(tt({...Kn(s,e,n),image_modes:i}))}let o=await this.sharedBlock();if(o)for(let s of bt(o)){let i=po(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=Bi(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let l=tt({id:`${s.model_id}:${s.variant}`,object:"model",created:St(i),owned_by:"urun",image_modes:a});r.push(l)}return{object:"list",data:r}}async speechToTextModelList(){let e=await this.catalogRows(),n=an,r=[];for(let s of await this.availableIds())qe(Gi(s,e))==="stt"&&r.push(Kn(s,e,n));let o=await this.sharedBlock();if(o)for(let s of bt(o)){let i=po(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null);if(qe(i)!=="stt")continue;let a=tt({id:`${s.model_id}:${s.variant}`,object:"model",created:St(i),owned_by:"urun"});r.push(a)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Kd=256,ho=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Kd;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},zd="local",pn=t=>t.slice(0,120),yo=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 W){this.ws.close(oi,pn(e.message));return}if(e instanceof q){this.ws.close(Jn,pn(e.message));return}if(e instanceof C){this.ws.close(e.closeCode,pn(e.message));return}this.ws.close(De,pn(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=si(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 C(`"${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}=pi(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=gi(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:mi);return}this.transcript.push(...hi(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new C("setup may only be sent once, as the first client message");let n=ui(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new C("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",Jn);if(s.model!==n.model)throw new C(`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 C("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 C(`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`,Jn);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(u=>this.send(li(u))),l=i.onLaneError(u=>this.fail(u));this.detachVideoOut=()=>{a(),l()},o[et]=ai(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 C("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new C("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",De);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(wi(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 C("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new C("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",De);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 C(`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 C("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 C("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,Wi.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(di(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(ci(e.timeLeftMs)),this.ws.close(De,pn(`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 l of r){if(n.interrupted)break;let u=l;if(u.type==="error")throw new C(`upstream error: ${JSON.stringify(u)}`,De);if(u.type==="response.completed"){o=u.response,s=!0;continue}let d=yi(u);d&&this.send(d)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new C("upstream produced no response.completed event",De);let{messages:i,assistantItems:a}=_i(o);this.transcript.push(...a);for(let l of i)this.send(l);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},st=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Yd(t,e,n){let r=new Set;(l=>{if(typeof l=="string")l!==""&&r.add(l);else if(Array.isArray(l))for(let u of l)u!==""&&r.add(u)})(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 st(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 st(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let l of r)a=l;if(a===void 0&&n)throw new st(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function wo(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 Ji.WebSocketServer({noServer:!0}),o=new ho;t.on("upgrade",(i,a,l)=>{let u=new URL(i.url??"/","http://localhost");u.pathname===Wn&&(a.on("error",()=>{}),(async()=>{let d=Yd(i,u,n),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new st(401,"invalid local proxy api key");c={clients:e.clients,scope:zd}}r.handleUpgrade(i,a,l,f=>{new yo(f,c,o)})})().catch(d=>{let c=502;(d instanceof st||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let f=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",h=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${f}\r
|
|
8
8
|
Connection: close\r
|
|
9
9
|
\r
|
|
10
10
|
${h}\r
|
|
11
|
-
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(l=>l===void 0?i():a(l)))})(),s)}var
|
|
12
|
-
`}var Yd=256,Xd=128;function me(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Xd)}var ot=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>=Yd?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},Qd=256;function Zd(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 st=class extends Error{},kt=class{conversations=new Map;thread(e,n){let r=Zd(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new st(`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<=Qd)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},Zi=new WeakMap;function mn(t){let e=Zi.get(t);return e||(e=new kt,Zi.set(t,e)),e}function Rt(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function $e(t){return t.find(e=>e.type==="response.completed")?.response??null}function Et(t){return t.type!=="response.function_call_arguments.delta"||typeof t.tool_index!="number"?null:{tool_index:t.tool_index,call_id:typeof t.call_id=="string"?t.call_id:void 0,name:typeof t.name=="string"?t.name:void 0,delta:typeof t.delta=="string"?t.delta:""}}var Ge=class{calls=new Map;add(e){let n=this.calls.get(e.tool_index),r=!n;return n||(n={args:""},this.calls.set(e.tool_index,n)),e.call_id&&(n.id=e.call_id),e.name&&(n.name=e.name),n.args+=e.delta,{call:n,isNew:r}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([e,n])=>({type:"function_call",call_id:n.id??`call_${e}`,name:n.name??"",arguments:n.args}))}},ec=["<tool_call>","<function="];function tc(t){return ec.find(e=>t.includes(e))}function it(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 at(t,e,n){if(!(!t||e>0))return tc(n)}function xt(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 De(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function nc(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 _o(t,e){let n=nc(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var be=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function At(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof st?new be(n.message,"previous_response_not_found",400,"previous_response_id"):new be(String(n instanceof Error?n.message:n),"invalid_input")}}function ea(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function vo(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new be("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}:{},...ea(e)!==void 0?{response_format:ea(e)}:{}},o)}async function gn(t){let{body:e,clients:n,store:r,stats:o}=t,s=At(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,l=e.store!==!1,u=me(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await vo(n,e,s,!0,c?ve(c):void 0);return{responseId:i,events:ic({events:f,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function rc(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?sc(o[i++],l):l),...oc(r,n)]}function oc(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function sc(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*ic(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=D=>D.response&&typeof D.response=="object"?{...D,response:{...D.response,id:r}}:D,f=`item_${r.slice(5)}`,h=!1,m=!1,_=0;function*R(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],b=(D,j)=>{v.push({output_index:D,item:j})},p=!1,g=0,y="",S=0,x="";function*E(){if(!p)return;p=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:x};let D={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:x}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:D},b(g,D),x=""}let I=!1,k=0,O="",w=0,A="",P="";function*T(D){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:O,output_index:k,content_index:0,text:A},yield{type:"response.content_part.done",item_id:O,output_index:k,content_index:0,part:{type:"output_text",text:A}};let j={id:O,type:"message",role:"assistant",status:D,content:[{type:"output_text",text:A}]};yield{type:"response.output_item.done",output_index:k,item:j},b(k,j),A=""}let L=new Ge,N=null,V=-1;function*H(D){if(!N)return;let j=N;N=null,yield{type:"response.function_call_arguments.done",item_id:j.fcId,output_index:j.outputIndex,arguments:j.args};let K={id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:j.args,status:D};yield{type:"response.output_item.done",output_index:j.outputIndex,item:K},b(j.outputIndex,K)}let Y=!1;for await(let D of u.track(e,o,t.turn)){d.push(D);let j=String(D.type??"");if(j==="response.created"||j==="response.in_progress"){h=!0,yield c(D);continue}if(j==="response.output_item.added"){m=!0,yield c(D);continue}if(j==="response.reasoning_text.delta"&&!m){yield*R(),p||(p=!0,g=_++,S+=1,y=S===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${S}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),x+=String(D.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:D.delta};continue}if(j==="response.output_text.delta"&&!m){yield*R(),yield*E(),I||(I=!0,k=_++,w+=1,O=w===1?f:`${f}_${w}`,yield{type:"response.output_item.added",output_index:k,item:{id:O,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:O,output_index:k,content_index:0,part:{type:"output_text",text:""}}),A+=String(D.delta??""),P+=String(D.delta??""),yield{type:j,item_id:O,output_index:k,content_index:0,delta:D.delta};continue}let K=m?null:Et(D);if(K){if(yield*R(),yield*E(),yield*T("completed"),L.add(K),K.tool_index!==V){yield*H("completed"),V=K.tool_index;let Ye=_++;N={fcId:`fc_${r.slice(5)}_${K.tool_index}`,outputIndex:Ye,callId:K.call_id,name:K.name,args:""},yield{type:"response.output_item.added",output_index:Ye,item:{id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:"",status:"in_progress"}}}N&&(K.call_id&&(N.callId=K.call_id),K.name&&(N.name=K.name),N.args+=K.delta,yield{type:"response.function_call_arguments.delta",item_id:N.fcId,output_index:N.outputIndex,delta:K.delta});continue}if(j==="response.completed"&&!m){let Ye=Rt(D.response),yt=at(s,L.size+Ye.length,P);if(yt){Y=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:it(o,yt)}};break}if(yield*E(),yield*T("completed"),yield*H("completed"),L.size===0)for(let re of Ye){let Ee=_++,Xe=re.id??re.call_id??`fc_${Ee}`,Qr=re.arguments??"",Vs={id:Xe,type:"function_call",call_id:re.call_id??Xe,name:re.name??""};yield{type:"response.output_item.added",output_index:Ee,item:{...Vs,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Xe,output_index:Ee,delta:Qr},yield{type:"response.function_call_arguments.done",item_id:Xe,output_index:Ee,arguments:Qr};let Ks={...Vs,arguments:Qr,status:"completed"};yield{type:"response.output_item.done",output_index:Ee,item:Ks},b(Ee,Ks)}let Q=rc(v,D.response);yield Q.length>0?c({...D,response:{...D.response,output:Q}}):c(D);continue}yield c(D)}if(yield*E(),yield*T("incomplete"),yield*H("incomplete"),i&&!Y){let D=$e(d);l.remember(r,n,_o(D,xt(d,D)),a)}}var Se=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ue=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var We=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)}},hn=class extends We{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},bo=class extends We{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")}},xe=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Yn=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 hn;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 hn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let l=r+n-Date.now();if(l<=0)throw new bo(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);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 hn}}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 a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}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 So=require("@urun-sh/core"),Ae=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)}},ko=33e4;function ta(t,e=ko){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Xn),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof q||u instanceof So.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Xn?(await r.return?.(void 0),new Ae("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 Ae("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ae("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Xn=class extends Error{constructor(){super("stream idle timeout")}};function na(t){return t instanceof Ae?!1:t instanceof q?!0:t instanceof So.SessionFailedError?t.kind==="transport-failed":!1}var ac=[/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 Oe(t){return!ac.some(e=>e.test(t))}function Te(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 we(t,e){if(t instanceof q)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=ra(t);return n||{message:Te(e?.inferenceId??null),redacted:!0}}function ra(t){return t instanceof He?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Z?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof W?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:t instanceof We?{message:t.message,redacted:!1}:t instanceof Ae?Oe(t.message)?{message:t.message,redacted:!1}:null:t instanceof xe?{message:t.message,redacted:!1}:t instanceof ue?{message:t.message,redacted:!1}:null}function It(t,e,n){let r=n??(i=>console.error(i)),o=ra(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ie(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Oe(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${Ie(e)}`),`the ${t} upstream failed while serving this request`)}function Me(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Oe(e)?e:null}function Ie(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var xo="/v1/responses",lc=64*1024*1024,uc=8*1024*1024,dc=16,oa=32,sa=3600*1e3,cc=/^[A-Za-z0-9._-]{1,256}$/;function ge(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var pc=ge(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 Ao(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function fc(t){for(;t.bufferedAmount>uc&&t.readyState===Je.WebSocket.OPEN;){let{promise:e,resolve:n}=Ao();setTimeout(n,5),await e}}var Ro=class extends kt{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 st))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)}},Eo=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 Ro(mn(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${sa/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},sa).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(ge(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(ge(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(ge(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(ge(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(ge(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(ge(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"||!cc.test(o.stream_id)){this.sendFrame(pc);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=oa){this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${oa}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(this.closed)return;await this.acquire();let r=rt();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await gn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:fn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==Je.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await fc(this.ws)}}finally{this.activeTurns.delete(i)}}catch(o){this.failTurn(o,n,e,r)}finally{this.release()}}runWarmup(e,n){if(this.closed)return;let r=rt(),o=fn(r);try{let s=At(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:Ie(e);if(e instanceof be)return ge(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof W)return ge(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof q){let a=we(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ge(503,{type:"upstream_error",code:"session_gone",message:a.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}`),ge(s.status,{type:s.openaiType,message:o},n);let i=we(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}`),ge(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Me(o),a=i??Te(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)}`),ge(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=dc;){let{promise:e,resolve:n}=Ao();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!==Je.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!==Je.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Qn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
11
|
+
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(l=>l===void 0?i():a(l)))})(),s)}var Ve=require("ws");var Vi=require("crypto"),Ki="Inference-Id";function it(){return(0,Vi.randomUUID)()}function _o(t){return t==="/v1"||t.startsWith("/v1/")}function zi(t,e){if(!_o(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 fn(t){return`resp_${t}`}function Yi(t){return`chatcmpl-${t}`}function Xi(t){return`msg_${t}`}function ve(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function Qi(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 Zi(t){return`${JSON.stringify(t)}
|
|
12
|
+
`}var Xd=256,Qd=128;function me(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Qd)}var at=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>=Xd?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let u of e)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield u;let l=(performance.now()-(i??s))/1e3;a>0&&l>0&&(o.tokRates.push(a/l),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}}}},Zd=256;function ec(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 lt=class extends Error{},xt=class{conversations=new Map;thread(e,n){let r=ec(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new lt(`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<=Zd)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},ea=new WeakMap;function mn(t){let e=ea.get(t);return e||(e=new xt,ea.set(t,e)),e}function At(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function Me(t){return t.find(e=>e.type==="response.completed")?.response??null}function It(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 We=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}))}},tc=["<tool_call>","<function="];function nc(t){return tc.find(e=>t.includes(e))}function ut(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 dt(t,e,n){if(!(!t||e>0))return nc(n)}function Ot(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 Fe(t){let e=t?.urun_timing?.output_seconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function rc(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 vo(t,e){let n=rc(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var be=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Tt(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof lt?new be(n.message,"previous_response_not_found",400,"previous_response_id"):new be(String(n instanceof Error?n.message:n),"invalid_input")}}function ta(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function bo(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new be("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}:{},...ta(e)!==void 0?{response_format:ta(e)}:{}},o)}async function gn(t){let{body:e,clients:n,store:r,stats:o}=t,s=Tt(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,l=e.store!==!1,u=me(e);o.model(u);let d=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,f=await bo(n,e,s,!0,c?ve(c):void 0);return{responseId:i,events:ac({events:f,conversation:s,responseId:i,modelKey:u,requestHadTools:d,remember:a,persist:l,store:r,stats:o,turn:t.turn})}}function oc(t,e){let n=[...t].sort((l,u)=>l.output_index-u.output_index).map(({item:l})=>l),r=Array.isArray(e?.output)?e.output:[],o=r.filter(l=>l!==null&&typeof l=="object"&&l.type==="message"),s=n.filter(l=>l.type==="message").length===o.length,i=0;return[...n.map(l=>l.type==="message"&&s?ic(o[i++],l):l),...sc(r,n)]}function sc(t,e){let n=e.some(u=>u.type==="message"),r=e.some(u=>u.type==="reasoning"),o=u=>String(u.call_id??u.id??""),s=e.filter(u=>u.type==="function_call"),i=t.filter(u=>u!==null&&typeof u=="object"&&u.type==="function_call").length,a=s.length===i,l=new Set(s.map(o));return t.filter(u=>{if(u===null||typeof u!="object")return!0;let d=u;return d.type==="message"?!n:d.type==="reasoning"?!r:d.type==="function_call"?!a&&!l.has(o(d)):!0})}function ic(t,e){let n=a=>a!==null&&typeof a=="object"&&a.type==="output_text",r=Array.isArray(t.content)?t.content:[];if(r.filter(n).length!==1)return e;let s=(Array.isArray(e.content)?e.content:[]).find(n);if(s===void 0)return e;let i={...t};return i.id=e.id,t.role===void 0&&(i.role=e.role),t.status===void 0&&(i.status=e.status),i.content=r.map(a=>n(a)?{...a,text:s.text}:a),i}async function*ac(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:l,stats:u}=t,d=[],c=D=>D.response&&typeof D.response=="object"?{...D,response:{...D.response,id:r}}:D,f=`item_${r.slice(5)}`,h=!1,m=!1,_=0;function*R(){h||(h=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let v=[],b=(D,j)=>{v.push({output_index:D,item:j})},p=!1,g=0,y="",S=0,x="";function*E(){if(!p)return;p=!1,yield{type:"response.reasoning_text.done",item_id:y,output_index:g,content_index:0,text:x};let D={id:y,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:x}],status:"completed"};yield{type:"response.output_item.done",output_index:g,item:D},b(g,D),x=""}let I=!1,k=0,O="",w=0,A="",T="";function*P(D){if(!I)return;I=!1,yield{type:"response.output_text.done",item_id:O,output_index:k,content_index:0,text:A},yield{type:"response.content_part.done",item_id:O,output_index:k,content_index:0,part:{type:"output_text",text:A}};let j={id:O,type:"message",role:"assistant",status:D,content:[{type:"output_text",text:A}]};yield{type:"response.output_item.done",output_index:k,item:j},b(k,j),A=""}let L=new We,N=null,V=-1;function*H(D){if(!N)return;let j=N;N=null,yield{type:"response.function_call_arguments.done",item_id:j.fcId,output_index:j.outputIndex,arguments:j.args};let K={id:j.fcId,type:"function_call",call_id:j.callId??j.fcId,name:j.name??"",arguments:j.args,status:D};yield{type:"response.output_item.done",output_index:j.outputIndex,item:K},b(j.outputIndex,K)}let Y=!1;for await(let D of u.track(e,o,t.turn)){d.push(D);let j=String(D.type??"");if(j==="response.created"||j==="response.in_progress"){h=!0,yield c(D);continue}if(j==="response.output_item.added"){m=!0,yield c(D);continue}if(j==="response.reasoning_text.delta"&&!m){yield*R(),p||(p=!0,g=_++,S+=1,y=S===1?`rs_${r.slice(5)}`:`rs_${r.slice(5)}_${S}`,yield{type:"response.output_item.added",output_index:g,item:{id:y,type:"reasoning",summary:[],content:[],status:"in_progress"}}),x+=String(D.delta??""),yield{type:"response.reasoning_text.delta",item_id:y,output_index:g,content_index:0,delta:D.delta};continue}if(j==="response.output_text.delta"&&!m){yield*R(),yield*E(),I||(I=!0,k=_++,w+=1,O=w===1?f:`${f}_${w}`,yield{type:"response.output_item.added",output_index:k,item:{id:O,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:O,output_index:k,content_index:0,part:{type:"output_text",text:""}}),A+=String(D.delta??""),T+=String(D.delta??""),yield{type:j,item_id:O,output_index:k,content_index:0,delta:D.delta};continue}let K=m?null:It(D);if(K){if(yield*R(),yield*E(),yield*P("completed"),L.add(K),K.tool_index!==V){yield*H("completed"),V=K.tool_index;let Qe=_++;N={fcId:`fc_${r.slice(5)}_${K.tool_index}`,outputIndex:Qe,callId:K.call_id,name:K.name,args:""},yield{type:"response.output_item.added",output_index:Qe,item:{id:N.fcId,type:"function_call",call_id:N.callId??N.fcId,name:N.name??"",arguments:"",status:"in_progress"}}}N&&(K.call_id&&(N.callId=K.call_id),K.name&&(N.name=K.name),N.args+=K.delta,yield{type:"response.function_call_arguments.delta",item_id:N.fcId,output_index:N.outputIndex,delta:K.delta});continue}if(j==="response.completed"&&!m){let Qe=At(D.response),vt=dt(s,L.size+Qe.length,T);if(vt){Y=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ut(o,vt)}};break}if(yield*E(),yield*P("completed"),yield*H("completed"),L.size===0)for(let re of Qe){let xe=_++,Ze=re.id??re.call_id??`fc_${xe}`,Zr=re.arguments??"",Ks={id:Ze,type:"function_call",call_id:re.call_id??Ze,name:re.name??""};yield{type:"response.output_item.added",output_index:xe,item:{...Ks,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:Ze,output_index:xe,delta:Zr},yield{type:"response.function_call_arguments.done",item_id:Ze,output_index:xe,arguments:Zr};let zs={...Ks,arguments:Zr,status:"completed"};yield{type:"response.output_item.done",output_index:xe,item:zs},b(xe,zs)}let Q=oc(v,D.response);yield Q.length>0?c({...D,response:{...D.response,output:Q}}):c(D);continue}yield c(D)}if(yield*E(),yield*P("incomplete"),yield*H("incomplete"),i&&!Y){let D=Me(d);l.remember(r,n,vo(D,Ot(d,D)),a)}}var Se=class extends Error{status=500;constructor(e){super(e),this.name="LaneTargetError"}},ue=class extends Error{pool;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=e}};var ct=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}};var Je=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)}},hn=class extends Je{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},So=class extends Je{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")}},Ae=class extends Error{lastDemandAgeMs;constructor(e){super("no capacity available for this model right now, retry shortly"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},Xn=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 hn;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 hn;let s=this.slots.some(c=>c.state==="queued"),i=!this.slots.some(c=>c.state==="attached"),a=this.slots.some(c=>c.dead&&!c.opening);if(!s&&(i||a)&&this.slots.length<this.opts.max){this.openForDemand();continue}let l=r+n-Date.now();if(l<=0)throw new So(n,this.slots.some(c=>c.state==="queued"));let u,d={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(c=>{d.resolve=c,this.waiters.push(d)}),new Promise(c=>{u=setTimeout(c,l)})])}finally{clearTimeout(u);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 hn}}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 a=r.entry;try{return await i.call(s,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&n--;continue}}return!1}tryLease(){let e=null;for(let s of this.slots)s.state!=="attached"||s.inFlight>=this.opts.inFlightCap||(!e||s.inFlight<e.inFlight)&&(e=s);if(!e)return null;let n=e.entry;if(n===null)return null;let r=e;r.inFlight+=1;let o=!1;return{slot:r.slot,entry:n,release:()=>{o||(o=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let n=this.slots.find(r=>r.entry===e);n&&(n.entry=null,n.state="paused",n.opening=null,this.opts.onDetach?.(n.slot,"runtime detached"),this.signalDrain())}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 ko=require("@urun-sh/core"),Ie=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)}},Ro=33e4;function na(t,e=Ro){return(async function*(){let r=t[Symbol.asyncIterator]();for(;;){let o,s=new Promise((u,d)=>{o=d}),i=setTimeout(()=>o(new Qn),e),a;try{a=await Promise.race([r.next(),s])}catch(u){throw u instanceof q||u instanceof ko.SessionFailedError&&u.kind==="transport-failed"?u:u instanceof Qn?(await r.return?.(void 0),new Ie("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 Ie("upstream_threw",`decision stream failed: ${String(u instanceof Error?u.message:u)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let l=a.value;if(typeof l=="object"&&l!==null&&"type"in l&&l.type==="error")throw new Ie("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield l}})()}var Qn=class extends Error{constructor(){super("stream idle timeout")}};function ra(t){return t instanceof Ie?!1:t instanceof q?!0:t instanceof ko.SessionFailedError?t.kind==="transport-failed":!1}var lc=[/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 Oe(t){return!lc.some(e=>e.test(t))}function Te(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 we(t,e){if(t instanceof q)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=oa(t);return n||{message:Te(e?.inferenceId??null),redacted:!0}}function oa(t){return t instanceof je?{message:"the model listing is temporarily unavailable \u2014 please retry shortly",redacted:!0}:t instanceof Z?{message:"this request cannot be completed right now due to a platform configuration problem \u2014 please retry shortly",redacted:!0}:t instanceof W?{message:t.message,redacted:!1}:t instanceof Se?{message:t.message,redacted:!1}:t instanceof Je?{message:t.message,redacted:!1}:t instanceof Ie?Oe(t.message)?{message:t.message,redacted:!1}:null:t instanceof Ae?{message:t.message,redacted:!1}:t instanceof ue?{message:t.message,redacted:!1}:null}function Pt(t,e,n){let r=n??(i=>console.error(i)),o=oa(e);if(o)return o.redacted&&r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${ke(e)}`),`the ${t} upstream failed: ${o.message}`;let s=e instanceof Error?e.message:"";return e instanceof Error&&s.length>0&&Oe(s)?`the ${t} upstream failed: ${s}`:(r(`[caller-message-boundary] ${t} upstream failure detail withheld from the caller: ${ke(e)}`),`the ${t} upstream failed while serving this request`)}function Ne(t){let e=t?.message;return typeof e=="string"&&e.length>0&&Oe(e)?e:null}function ke(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var Ao="/v1/responses",uc=64*1024*1024,dc=8*1024*1024,cc=16,sa=32,ia=3600*1e3,pc=/^[A-Za-z0-9._-]{1,256}$/;function ge(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var fc=ge(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 Io(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function mc(t){for(;t.bufferedAmount>dc&&t.readyState===Ve.WebSocket.OPEN;){let{promise:e,resolve:n}=Io();setTimeout(n,5),await e}}var Eo=class extends xt{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 lt))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)}},xo=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 Eo(mn(n)),e.on("message",(a,l)=>this.onMessage(a,l)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ia/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ia).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(ge(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(ge(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(ge(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(ge(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(ge(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(ge(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"||!pc.test(o.stream_id)){this.sendFrame(fc);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=sa){this.sendFrame(ge(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${sa}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",l=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,l.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=it();try{let o=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",o,o);let s;try{s=await gn({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:fn(r)})}catch(a){this.failTurn(a,n,e,r);return}this.laneOfResponse.set(s.responseId,n??null);let i=s.events;this.activeTurns.add(i);try{for await(let a of i){if(this.closed||this.ws.readyState!==Ve.WebSocket.OPEN)break;if(a.type==="error"){this.sendFrame(this.upstreamErrorFrameOf(a,n,r));break}this.send(a,n),await mc(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=it(),o=fn(r);try{let s=Tt(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:ke(e);if(e instanceof be)return ge(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof W)return ge(404,{type:"invalid_request_error",code:"model_not_found",message:o},n);if(e instanceof q){let a=we(e,{inferenceId:r});return a.redacted&&this.operatorLog(`[caller-message-boundary] WS /v1/responses turn failed (inference id ${r??"none"}); raw error withheld from the caller: ${o}`),ge(503,{type:"upstream_error",code:"session_gone",message:a.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}`),ge(s.status,{type:s.openaiType,message:o},n);let i=we(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}`),ge(500,{type:"upstream_error",message:i.message},n)}upstreamErrorFrameOf(e,n,r){let o=e.error,s=o?.type??"upstream_error",i=Ne(o),a=i??Te(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)}`),ge(s==="invalid_request_error"?400:502,{type:s,...o&&typeof o.code=="string"?{code:o.code}:{},message:a},n)}async acquire(){for(;this.active>=cc;){let{promise:e,resolve:n}=Io();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!==Ve.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!==Ve.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function Zn(t,e,n){let r=e===401?"Unauthorized":e===402?"Payment Required":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
13
13
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
14
14
|
Connection: close\r
|
|
15
15
|
Content-Type: text/plain; charset=utf-8\r
|
|
16
16
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
17
17
|
\r
|
|
18
|
-
${o}`)}function Io(t,e){let n=new Je.WebSocketServer({noServer:!0,maxPayload:lc}),r=new ot,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Qn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==xo){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Qn(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(R){let v=e.statusOf?.(R)??null;Qn(c,v?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,R=>{s.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new Eo(R,_,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Qn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=Ao();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==Je.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}var Mo=require("@urun-sh/core");var ia=require("@urun-sh/core"),mc={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},gc={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 yn(t,e){let n=gc[t.code];return e?`${n} (${e})`:n}function Zn(t){if(t==null)return null;let e=mc[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 er(t){if(t.kind==="create-failed")return Zn(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=ia.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Zn(e?"cold_start_exceeded":"queue_timeout")}var hc=fe(require("os"),1),yc=fe(require("path"),1),wc=require("url"),_c=require("util");function aa(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 tr(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}var vc=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function bc(t){let e=t?.code;return typeof e=="string"&&vc.has(e)}function Ve(t,e){try{return t.write(e),!0}catch(n){if(bc(n))return!1;throw n}}var vn=require("ws");var pa=require("@urun-sh/core");var ua=require("crypto");function M(t){return`${t}_${(0,ua.randomUUID)().replace(/-/g,"").slice(0,24)}`}var nr=4*1024*1024,Oo=8*1024*1024,rr=512,or=20*1024*1024;function ee(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function lt(t,e){return{type:"server_error",code:t,message:e}}function z(t){return{type:"error",event_id:M("event"),error:t}}function To(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var U=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Sc={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},kc={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Rc={format:!0,voice:!0,speed:!0};function Ec(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function Ot(t,e){if(!Array.isArray(t)||t.length===0)throw new U(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new U(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function la(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new U(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var xc=10;function Po(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:xc})}function wn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new U("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in Sc));if(s.length>0)throw new U(`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 a=Ot(o.modalities,"modalities"),l=Ot(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new U("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[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new U(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new U(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new U('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=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new U(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=Ot(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new U('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!Ec(l))throw new U(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new U("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new U("instructions must be a string or null","instructions");i.instructions=Po(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new U("voice must be a string or null","voice");if(!n.voice)throw new U("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new U(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new U("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new U(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new U("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new U("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new U("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new U("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new U(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new U(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new U(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new U("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(!l||typeof l!="object"||Array.isArray(l))throw new U("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new U(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new U(`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(l!==null)throw new U("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new U("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new U("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in kc))throw new U(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&la(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=wn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=wn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new U("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new U("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Rc))throw new U(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&la(d.format,"audio.output.format"),d.speed!==void 0)throw new U("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 U("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new U("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 sr(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 Co(t,e){let n=t;if(!n||typeof n!="object")throw new U("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 U("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:M("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 U('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new U("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 U("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 U(`${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 U("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 U("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 U("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new U("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new U("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 l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new U(`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:M("item"),type:"message",role:r,content:o}}throw new U(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function ir(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 Ac=1001,Ic=1011,Oc=15e3;var ar=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},da=t=>t.slice(0,120),Tc=/^[A-Za-z0-9+/=]*$/,Pc=2;function Cc(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Pc)return!1;return!0}var _n=class{id=M("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=To();sessionId=M("sess");conversationId=M("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??Oc,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:M("event"),session:sr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:M("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 q&&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(z(lt("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:M("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:M("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:M("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:M("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:M("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:M("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:M("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:M("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=M("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:M("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:M("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:M("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:M("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ee("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>nr){this.fail(ee("frame_too_large",`frame exceeds the ${nr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ee("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ee("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(z({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(lt(null,this.callerLine(o,"event handler")),"handler_fault")}}async handle(e){switch(e.type){case"session.update":{let n=wn(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(z(ee("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:M("event"),session:sr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=Co(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.forwardImageFrames(n),this.send({type:"conversation.item.added",event_id:M("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(z(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:M("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(z(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:M("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(z(ee("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:M("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(z(ee("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Tc.test(e.audio)){this.send(z(ee("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>or){this.send(z(ee("buffer_full",`uncommitted input audio exceeds the ${or}-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:M("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send(z(ee("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=M("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:M("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:M("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:M("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:M("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(z(ee("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(z(ee("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(z(ee("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(z(ee("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new Error("voice binding already owned by another connection \u2014 the resolver handed one audio bridge to two realtime conversations, which must never happen (independent callers require private bindings)");n.add(e),this.audioLaneOwner=!0}releaseVoiceBinding(){let e=this.binding.audioSession;!e||!this.audioLaneOwner||(e.openaiRealtimeClaims?.delete(e),this.audioLaneOwner=!1)}warnAudioOnlyTranscriptGap(){this.audioOnlyTranscriptGapWarned||(this.audioOnlyTranscriptGapWarned=!0,this.send(z({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((a,l)=>{s=setTimeout(()=>l(new ar),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,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(z(ee("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?Ot(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?Ot(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 U("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(z(ee("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=M("req"),a=`resp_${i}`;this.activeResponseId=a;let l=this.binding.composite===!0,u=l?0:this.items.length,d=l?null:ir(this.items),c=Po(typeof n.instructions=="string"?n.instructions:this.config.instructions),f=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,m=h==="inf"||h===void 0?void 0:h,_=n.tools!==void 0?n.tools:this.config.tools,R=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,v={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...f!==void 0?{temperature:f}:{},...m!==void 0?{max_output_tokens:m}:{},..._!==void 0?{tools:_}:{},...R!==void 0?{tool_choice:R}:{}};if(!(l&&!this.ensureVoice())){for(let{audio:b,captureWallMs:p}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(b,p);this.inFlight=(async()=>{let b=[],p=x=>{this.responseFlushed?this.send(x):b.push(x)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:M("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:M("event"),response:this.responseObject(a,"in_progress")});for(let x of b)this.send(x);b.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},S=null;try{if(l){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))return;u=this.items.length,d=ir(this.items)}let{input:x,sawAudioOnlyItem:E}=d??{input:[],sawAudioOnlyItem:!1},I={...v,input:x,...l?this.compositeTurnAsk(n):{}};E&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let k;try{k=await this.upstreamStream(I,i)}catch(O){this.upstreamTurnFault(O,a);return}try{for await(let O of this.stallBoundedTurn(k)){if(this.cancelled)break;let w=O;if(w.type==="error"){let A=this.upstreamErrorBody(w);this.responseFlushed?this.send(z(A)):this.send({type:"response.failed",event_id:M("event"),response:this.failedResponse(a,A)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){g(),y.messageOpen||(this.beginMessageItem(a,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&p({type:"response.output_text.delta",event_id:M("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,p({type:"response.output_audio_transcript.delta",event_id:M("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta})),y.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){g();let A=typeof w.delta=="string"?w.delta:"",P=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${a}_fc_${y.nextOutputIndex}`,T=y.tools.get(P);if(!T){let L=typeof w.name=="string"&&w.name.length>0?w.name:void 0;T={outputIndex:y.nextOutputIndex++,name:L,args:""},y.tools.set(P,T);let N={id:P,object:"realtime.item",type:"function_call",call_id:P,name:L??"",arguments:"",status:"in_progress"};p({type:"response.output_item.added",event_id:M("event"),response_id:a,output_index:T.outputIndex,item:N}),this.emitAssistantItemAdded(N)}typeof w.name=="string"&&w.name.length>0&&(T.name=w.name),T.args+=A,p({type:"response.function_call_arguments.delta",event_id:M("event"),item_id:P,response_id:a,output_index:T.outputIndex,call_id:P,name:T.name??"",delta:A});continue}if(w.type==="response.completed"){S=w.response??null;continue}}}catch(O){if(O instanceof ar)this.operatorLog(`[realtime] turn ${a} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(O,a);return}}if(this.cancelled)return;this.closeOpenItems(a,y,u),g(),this.send({type:"response.done",event_id:M("event"),response:this.doneResponse(a,u,S)})}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(Cc(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(z({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:M("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:M("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:M("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:M("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:M("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:M("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:M("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:M("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"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:M("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:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:M("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:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:M("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.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:M("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:M("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.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=Me(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??Te(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Oe(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: ${Ie(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(lt("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof pa.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=lt(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(z(r)):this.send({type:"response.failed",event_id:M("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(z(ee("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:M("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>rr&&(this.items.shift(),this.send(z({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${rr} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}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(z(ee("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>rn){this.send(z(ee("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${rn}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(z(ee("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(z(lt(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>Oo){this.ws.close(Ac,da("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=we(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${Ie(e)}`),r.message}fail(e,n){this.send(z(e)),this.ws.close(Ic,da(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=>ca(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),ca(this.id,e)}},Lo=[];function ca(t,e){Lo.push({id:t,reason:e}),Lo.length>256&&Lo.shift()}var bn="/v1/realtime",fa="urun.admission",ma=t=>t.slice(0,120);function Lc(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
|
|
18
|
+
${o}`)}function Oo(t,e){let n=new Ve.WebSocketServer({noServer:!0,maxPayload:uc}),r=new at,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,l=!1,u=(d,c,f)=>{let h;try{h=new URL(d.url??"/","http://localhost")}catch{Zn(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),h.pathname!==Ao){i.add(c);return}s.add(c);let m=!1;(async()=>{if(e.apiKey&&(d.headers.authorization??"")!==`Bearer ${e.apiKey}`){Zn(c,401,"invalid local proxy api key");return}let _;try{_=await a(d)}catch(R){let v=e.statusOf?.(R)??null;Zn(c,v?.status??500,"upstream resolver rejected the connection");return}l||c.destroyed||(m=!0,n.handleUpgrade(d,c,f,R=>{s.delete(c),o.add(R),R.on("close",()=>o.delete(R));try{new xo(R,_,r,e.statusOf,e.operatorLog??(v=>console.error(v)))}catch{o.delete(R),R.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!m&&!c.destroyed&&Zn(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",u),{stats:r,close:()=>{let{promise:d,resolve:c}=Io();if(l)return c(),d;l=!0,t.off("upgrade",u);for(let h of s)h.destroy();s.clear();for(let h of i)h.destroy();i.clear();for(let h of o)h.close(1001,"server shutting down");let f=setTimeout(()=>{for(let h of o)h.readyState!==Ve.WebSocket.CLOSED&&h.terminate()},2e3);return f.unref?.(),n.close(()=>{clearTimeout(f),c()}),d}}}var Uo=require("@urun-sh/core");var aa=require("@urun-sh/core"),gc={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},hc={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 yn(t,e){let n=hc[t.code];return e?`${n} (${e})`:n}function er(t){if(t==null)return null;let e=gc[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 tr(t){if(t.kind==="create-failed")return er(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=aa.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return er(e?"cold_start_exceeded":"queue_timeout")}var yc=fe(require("os"),1),wc=fe(require("path"),1),_c=require("url"),vc=require("util");function la(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 nr(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}var bc=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function Sc(t){let e=t?.code;return typeof e=="string"&&bc.has(e)}function Ke(t,e){try{return t.write(e),!0}catch(n){if(Sc(n))return!1;throw n}}var vn=require("ws");var fa=require("@urun-sh/core");var da=require("crypto");function M(t){return`${t}_${(0,da.randomUUID)().replace(/-/g,"").slice(0,24)}`}var rr=4*1024*1024,To=8*1024*1024,Po=512,or=20*1024*1024;function ee(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function ze(t,e){return{type:"server_error",code:t,message:e}}function z(t){return{type:"error",event_id:M("event"),error:t}}function Co(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var U=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},kc={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},Rc={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Ec={format:!0,voice:!0,speed:!0};function xc(t){return t==null?!0:Array.isArray(t)?t.length===0:typeof t=="object"?Object.values(t).every(e=>e==null):!1}function Ct(t,e){if(!Array.isArray(t)||t.length===0)throw new U(`${e} must be a non-empty array`,e,"invalid_modalities");let n=[];for(let r of t){if(r!=="text"&&r!=="audio")throw new U(`modality ${JSON.stringify(r)} is not "text" or "audio"`,e,"invalid_modalities");n.includes(r)||n.push(r)}return n}function ua(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new U(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}var Ac=10;function Lo(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:Ac})}function wn(t,e,n,r){if(!t||typeof t!="object"||Array.isArray(t))throw new U("session must be an object","session","invalid_request");let o=t,s=Object.keys(o).filter(a=>!(a in kc));if(s.length>0)throw new U(`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 a=Ct(o.modalities,"modalities"),l=Ct(o.output_modalities,"output_modalities");if(a.slice().sort().join(",")!==l.slice().sort().join(","))throw new U("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[a,l]of Object.entries(o))switch(a){case"type":{if(l!=="realtime"&&l!=="transcription")throw new U(`session.type ${JSON.stringify(l)} is not "realtime" or "transcription"`,"type");if(e.type!==void 0&&e.type!==l)throw new U(`session.type cannot change once established \u2014 this session is ${JSON.stringify(e.type)} and the update names ${JSON.stringify(l)}: 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(l==="transcription"&&!n.turns)throw new U('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=l;break}case"object":case"id":case"expires_at":{if(l===null)break;let u=a==="object"?"realtime.session":a==="id"?r:null;if(l!==u)throw new U(`session.${a} is server-set (echoed from session.created/session.updated) and cannot be changed: expected ${JSON.stringify(u)}, got ${JSON.stringify(l)}`,a,"unsupported_field");break}case"output_modalities":case"modalities":{let u=Ct(l,a);for(let d of u)if(d==="audio"&&!n.voice)throw new U('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',a,"audio_not_supported");i.outputModalities=u;break}case"tracing":case"prompt":case"include":case"reasoning":{if(!xc(l))throw new U(`session.${a} cannot be honoured by this backend: the resolved session has no ${a==="reasoning"?"reasoning-effort control":a} primitive`,a,"unsupported_field");break}case"model":if(l!==null&&typeof l!="string")throw new U("model must be a string or null","model");i.model=l??void 0;break;case"instructions":if(l!==null&&typeof l!="string")throw new U("instructions must be a string or null","instructions");i.instructions=Lo(l??void 0)??void 0;break;case"voice":if(l===null){delete i.voice;break}if(typeof l!="string")throw new U("voice must be a string or null","voice");if(!n.voice)throw new U("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");i.voice=l;break;case"input_audio_format":case"output_audio_format":if(l!=="pcm16")throw new U(`${a} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,a);break;case"temperature":if(l!==null&&(typeof l!="number"||!Number.isFinite(l)))throw new U("temperature must be a finite number or null","temperature");i.temperature=l??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(l!==null&&l!=="inf"&&(typeof l!="number"||!Number.isInteger(l)||l<1))throw new U(`${a} must be a positive integer, "inf" or null`,a);i.maxOutputTokens=l===null?void 0:l;break;case"tools":if(!Array.isArray(l))throw new U("tools must be an array","tools");i.tools=l;break;case"tool_choice":i.toolChoice=l;break;case"metadata":if(l!==null&&(!l||typeof l!="object"||Array.isArray(l)))throw new U("metadata must be an object or null","metadata");i.metadata=l??null;break;case"turn_detection":{if(l===null){i.turnDetection=null;break}if(!n.turns)throw new U("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new U("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new U(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");let c=d==="server_vad"?{threshold:.5,prefix_padding_ms:300,silence_duration_ms:500}:{eagerness:null};for(let[f,h]of Object.entries(u))if(!(f==="type"||f==="create_response"||f==="interrupt_response")){if(!(f in c))throw new U(`turn_detection.${f} cannot be honoured by this backend: the turn boundary comes from the engine's own semantic-VAD lane, which exposes no such knob`,`turn_detection.${f}`,"unsupported_field");if(h!=null&&h!==c[f])throw new U(`turn_detection.${f} cannot be tuned on this backend: the turn boundary comes from the engine's own semantic-VAD lane (got ${JSON.stringify(h)}, the lane's own tuning is fixed)`,`turn_detection.${f}`,"unsupported_field")}i.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(l===null){i.inputAudioTranscription=!1;break}if(!n.turns)throw new U("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(!l||typeof l!="object"||Array.isArray(l))throw new U("input_audio_transcription must be an object or null","input_audio_transcription");for(let d of Object.keys(l))if(!["model","language","languages","prompt"].includes(d))throw new U(`input_audio_transcription field not honored by this backend: ${d} (transcription comes from the voice engine itself)`,`input_audio_transcription.${d}`,"unsupported_field");let u=l.model;if(u!=null){let d=typeof u=="string"?u:JSON.stringify(u);if(typeof u!="string"||u!==n.model)throw new U(`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(l!==null)throw new U("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(l===null)break;let u=l;if(!u||typeof u!="object"||Array.isArray(u))throw new U("audio must be an object or null","audio");if(u.input!==void 0&&u.input!==null){let d=u.input;if(!d||typeof d!="object"||Array.isArray(d))throw new U("audio.input must be an object","audio.input");for(let c of Object.keys(d))if(!(c in Rc))throw new U(`audio.input field not supported by this backend: ${c}`,`audio.input.${c}`,"unsupported_field");if(d.format!==void 0&&ua(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let c=wn({input_audio_transcription:d.transcription},i,n,r);i.inputAudioTranscription=c.inputAudioTranscription}if(d.turn_detection!==void 0){let c=wn({turn_detection:d.turn_detection},i,n,r);i.turnDetection=c.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new U("audio.input.noise_reduction must be null on this backend: no noise-reduction primitive","audio.input.noise_reduction","unsupported_field")}if(u.output!==void 0&&u.output!==null){let d=u.output;if(!d||typeof d!="object"||Array.isArray(d))throw new U("audio.output must be an object","audio.output");for(let c of Object.keys(d))if(!(c in Ec))throw new U(`audio.output field not supported by this backend: ${c}`,`audio.output.${c}`,"unsupported_field");if(d.format!==void 0&&ua(d.format,"audio.output.format"),d.speed!==void 0)throw new U("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 U("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new U("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 sr(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 $o(t,e){let n=t;if(!n||typeof n!="object")throw new U("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 U("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:M("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 U('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new U("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 U("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 U(`${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 U("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 U("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 U("input_image content is only valid on user message items","item.content.type","invalid_request");let a=typeof i.image_url=="string"?i.image_url:i.image_url?.url;if(typeof a!="string"||a.length===0)throw new U("input_image part requires an image_url (string or { url })","item.content.image_url","invalid_request");if(!a.startsWith("data:image/"))throw new U("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 l=typeof i.detail=="string"?i.detail:void 0;o.push({type:"input_image",imageUrl:a,...l!==void 0?{detail:l}:{}});continue}throw new U(`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:M("item"),type:"message",role:r,content:o}}throw new U(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function ir(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 Ic=1001,Oc=1011,Tc=15e3;var ar=class extends Error{},lr=class extends Error{constructor(){super("the upstream turn stream stalled"),this.name="TurnStalledError"}},ca=t=>t.slice(0,120),Pc=/^[A-Za-z0-9+/=]*$/,Cc=2;function Lc(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>Cc)return!1;return!0}var _n=class{id=M("conn");ws;binding;onClosed;operatorLog;turnStallMs;config=Co();sessionId=M("sess");conversationId=M("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??Tc,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:M("event"),session:sr(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:M("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 q&&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(z(ze("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:M("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:M("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:M("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:M("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:M("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:M("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:M("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:M("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=M("item"),a=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:i,type:"message",role:"user",content:[{type:"input_audio",...s!==null?{transcript:s}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:M("event"),previous_item_id:a,item_id:i}),this.send({type:"conversation.item.added",event_id:M("event"),previous_item_id:a,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:M("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:M("event"),item_id:i,content_index:0,transcript:s}),this.emitItemDone(i),this.config.turnDetection?.createResponse&&!this.inFlight&&!this.isTranscriptionSession()&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(ee("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>rr){this.fail(ee("frame_too_large",`frame exceeds the ${rr}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(ee("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(ee("missing_type",'event is missing a string "type"'),"invalid_frame");return}try{await this.handle(r)}catch(o){let s=o;if(s&&typeof s=="object"&&s.name==="SessionUpdateError"){this.send(z({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}if(o instanceof ar){this.fail(ze(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}):
|
|
19
|
+
${o?.stack??ke(o)}`),this.send(z(ze(null,this.callerLine(o,"event handler"))))}}async handle(e){switch(e.type){case"session.update":{let n=wn(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(z(ee("turn_detection_refused","turn_detection is refused on this composite realtime lane \u2014 turn_detection: null (manual mode) is the only mode: the client's own VAD commits (input_audio_buffer.commit + response.create), and the stt leg's semantic-VAD boundaries are never a server-side commit","turn_detection")));return}this.config=n,this.send({type:"session.updated",event_id:M("event"),session:sr(this.config,this.sessionId)});return}case"conversation.item.create":{let n=$o(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:M("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(z(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.items.splice(n,1),this.send({type:"conversation.item.deleted",event_id:M("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(z(ee("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:M("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(z(ee("item_not_found",`no assistant message item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}n.truncated=!0,this.send({type:"conversation.item.truncated",event_id:M("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(z(ee("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Pc.test(e.audio)){this.send(z(ee("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=typeof e.capture_wall_ms=="number"&&Number.isInteger(e.capture_wall_ms)?e.capture_wall_ms:void 0,r=Buffer.byteLength(e.audio,"base64");if(this.config.type===void 0&&(this.config.type="realtime"),this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio,n);return}if(this.liveSttIn()){this.binding.audioSession.audio.appendInputAudio(e.audio,n),this.pendingAudioTotalBytes+=r;return}if(this.pendingAudioTotalBytes+r>or){this.send(z(ee("buffer_full",`uncommitted input audio exceeds the ${or}-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:M("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.lastCommittedTranscript===null){this.send(z(ee("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.liveSttIn()&&this.pendingTranscriptItemId!==null&&this.completePendingTranscription(this.pendingTranscriptItemId),this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=M("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:M("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.added",event_id:M("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:M("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:M("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(z(ee("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":if(this.isTranscriptionSession()){this.send(z(ee("unsupported","response.create is not supported on a transcription session \u2014 this session transcribes the streamed audio with the engine's own transcript lane and emits conversation.item.input_audio_transcription events; there are no model responses to create","response.create")));return}this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send(z(ee("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send(z(ee("audio_not_supported","audio events require a voice binding from the resolver \u2014 this session was resolved text-only","audio"))),!1):(this.voiceClaimed||(this.claimVoiceBinding(),this.audioUnsubscribe=this.binding.audioSession.audio.onOutputAudio(e=>{this.onOutputAudioFrame(this.activeResponseId??"",e)}),this.voiceClaimed=!0),!0)}claimVoiceBinding(){let e=this.binding.audioSession,n=e.openaiRealtimeClaims??(e.openaiRealtimeClaims=new Set);if(n.has(e))throw new ar("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(z({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((a,l)=>{s=setTimeout(()=>l(new lr),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,...a}=e;return await o.createResponse({...a,input:i})}throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send(z(ee("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{},r=n.modalities!==void 0?Ct(n.modalities,"response.modalities"):void 0,o=n.output_modalities!==void 0?Ct(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 U("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(z(ee("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1,this.messageItemOpenForAudio=!1,this.turnLastAnnouncedItemId=this.items.length>0?this.items[this.items.length-1].id:null;let i=M("req"),a=`resp_${i}`;this.activeResponseId=a;let l=this.binding.composite===!0,u=l?0:this.items.length,d=l?null:ir(this.items),c=Lo(typeof n.instructions=="string"?n.instructions:this.config.instructions),f=typeof n.temperature=="number"?n.temperature:this.config.temperature,h=n.max_output_tokens??this.config.maxOutputTokens,m=h==="inf"||h===void 0?void 0:h,_=n.tools!==void 0?n.tools:this.config.tools,R=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,v={stream:!0,...this.config.model?{model:this.config.model}:{},...c!==void 0?{instructions:c}:{},...f!==void 0?{temperature:f}:{},...m!==void 0?{max_output_tokens:m}:{},..._!==void 0?{tools:_}:{},...R!==void 0?{tool_choice:R}:{}};if(!(l&&!this.ensureVoice())){for(let{audio:b,captureWallMs:p}of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(b,p);this.inFlight=(async()=>{let b=[],p=x=>{this.responseFlushed?this.send(x):b.push(x)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:M("event"),response:this.responseObject(a,"in_progress")}),this.send({type:"response.in_progress",event_id:M("event"),response:this.responseObject(a,"in_progress")});for(let x of b)this.send(x);b.length=0,this.responseFlushed=!0}},y={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0,transcriptDelta:!1},S=null;try{if(l){if(this.pendingTranscriptItemId!==null&&(await new Promise(O=>{this.pendingTranscriptSettled=O}),this.cancelled||this.closed))return;u=this.items.length,d=ir(this.items)}let{input:x,sawAudioOnlyItem:E}=d??{input:[],sawAudioOnlyItem:!1},I={...v,input:x,...l?this.compositeTurnAsk(n):{}};E&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let k;try{k=await this.upstreamStream(I,i)}catch(O){this.upstreamTurnFault(O,a);return}try{for await(let O of this.stallBoundedTurn(k)){if(this.cancelled)break;let w=O;if(w.type==="error"){let A=this.upstreamErrorBody(w);this.responseFlushed?this.send(z(A)):this.send({type:"response.failed",event_id:M("event"),response:this.failedResponse(a,A)});return}if(w.type==="response.output_text.delta"&&typeof w.delta=="string"){g(),y.messageOpen||(this.beginMessageItem(a,y.nextOutputIndex++),y.messageOpen=!0),this.config.outputModalities.includes("text")&&p({type:"response.output_text.delta",event_id:M("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta}),this.turnOutputIsAudio()&&(y.transcriptDelta=!0,p({type:"response.output_audio_transcript.delta",event_id:M("event"),item_id:`${a}_msg_0`,response_id:a,output_index:0,content_index:0,delta:w.delta})),y.messageText+=w.delta;continue}if(w.type==="response.function_call_arguments.delta"){g();let A=typeof w.delta=="string"?w.delta:"",T=typeof w.call_id=="string"&&w.call_id.length>0?w.call_id:`${a}_fc_${y.nextOutputIndex}`,P=y.tools.get(T);if(!P){let L=typeof w.name=="string"&&w.name.length>0?w.name:void 0;P={outputIndex:y.nextOutputIndex++,name:L,args:""},y.tools.set(T,P);let N={id:T,object:"realtime.item",type:"function_call",call_id:T,name:L??"",arguments:"",status:"in_progress"};p({type:"response.output_item.added",event_id:M("event"),response_id:a,output_index:P.outputIndex,item:N}),this.emitAssistantItemAdded(N)}typeof w.name=="string"&&w.name.length>0&&(P.name=w.name),P.args+=A,p({type:"response.function_call_arguments.delta",event_id:M("event"),item_id:T,response_id:a,output_index:P.outputIndex,call_id:T,name:P.name??"",delta:A});continue}if(w.type==="response.completed"){S=w.response??null;continue}}}catch(O){if(O instanceof lr)this.operatorLog(`[realtime] turn ${a} received no upstream event for ${this.turnStallMs}ms \u2014 closing the stalled turn visibly`);else{this.upstreamTurnFault(O,a);return}}if(this.cancelled)return;this.closeOpenItems(a,y,u),g(),this.send({type:"response.done",event_id:M("event"),response:this.doneResponse(a,u,S)})}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(Lc(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send(z({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:M("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:M("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:M("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:M("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:M("event"),response_id:e,output_index:n,item:o}),this.emitAssistantItemAdded(o)}this.send({type:"response.content_part.added",event_id:M("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:M("event"),response_id:e,output_index:0,item:r}),this.emitAssistantItemAdded(r)}this.send({type:"response.content_part.added",event_id:M("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"),a=n.messageText;s?(this.send({type:"response.output_audio_transcript.done",event_id:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),this.send({type:"response.output_audio.done",event_id:M("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:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,transcript:a}),n.messageText.length>0&&i&&this.send({type:"response.output_text.done",event_id:M("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:M("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:a}:{type:"output_text",text:n.messageText}});let l=[];s&&l.push({type:"output_audio",transcript:a}),n.messageText.length>0&&l.push({type:"output_text",text:n.messageText});let u={id:o,type:"message",role:"assistant",content:l};this.pushItem(u),this.send({type:"response.output_item.done",event_id:M("event"),response_id:e,output_index:0,item:this.itemToProtocol(u)}),this.emitItemDone(u.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:M("event"),item_id:o,response_id:e,output_index:s.outputIndex,call_id:o,name:s.name??"",arguments:i});let a={id:o,type:"function_call",callId:o,name:s.name,arguments:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:M("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)}),this.emitItemDone(a.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=Ne(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??Te(null);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:o}}failSessionGone(e){let n=e instanceof Error&&Oe(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: ${ke(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(ze("session_gone",r),"session_gone")}upstreamTurnFault(e,n){if(e instanceof q){this.failSessionGone(e);return}if(!this.cancelled){if(!this.responseFlushed&&!(e instanceof fa.SessionFailedError&&(e.kind==="never-live"||e.kind==="create-failed"))){this.failSessionGone(e);return}this.emitUpstreamFault(e,n)}}emitUpstreamFault(e,n){let r=ze(null,this.callerLine(e,"upstream turn"));this.responseFlushed?this.send(z(r)):this.send({type:"response.failed",event_id:M("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send(z(ee("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0,this.binding.composite===!0&&this.binding.cancelActiveTurn?.();let n=this.pendingTranscriptSettled;this.pendingTranscriptSettled=null,n?.();let r=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:M("event"),response:this.responseObject(r,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Po&&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(z(ee("invalid_frame","input_image data URI carries no decodable bytes","item.content")));continue}if(o.byteLength>on){this.send(z(ee("frame_too_large",`input_image frame is ${o.byteLength} bytes \u2014 over the ${on}-byte data-channel budget; the frame is dropped, never truncated`,"item.content")));continue}if(!this.binding.video){this.send(z(ee("video_unsupported","no video frame lane is wired for this connection (the binding provides no video seam) \u2014 frames cannot be forwarded to the engine","item.content")));continue}this.videoLane??=this.binding.video().catch(s=>{throw this.videoLane=null,s}),this.videoLane.then(s=>s.sendInputFrame(new Uint8Array(o))).catch(s=>this.send(z(ze(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>To){this.ws.close(Ic,ca("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}callerLine(e,n){let r=we(e);return r.redacted&&this.operatorLog(`[caller-message-boundary] realtime ${n} (conn ${this.id}, session ${this.sessionId}) failed; raw error withheld from the caller: ${ke(e)}`),r.message}fail(e,n){this.send(z(e)),this.ws.close(Oc,ca(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=>pa(this.id,`binding release failed: ${o instanceof Error?o.message:String(o)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this,{reason:e}),pa(this.id,e)}},Mo=[];function pa(t,e){Mo.push({id:t,reason:e}),Mo.length>256&&Mo.shift()}var bn="/v1/realtime",ma="urun.admission",ga=t=>t.slice(0,120);function $c(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
|
|
19
20
|
Connection: close\r
|
|
20
21
|
Content-Type: text/plain\r
|
|
21
22
|
\r
|
|
22
|
-
${
|
|
23
|
-
`),t.destroy()}function
|
|
24
|
-
`}function
|
|
25
|
-
`)}}}),d({stage:"admit",conn:l,model:u
|
|
23
|
+
${ga(n)}\r
|
|
24
|
+
`),t.destroy()}function Mc(t){return`${JSON.stringify({event:"realtime_upgrade",ts:new Date().toISOString(),...t})}
|
|
25
|
+
`}function Nc(t){Ke(process.stdout,t)}function Uc(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function No(t){return t.audioSession?.audio.sessionId??void 0}function ur(t,e){let n=new vn.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==bn)return;r.add(s),s.on("close",()=>{r.delete(s)});let l=M("rtup"),u=Uc(o),d=k=>{(e.log??Nc)(Mc(k))};d({stage:"accept",conn:l,model:u}),s.resume();let c=new AbortController,f=null,h=k=>{f??=k,c.abort(new Error(f))},m=()=>h("client socket closed"),_=()=>h("client socket closed (half-close)"),R=k=>h(`client socket error: ${k.message}`);s.once("close",m),s.once("end",_),s.once("error",R);let v=()=>{s.removeListener("close",m),s.removeListener("end",_),s.removeListener("error",R)},b=k=>{d({stage:"close",conn:l,model:u,...k})},p=null,g=!1,y=null,S=k=>JSON.stringify({type:ma,event_id:M("event"),...k}),x=k=>{if(p!==null){p.readyState===vn.WebSocket.OPEN&&p.send(S(k));return}g||(g=!0,n.handleUpgrade(o,s,i,O=>{p=O,y=[],O.on("message",w=>{y?.push(String(w))}),d({stage:"waiting",conn:l,model:u,status:k.status}),O.send(S(k))}))},E=k=>{let O=k,w=O.session!=null&&typeof O.session.sendResponseCreate=="function",A=O.clients!=null&&typeof O.clients.createResponse=="function";if(!w&&!A)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((T,P)=>{let L=(N,V)=>{try{let H=Date.now();new _n({ws:N,binding:k,operatorLog:e.operatorLog,...V.length>0?{replayFrames:V}:{},onClosed:(Y,D)=>{b({while:"live",reason:D.reason});try{e.onSessionEnded?.({req:o,binding:k,connected_ms:Math.max(0,Date.now()-H),reason:D.reason})}catch(j){(e.operatorLog??console.error)(`realtime session ledger hook failed: ${j instanceof Error?j.message:String(j)}
|
|
26
|
+
`)}}}),d({stage:"admit",conn:l,model:u,...No(k)===void 0?{}:{session:No(k)}}),T()}catch(H){P(H)}};if(p!==null){let N=y??[];y=null,L(p,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 k=>{if(c.signal.aborted){v();let O=No(k);try{await k.release?.()}catch(w){b({while:"queued",...O===void 0?{}:{session:O},reason:f??"client socket closed",release_failed:w instanceof Error?w.message:String(w)});return}b({while:"queued",...O===void 0?{}:{session:O},reason:f??"client socket closed",released:!0}),s.destroy();return}v(),await E(k)}).catch(k=>{let O=k instanceof Uo.SessionFailedError?tr(k):null,w=null;if(k!==null&&typeof k=="object"&&"status"in k){let L=k.status;typeof L=="number"&&(w=L)}let A=w??O?.status??502,T=k instanceof Error?k.message:String(k),P=w!==null?T:O!==null?yn(O,k instanceof Uo.SessionFailedError&&k.status.sessionId?`session ${k.status.sessionId}`:void 0):we(k).message;if(b({while:"queued",...c.signal.aborted?{reason:f??"client socket closed"}:{reason:T,status:A}}),p!==null&&!c.signal.aborted){let L=JSON.stringify({type:ma,event_id:M("event"),status:A<500?"rejected":"failed",reason:P});p.readyState===vn.WebSocket.OPEN&&p.send(L),p.close(1011,ga(P));return}s.destroyed||$c(s,A,P)}).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 Pe=require("crypto"),va=require("dns/promises");var ha="/realtime/openai.quic-relay";async function ya(t){let e=await fetch(`${t.sfuBase}${ha}${t.query}`,{method:"POST",headers:{"content-type":"application/json",authorization:t.upstreamHeaders.authorization??""},body:"{}"});if(e.status!==201){let s=await e.text().catch(()=>"");throw new Error(`quic relay ${t.sfuBase}${ha} -> ${e.status} ${s}`)}let n=await e.json(),r=new URL(t.sfuBase).host,o=n.url??`https://${r}:${n.wtPort??4443}/wt`;return{status:201,body:{callId:n.callId,url:o,token:n.token,certHashes:n.certHashes},location:`/v1/realtime/calls/${n.callId}`}}var Do="/v1/realtime/calls",wa="/v1/realtime/client_secrets",Dc="session-server-ts-pods.urun.svc.cluster.local",_a=8081,Fc="/realtime/openai.relay",Bc=262144,Hc=600;function ba(t){let e=t.secret===void 0?void 0:Buffer.from((0,Pe.hkdfSync)("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>Jc(await(0,va.resolve4)(Dc))),r=(o,s,i,a)=>{o.writeHead(s,{"content-type":"application/json"}),o.end(JSON.stringify({error:{message:i,type:"invalid_request_error",...a?{code:a}:{}}}))};return async(o,s)=>{let i=new URL(o.url??"/","http://proxy");if(o.method!=="POST"||i.pathname!==Do&&i.pathname!==wa)return!1;let a=await qc(o);if(a===null)return r(s,413,"request body too large"),!0;let l=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");if(l.startsWith("ek_")){let v=e===void 0?null:Wc(e,l.slice(3));if(v===null)return r(s,401,"invalid or expired client secret","invalid_api_key"),!0;o.headers.authorization=`Bearer ${v}`}try{await t.authorize(o)}catch(v){let b=typeof v=="object"&&v!==null&&"status"in v&&typeof v.status=="number"?v.status:401;return r(s,b,v instanceof Error?v.message:String(v)),!0}if(i.pathname===wa){if(e===void 0)return r(s,501,"client secrets are not configured on this proxy"),!0;let v=a.length===0?{}:JSON.parse(a.toString("utf8")),b=typeof v=="object"&&v!==null&&"session"in v?v.session:null,p=Math.floor(Date.now()/1e3)+Hc,g=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");return s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({value:`ek_${Gc(e,g,p)}`,expires_at:p,session:b})),!0}if(i.searchParams.get("transport")==="quic"){let v=i.searchParams.get("model");if(v===null)return r(s,400,"model is required (?model=)"),!0;let b=`quic_${(0,Pe.randomUUID)().replaceAll("-","")}`,p=new URLSearchParams(i.searchParams);p.set("model",v),p.set("call_id",b);let g="no media edge resolved";for(let y of await n())try{let S=await ya({sfuBase:`http://${y}:${_a}`,query:`?${p}`,upstreamHeaders:{authorization:o.headers.authorization??""}});return s.writeHead(201,{"content-type":"application/json",location:`${Do}/${S.body.callId}`}),s.end(JSON.stringify(S.body)),!0}catch(S){g=`${y}: ${String(S)}`}return r(s,502,`no media edge accepted the quic call (${g})`),!0}let{sdp:u,session:d}=await jc(o.headers["content-type"]??"",a);if(u===void 0)return r(s,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)"),!0;let c=typeof d=="object"&&d!==null&&"model"in d&&typeof d.model=="string"?d.model:void 0,f=i.searchParams.get("model")??c;if(f===void 0)return r(s,400,"model is required (?model= or session.model)"),!0;let h=`rtc_${(0,Pe.randomUUID)().replaceAll("-","")}`,m=new URLSearchParams(i.searchParams);m.set("model",f),m.set("call_id",h);let _=JSON.stringify({sdp:u,...d!==void 0?{session:d}:{}}),R="no media edge resolved";for(let v of await n()){let b;try{b=await fetch(`http://${v}:${_a}${Fc}?${m}`,{method:"POST",headers:{"content-type":"application/json",authorization:o.headers.authorization??""},body:_,signal:AbortSignal.timeout(1e4)})}catch(g){R=`${v}: ${String(g)}`;continue}let p=await b.text();if(b.status===201)return s.writeHead(201,{"content-type":"application/sdp",location:`${Do}/${h}`}),s.end(p),!0;if(b.status>=500||b.status===404||b.status===405||b.status===501){R=`${v}: ${b.status} ${p}`;continue}return r(s,b.status,p),!0}return r(s,503,`no media edge answered the offer (${R})`,"media_edge_unavailable"),!0}}async function jc(t,e){if(t.startsWith("application/sdp"))return{sdp:e.toString("utf8")};if(!t.startsWith("multipart/form-data"))return{};let n=await new Response(new Uint8Array(e),{headers:{"content-type":t}}).formData(),r=n.get("sdp"),o=n.get("session");return{...typeof r=="string"?{sdp:r}:{},...typeof o=="string"?{session:JSON.parse(o)}:{}}}async function qc(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>Bc)return null;e.push(r)}return Buffer.concat(e)}function Gc(t,e,n){let r=(0,Pe.randomBytes)(12),o=(0,Pe.createCipheriv)("aes-256-gcm",t,r),s=Buffer.concat([o.update(JSON.stringify({b:e,e:n}),"utf8"),o.final()]);return Buffer.concat([r,o.getAuthTag(),s]).toString("base64url")}function Wc(t,e){try{let n=Buffer.from(e,"base64url"),r=(0,Pe.createDecipheriv)("aes-256-gcm",t,n.subarray(0,12));r.setAuthTag(n.subarray(12,28));let o=JSON.parse(Buffer.concat([r.update(n.subarray(28)),r.final()]).toString("utf8"));if(typeof o!="object"||o===null||!("b"in o)||!("e"in o))return null;let{b:s,e:i}=o;return typeof s!="string"||typeof i!="number"?null:i>Date.now()/1e3?s:null}catch{return null}}function Jc(t){for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}var Tl=require("crypto");var ef=require("http");var F=class extends Error{},Re=class extends Error{};function de(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dr(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Lt(t,e){if(t!=null)throw new F(`${e} is not supported on the /v1/decisions lane \u2014 the sense wire carries no translation for it (remove it or pass null)`)}function Fo(t){let e=dr(t);return e!==null&&e<=1?e:null}function Sa(t,e){if(!de(t))throw new F("decisions requires a JSON object body");Lt(t.prompt_cache_key,"prompt_cache_key"),Lt(t.prompt_cache_options,"prompt_cache_options"),Lt(t.safety_identifier,"safety_identifier");let n=[],r=Vc(t.input,n),o=t.questions;if(!Array.isArray(o)||o.length<1||o.length>400)throw new F("decisions requires a questions array of 1 to 400 questions");let s={},i=[],a=new Set;for(let u=0;u<o.length;u++){let{entry:d,spec:c}=Xc(o[u],u,o.length,n);if(a.has(c.key))throw new F(`duplicate question name "${c.key}" \u2014 the systemone questions object is keyed by name, so a duplicate would silently drop one answer`);a.add(c.key),s[c.key]=d,i.push(c)}let l={model:e,state:r,questions:s};return n.length>0&&(l.media=n),{systemone:l,specs:i}}function Vc(t,e){if(typeof t=="string")return t;if(!de(t)&&!Array.isArray(t))throw new F("decisions input must be a string or an array of messages");let n=Array.isArray(t)?t:[t],r=[];for(let o of n)zc(o,r,e);return Kc(r)}function Kc(t){return t.length===0?"":t.some(e=>e.role!==void 0)?t:t.flatMap(e=>"text"in e?[e.text]:[]).join(`
|
|
26
27
|
|
|
27
|
-
`)}function
|
|
28
|
+
`)}function zc(t,e,n){if(!de(t))throw new F("decisions input items must be JSON objects");let r=t.role,o=t.type;if(r==="user"||r==="developer"||r==="system"||r==="assistant"){Yc(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)){ka(s,e,n,void 0,!1);return}throw new F(`${o} output must be a string or an array of parts`)}default:throw new F(`unsupported decisions input item (role ${JSON.stringify(r??null)}, type ${JSON.stringify(o??null)})`)}}function Yc(t,e,n,r){e==="assistant"&&Lt(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 F(`decisions ${e} message content must be a string or an array of parts`);if(e==="assistant"){for(let s of o){if(!de(s))throw new F("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 F(`unsupported decisions assistant message part type ${JSON.stringify(s.type??null)}`)}return}ka(o,n,r,e)}function ka(t,e,n,r,o=!0){for(let s of t){if(!de(s))throw new F("decisions content parts must be JSON objects");switch(Lt(s.prompt_cache_breakpoint,"prompt_cache_breakpoint"),s.type){case"input_text":{if(typeof s.text!="string")throw new F("input_text requires a string text");e.push({role:r,text:s.text});break}case"input_json":{if(!o)throw new F("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(!de(i)&&!(Array.isArray(i)&&i.every(de)))throw new F("input_json data must be an object or an array of objects");e.push({role:r,json:i});break}case"input_image":{n.push(Ra(s));break}default:throw new F(`unsupported decisions content part type ${JSON.stringify(s.type??null)}`)}}}function Ra(t){let e=t.image_url;if(typeof e!="string"||e==="")throw new F("input_image requires a string image_url");let n=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(n===null)throw new F("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 F("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 F("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 F("input_image detail must be low, high, auto, or original");let a={type:"image",mime:r,data:o};return(i==="low"||i==="high")&&(a.detail=i),a}function Xc(t,e,n,r){if(!de(t))throw new F(`questions[${e}] must be a JSON object`);let o=t.type;if(o!=="predicate"&&o!=="choice"&&o!=="score")throw new F(`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 F(`questions[${e}] name must be a string`);let i=s??null,a=i??`q${e}`,l=Qc(t.instructions,e,n,r);switch(o){case"predicate":return{entry:{kind:"noul",prompt:l,criteria:{true:"the condition is true",false:"the condition is not true"}},spec:{type:o,key:a,name:i}};case"choice":{let u=t.choices;if(!Array.isArray(u)||u.length<2||u.length>255)throw new F(`questions[${e}] (choice) requires a choices array of 2 to 255 options`);let d=[],c=new Set,f=[];for(let _ of u){if(!de(_))throw new F(`questions[${e}] choices must be JSON objects`);let R=_.value;if(typeof R!="string"&&typeof R!="boolean")throw new F(`questions[${e}] choice value must be a string or boolean`);let v=String(R);if(c.has(v))throw new F(`questions[${e}] has duplicate choice value ${JSON.stringify(v)} (choices must be unique)`);c.add(v);let b=_.description;if(b!==void 0&&typeof b!="string")throw new F(`questions[${e}] choice description must be a string`);d.push(R),f.push(b)}let h=u.map((_,R)=>({name:String(d[R]),description:f[R]??String(d[R])}));return{entry:{kind:"choice",prompt:l,options:h},spec:{type:o,key:a,name:i,choiceValues:d}}}case"score":{let u=t.levels;if(!Array.isArray(u)||u.length<2||u.length>10)throw new F(`questions[${e}] (score) requires a levels array of 2 to 10 ordered levels`);let d=[],c=[];for(let h of u){if(!de(h)||typeof h.label!="string")throw new F(`questions[${e}] score levels must carry a string label`);if(d.includes(h.label))throw new F(`questions[${e}] has duplicate level label ${JSON.stringify(h.label)}`);d.push(h.label);let m=h.description;if(m!==void 0&&typeof m!="string")throw new F(`questions[${e}] score level description must be a string`);let _=m!==void 0?`${h.label}: ${m}`:h.label;if(c.includes(_))throw new F(`questions[${e}] has duplicate score criterion ${JSON.stringify(_)} \u2014 two levels fuse to one criterion on the wire, so one sense criterion would answer both`);c.push(_)}return{entry:{kind:"score",prompt:l,criteria:c},spec:{type:o,key:a,name:i,levelLabels:d}}}}}function Qc(t,e,n,r){if(typeof t=="string")return t;if(!Array.isArray(t))throw new F(`questions[${e}] instructions must be a string or an array of input parts`);let o=[];for(let s of t){if(!de(s))throw new F(`questions[${e}] instruction parts must be JSON objects`);switch(Lt(s.prompt_cache_breakpoint,`questions[${e}] prompt_cache_breakpoint`),s.type){case"input_text":{if(typeof s.text!="string")throw new F(`questions[${e}] input_text requires a string text`);o.push(s.text);break}case"input_image":{if(n>1)throw new F(`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(Ra(s));break}case"input_json":{let i=s.data;if(!de(i)&&!(Array.isArray(i)&&i.every(de)))throw new F(`questions[${e}] input_json data must be an object or an array of objects`);o.push(JSON.stringify(i));break}default:throw new F(`unsupported decisions instruction part type ${JSON.stringify(s.type??null)}`)}}return o.join(`
|
|
28
29
|
|
|
29
|
-
`)}function Ra(t,e){if(!de(e))throw new ke("decision answer was not a JSON object");let n=e.answers;if(!de(n))throw new ke("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!de(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=de(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=Uo(s.noul);if(a===null)throw new ke(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],l=s.choice;if(typeof l!="string")throw new ke(`the choice answer for "${o.key}" carries no string choice`);let u=a.findIndex(f=>String(f)===l);if(u===-1)throw new ke(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(l)})`);let d=ur(s.confidence);if(d===null)throw new ke(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let f of a){let h=Uo(i[String(f)]);h!==null&&c.push({value:f,probability:h})}r.push({type:"choice",name:o.name,choice:a[u],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],l=ur(s.score);if(l===null)throw new ke(`the score answer for "${o.key}" carries no numeric score to translate`);let u=ur(s.confidence);if(u===null)throw new ke(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let f=Uo(i[String(c)]);f!==null&&d.push({value:c,label:a[c],probability:f})}r.push({type:"score",name:o.name,score:l,confidence:u,probabilities:d});continue}}}return r}var ce=class extends Error{};async function dr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ce(`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 ce(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function cr(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new ce(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[u,d]of Object.entries(t.headers))if(typeof d=="string")i.set(u,d);else if(Array.isArray(d))for(let c of d)i.append(u,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof ce?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var Ea="/v1/images/generations",pr="/v1/images/edits";function xa(t){return t===Ea||t===pr}var Aa="/v1/images/models";async function Ia(t,e,n){if(t){if(t.model=me({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var G=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Qc=16*1024*1024,Oa=64*1024*1024;function Ta(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 Sn(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 Pa(t,e,n,r,o,s){let i=s??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),l=null;for await(let m of a){if(m.type==="error"){let _=m.error??{},R=typeof _.message=="string"&&_.message.length>0&&Oe(_.message)?_.message:null;throw R===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new G(502,"the image upstream failed while serving this request")):new G(502,`image upstream error: ${R}`)}if(m.type==="response.completed"){l=m.response??null;break}}if(l===null)throw new G(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=De(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new G(502,`image upstream returned ${Array.isArray(u)?u.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=u[0].startsWith("data:")?u[0].slice(u[0].indexOf(";base64,")+8):u[0],f=Buffer.from(c,"base64");if(Ta(f)===null)throw new G(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${f.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function Ca(t,e){if(t instanceof G)return t;if(t instanceof Se)throw t;return t instanceof W?new G(404,t.message):new G(502,It("image",t,e))}async function La(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 Sn(r,new G(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function $a(t,e){t&&(t.outputUnits=e.images.length)}function Ma(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 Zc={model:!0,prompt:!0,response_format:!0,n:!0};async function Na(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Oa;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${Ea}`);let s;try{s=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof ce?new G(413,f.message):new G(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new G(400,"request body must be a JSON object");let i=s;for(let f of Object.keys(i))if(!Zc[f])throw new G(400,`request field "${f}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,f);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new G(400,"prompt is required and must be a non-empty string","prompt");let l=i.model===void 0?void 0:i.model;if(l!==void 0&&typeof l!="string")throw new G(400,"model must be a string","model");await Ia(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new G(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new G(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await La(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let f=await Pa(n.clients,l,c,n.turn?ve(n.turn):void 0,n.turn,r);$a(n.turn,f),Ma(e,f)}catch(f){throw Ca(f,r)}}catch(s){if(s instanceof ce){Sn(e,new G(413,s.message));return}if(s instanceof G){Sn(e,s);return}throw s}}var ep={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ua(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Oa,s=n.maxImagePartBytes??Qc;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${pr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new G(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(m){throw m instanceof ce?new G(413,m.message):new G(400,String(m instanceof Error?m.message:m))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new G(400,"prompt is required and must be a non-empty string field","prompt");let u=a.get("model");if(u!==null&&typeof u!="string")throw new G(400,"model must be a string field","model");let d=u===null?void 0:u;await Ia(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new G(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let m of a.keys())if(!ep[m])throw new G(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let f=[];for(let m of["image","image[]"])for(let _ of a.getAll(m)){if(!(_ instanceof File))throw new G(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(_.size>s)throw new G(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let R=new Uint8Array(await _.arrayBuffer()),v=Ta(R);if(v===null)throw new G(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);f.push({bytes:R,mime:v})}if(f.length===0)throw new G(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await La(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:l}];for(let{bytes:m,mime:_}of f)h.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Pa(n.clients,d,h,n.turn?ve(n.turn):void 0,n.turn,r);$a(n.turn,m),Ma(e,m)}catch(m){throw Ca(m,r)}}catch(i){if(i instanceof ce){Sn(e,new G(413,i.message));return}if(i instanceof G){Sn(e,i);return}throw i}}var kn="/v1/audio/speech";function Ja(t){return t===kn}var Da=4096,Fa=18e4,Ba=5e3,tp=64*1024*1024,Ha=8,ja=5,qa=1024*1024,Pt="voice_applied",mr="X-Urun-Voice-Applied",B=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Do(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 gr=class extends B{constructor(e){super(502,e)}};function Va(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 Ka(t){return new B(502,`the runtime's ${Pt} receipt ${JSON.stringify(t)} cannot be relayed as the ${mr} 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 np(t,e,n){if(t){if(t.model=me({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function za(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var rp=2;function op(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>rp)return!1;return!0}function sp(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 Ga=new WeakMap,fr=new WeakMap;function ip(t,e){let n=fr.get(t)??0;if(n>=Ha)throw new B(503,`this model's speech queue is full \u2014 ${Ha} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${ja}s`,void 0,ja);fr.set(t,n+1);let r=Ga.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Ga.set(t,s),(async()=>{await r;try{return await e()}finally{fr.set(t,(fr.get(t)??1)-1),o()}})()}async function ap(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new B(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 q))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 ut(t,e){if(t instanceof B)return t;if(t instanceof Se)throw t;return t instanceof W?new B(404,t.message):new B(502,It("speech",t,e))}async function Wa(t,e,n,r,o,s,i,a,l,u){let d=u??(f=>console.error(f)),c=a??(()=>{});return ip(e,async()=>{if(i?.()===!0)return null;let f=!1,h=!1,m=!1,_,R=new Promise(O=>{_=O}),v=[],b,p=!1,g=null,y=()=>{g!==null&&(clearTimeout(b),b=setTimeout(()=>{p=!0,g?.()},o.capMs))},S=()=>{h&&!m&&v.length>=o.quietRunFrames&&(m=!0,_())},x=e.onOutputAudio(O=>{let w=Buffer.from(O,"base64");if(w.byteLength===0)return;y();let A=op(w);if(!f){if(A)return;f=!0}if(A){v.push(w),S();return}for(let P of v)c(P);v.length=0,c(w),S()}),E=null,I,k;try{k=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let w=()=>(clearTimeout(I),new Promise(L=>{I=setTimeout(L,s.capMs)})),A=w(),P=!1;for(;;){let L=k.next(),N=await Promise.race([L,A]);if(N===void 0){P=!0,L.catch(()=>{});break}if(N.done)break;let V=N.value;if(A=w(),V.type==="error"){let H=V.error??{};await k.return?.();let Y=typeof H.message=="string"&&H.message.length>0&&Oe(H.message)?H.message:null;throw Y===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(V)}`),new B(502,"the speech upstream failed while serving this request")):new B(502,`speech upstream error: ${Y}`)}if(V.type==="response.completed"){E=V.response??null,h=!0,l?.(E),S(),await k.return?.();break}}if(clearTimeout(I),P)throw new B(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(E===null)throw new B(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let T=new Promise(L=>{g=L});if(y(),await Promise.race([R,T]),clearTimeout(b),b=void 0,g=null,r.voice!==void 0){let L=E[Pt];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"?`${Pt} ${JSON.stringify(L)}`:`no ${Pt} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new gr(N):new B(502,N)}}if(!f)throw new B(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(p&&!m&&v.length<1)throw new B(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return E}catch(O){throw O instanceof gr||await ap(t,n,k,s.returnBoundMs),O}finally{clearTimeout(b),clearTimeout(I),x()}})}function lp(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",mr)),t.write(a,l=>{l||(s+=a.byteLength,za(e,s))}),t.writableLength>qa&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${qa} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let l=a[Pt];if(typeof l=="string"){if(!Va(l))throw Ka(l);t.addTrailers({[mr]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function up(t,e,n,r){let o;try{o=await t(e)}catch(s){throw ut(s,r)}return o?!0:(Do(n,new B(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 dp={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},cp="wav, pcm";async function Ya(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??tp,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${kn}`);let a;try{a=JSON.parse((await dr(t,o)).toString("utf8")||"{}")}catch(g){throw g instanceof ce?new B(413,g.message):new B(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new B(400,"request body must be a JSON object");let l=a;for(let g of Object.keys(l))if(!dp[g])throw new B(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 u=l.input;if(typeof u!="string"||u.trim().length===0)throw new B(400,"input is required and must be a non-empty string","input");if(u.length>Da)throw new B(400,`input is ${u.length} chars \u2014 over the ${Da}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=l.model===void 0?void 0:l.model;if(d!==void 0&&typeof d!="string")throw new B(400,"model must be a string","model");let c=l.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new B(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new B(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 ${kn} against a stale copy of the list`);let f;try{f=await n.clients.speechVoices(d)}catch(g){throw ut(g,r)}if(f.defect!==null)throw new B(500,`the voice set for this model cannot be resolved: ${f.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&f.published.length>0&&!f.published.includes(h))throw new B(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${f.published.join(", ")}`,"voice");let m=l.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new B(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${cp} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(l.stream_format!==void 0&&typeof l.stream_format!="string")throw new B(400,"stream_format, when present, must be a string","stream_format");let _=l.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new B(400,"speed, when present, must be a number","speed");if(_!==1)throw new B(400,`speed=${JSON.stringify(_)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let R=l.instructions;if(R!==void 0){if(typeof R!="string")throw new B(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new B(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 np(n.turn,n.clients,d);let v=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",v,v),!await up(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new B(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 B(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 B(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let b;try{b=await n.clients.speechSessionHandle(d)}catch(g){throw ut(g,r)}let p;try{p=await n.clients.openAudioOn(b)}catch(g){throw ut(g,r)}n.turn&&(n.turn.sessionId=p.sessionId);try{if(m==="wav"){let g=[],y=await Wa(n.clients,p,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fa,returnBoundMs:n.turnReturnBoundMs??Ba},i,x=>g.push(x),x=>{n.turn&&(n.turn.outputSeconds=De(x))},r);if(y===null||i())return;let S=Buffer.concat(g);if(h===void 0){let x=y[Pt];if(typeof x=="string"){if(!Va(x))throw Ka(x);e.setHeader(mr,x)}}za(n.turn,S.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([sp(S.byteLength),S]))}else{let g=lp(e,n.turn,i,h===void 0),y;try{y=await Wa(n.clients,p,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Fa,returnBoundMs:n.turnReturnBoundMs??Ba},i,g.sink,S=>{n.turn&&(n.turn.outputSeconds=De(S))},r)}catch(S){let x=ut(S,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(S){let x=ut(S,r);n.turn&&(n.turn.streamError=!0),g.fail(x);return}}}catch(g){throw ut(g,r)}}catch(a){if(a instanceof ce){Do(e,new B(413,a.message));return}if(a instanceof B){Do(e,a);return}throw a}}var hr="/v1/audio/transcriptions";function Xa(t){return t===hr}var Qa="/v1/audio/models",pp=16*1024*1024,fp=64*1024*1024,te=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Fo(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 Za(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 mp(t){if(!Za(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let l=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:l,bitsPerSample:d}}else if(s==="data"){let l=t.length-a;r=Math.min(i===0||i===4294967295?l:i,l)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function gp(t,e,n){if(t){if(t.model=me({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 hp(t,e){t&&(t.outputUnits=e.seconds)}async function yp(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),l=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),u=[],d=null;for await(let c of l){if(u.push(c),c.type==="error"){let f=c.error??{},h=typeof f.type=="string"?f.type:"upstream_error",m=typeof f.message=="string"&&f.message.length>0&&Oe(f.message)?f.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new te(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new te(h==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new te(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=De(d)),xt(u,d)}function el(t,e){if(t instanceof te)return t;if(t instanceof Se)throw t;return t instanceof W?new te(404,t.message):new te(502,It("transcription",t,e))}async function wp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw el(s,r)}return o?!0:(Fo(n,new te(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var _p=new Set(["file","model","language","response_format"]);async function tl(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??fp,s=n.maxAudioPartBytes??pp;try{if(t.method!=="POST")throw new te(405,`${String(t.method)} is not supported on ${hr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new te(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await cr(t,o)}catch(b){throw b instanceof ce?new te(413,b.message):new te(400,String(b instanceof Error?b.message:b))}let l=new Map;for(let b of a.keys()){if(!_p.has(b))throw new te(400,`form field "${b}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,b);l.set(b,(l.get(b)??0)+1)}for(let[b,p]of l)if(p>1)throw new te(400,`form field "${b}" appears ${p} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,b);let u=a.get("model");if(u!==null&&typeof u!="string")throw new te(400,"model must be a string field","model");let d=u===null?void 0:u,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new te(400,"language, when present, must be a non-empty string","language");let f=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new te(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=a.get("file");if(!(m instanceof File))throw new te(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>s)throw new te(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await m.arrayBuffer());if(!Za(_))throw new te(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let R=mp(_);if(R===null)throw new te(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await gp(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await wp(n.transcriptionModels,d,e,r))return;let v=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let b=await yp(n.clients,d,v,f,n.turn?ve(n.turn):void 0,n.turn,r);hp(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw el(b,r)}}catch(i){if(i instanceof ce){Fo(e,new te(413,i.message));return}if(i instanceof te){Fo(e,i);return}throw i}}var wr="/v1/usage/requests",nl=1e4,vp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ke=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},oe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},yr=class extends oe{constructor(e){super(e),this.name="UsageWithholdingError"}},il=1024*1024;function jo(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ke(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ke(`"${e}" must be an array of uuid strings`);if(n.length>nl)throw new Ke(`"${e}" carries ${n.length} ids; at most ${nl} 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"||!vp.test(s))throw new Ke(`"${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 al(t){return jo(t,"inference_ids")}var bp=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function Ct(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is not a non-empty string (got ${$t(r)})`);return r}function Bo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is neither null nor a non-empty string (got ${$t(r)})`);return r}function Lt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new oe(`${n}: ${e} is not a number (got ${$t(o)})`);if(r&&!Number.isSafeInteger(s))throw new oe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new oe(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var Sp=40,rl=64,ol=600;function ll(t){let e=Object.keys(t).sort(),r=e.slice(0,Sp).map(o=>o.length>rl?`${o.slice(0,rl)}\u2026`:o).join(", ");return r.length>ol&&(r=`${r.slice(0,ol)}\u2026`),`${e.length} keys present: [${r}]`}function $t(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Ho(t){Ve(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
|
|
30
|
-
`)}function
|
|
31
|
-
`}function Gp(t){Ve(process.stdout,t)}function _l(t,e){try{t(e)}catch{}}function vr(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Gp,o=Tp(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),_l(r,wl("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 a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let l;if(a.kind==="catalog")l={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:Up(e),completed_at:e.ts,billable_outcome:Np(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(dt.length>=pl){i("queue_full",`${dt.length} ledger writes are already waiting (capacity ${pl}, ${An} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}dt.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),An<Dp&&(An+=1,Wp())}async function Wp(){try{for(;;){let t=Jp();if(t===void 0)return;fl.add(t);try{await Vp(t)}finally{fl.delete(t)}}}finally{An-=1,qp()}}function Jp(){let t=Date.now();for(;;){let e=dt.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<xn)return e;Mt(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${n}ms for the control plane (bound ${xn}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 Vp(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Mt(t,{outcome:"written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:o.inference_id,path:n.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:n.org,session_id:e.session_id,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,unpriced_reason:o.unpriced_reason,attempts:t.attempts});return}catch(o){let s=Pp(o);if(s!==null){Mt(t,{outcome:"already_written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,attempts:t.attempts});return}let i=Lp(o),a=Date.now()-t.queuedAt;if(En){Mt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Cp(i)&&a<xn){if(await zp(Kp(t.attempts)),En||Date.now()-t.queuedAt>=xn){let l=Date.now()-t.queuedAt;Mt(t,{outcome:"failed",reason:En?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:En?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${xn}ms dwell bound (waited ${l}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}Mt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function Kp(t){return Math.min(Bp,Fp*2**Math.max(0,t-1))}function zp(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Mt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;_l(t.report,wl(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var Go="x-urun-profile",In="voice";var he=class extends Error{status=400},Yp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Xp=/\s/;function Qp(t){return Yp.test(t)}function qo(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new he(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function vl(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 he(`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 he(`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 he(`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 bl(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 he(`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 u=n.trim();if(u==="")throw new he(`the ${Go} header is empty \u2014 the only profile this lane accepts is "${In}" (omit the header for the ordinary lane)`);if(u!==In)throw new he(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${In}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==In)throw new he(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${In}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new he("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new he("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let l=a??{};return{flushMaxChars:vl(l,"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:vl(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:qo(l,"sentence_flush",!0),includeReasoning:qo(l,"include_reasoning",!1),metadata:qo(l,"metadata",!1)}}var Nt=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&&Qp(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(Xp.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function Vo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function ef(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 pe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function X(t,e,n,r="invalid_request_error",o){pe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Ko(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Me(r),a=i??Te(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 l=r?.code??null,u=o==="invalid_request_error"?400:l==="queue_timeout"?429:502;u===429&&t.setHeader("retry-after","30"),pe(t,u,{error:{message:a,type:o,code:l}})}function Ce(t,e,n,r){pe(t,e,{type:"error",error:{type:n,message:r}})}function Ut(t,e,n){if(e==="anthropic"){pe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}pe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var tf=64*1024*1024,On=class extends Error{};async function Sl(t,e=tf){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new On(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function ct(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 Rl(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,o=r(n.input_tokens),s=r(n.output_tokens),i=l=>l??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let l={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function br(t){let e=Rl(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function kl(t){let e=br(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:nf(t)},completion_tokens_details:{reasoning_tokens:0}}}function nf(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 rf(t,e){let n=Rl(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function of(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function sf(t,e){let n=of(e);n&&(t.timing=n),t.outputSeconds=De(e)}function pt(t,e){rf(t,e),sf(t,e)}async function Er(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 El(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 af(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 Sr=class extends Error{};function lf(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 Sr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function uf(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:lf(n.role,n.content)})}return e}function Wo(t){return Rt(t).map((e,n)=>({index:n,id:e.call_id??e.id??`call_${n}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function df(t,e,n,r,o,s,i){let a=fn(s.id),l=t.stream===!0;if(s.model=me(t),s.stream=l,await Er(s,e,typeof t.model=="string"?t.model:void 0),l){let b;try{b=await gn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(p){if(p instanceof W){Ut(r,"openai",p);return}if(p instanceof be){X(r,p.status,p.message);return}if(p instanceof xe||p instanceof ue){r.setHeader("retry-after","2"),X(r,503,p.message,"capacity_error");return}throw p}Vo(r);for await(let p of b.events){if(p.type==="error"){s.streamError=!0;let g=p.error,y=Me(g),S=y??Te(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(p)}`),r.write(`event: error
|
|
30
|
+
`)}function Ea(t,e){if(!de(e))throw new Re("decision answer was not a JSON object");let n=e.answers;if(!de(n))throw new Re("decision answer carried no answers object");let r=[];for(let o of t){let s=n[o.key];if(!de(s)||s.skipped===!0){r.push({type:"refusal",name:o.name});continue}let i=de(s.probabilities)?s.probabilities:{};switch(o.type){case"predicate":{let a=Fo(s.noul);if(a===null)throw new Re(`the predicate answer for "${o.key}" carries no noul probability to translate`);r.push({type:"predicate",name:o.name,probability:a});continue}case"choice":{let a=o.choiceValues??[],l=s.choice;if(typeof l!="string")throw new Re(`the choice answer for "${o.key}" carries no string choice`);let u=a.findIndex(f=>String(f)===l);if(u===-1)throw new Re(`the choice answer for "${o.key}" is not one of the supplied options (${JSON.stringify(l)})`);let d=dr(s.confidence);if(d===null)throw new Re(`the choice answer for "${o.key}" carries no numeric confidence to translate`);let c=[];for(let f of a){let h=Fo(i[String(f)]);h!==null&&c.push({value:f,probability:h})}r.push({type:"choice",name:o.name,choice:a[u],confidence:d,probabilities:c});continue}case"score":{let a=o.levelLabels??[],l=dr(s.score);if(l===null)throw new Re(`the score answer for "${o.key}" carries no numeric score to translate`);let u=dr(s.confidence);if(u===null)throw new Re(`the score answer for "${o.key}" carries no numeric confidence to translate`);let d=[];for(let c=0;c<a.length;c++){let f=Fo(i[String(c)]);f!==null&&d.push({value:c,label:a[c],probability:f})}r.push({type:"score",name:o.name,score:l,confidence:u,probabilities:d});continue}}}return r}var ce=class extends Error{};async function cr(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new ce(`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 ce(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function pr(t,e){let n=t[Symbol.asyncIterator](),r=0,o=new ReadableStream({async pull(i){try{let a=await n.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new ce(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){n.return?.()}}),s;try{let i=new Headers;for(let[u,d]of Object.entries(t.headers))if(typeof d=="string")i.set(u,d);else if(Array.isArray(d))for(let c of d)i.append(u,c);let a={method:"POST",headers:i,body:o,duplex:"half"};s=await new Request(`https://proxy.internal${t.url??"/"}`,a).formData()}catch(i){throw i instanceof ce?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return s}var xa="/v1/images/generations",fr="/v1/images/edits";function Aa(t){return t===xa||t===fr}var Ia="/v1/images/models";async function Oa(t,e,n){if(t){if(t.model=me({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var G=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},Zc=16*1024*1024,Ta=64*1024*1024;function Pa(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 Sn(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 Ca(t,e,n,r,o,s){let i=s??(m=>console.error(m)),a=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),l=null;for await(let m of a){if(m.type==="error"){let _=m.error??{},R=typeof _.message=="string"&&_.message.length>0&&Oe(_.message)?_.message:null;throw R===null?(i(`[caller-message-boundary] image upstream error event detail withheld from the caller: ${JSON.stringify(m)}`),new G(502,"the image upstream failed while serving this request")):new G(502,`image upstream error: ${R}`)}if(m.type==="response.completed"){l=m.response??null;break}}if(l===null)throw new G(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");o&&(o.outputSeconds=Fe(l));let u=l.images;if(!Array.isArray(u)||u.length!==1||typeof u[0]!="string"||u[0].length===0)throw new G(502,`image upstream returned ${Array.isArray(u)?u.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=u[0].startsWith("data:")?u[0].slice(u[0].indexOf(";base64,")+8):u[0],f=Buffer.from(c,"base64");if(Pa(f)===null)throw new G(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${f.length} bytes) \u2014 refusing to pass it through`);return d.push(c),{images:d}}function La(t,e){if(t instanceof G)return t;if(t instanceof Se)throw t;return t instanceof W?new G(404,t.message):new G(502,Pt("image",t,e))}async function $a(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 Sn(r,new G(404,e===void 0?`no image-capable default model is configured for this caller (${o}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${n==="edit"?"edit-capable":"generation-capable"} for this caller (${o}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function Ma(t,e){t&&(t.outputUnits=e.images.length)}function Na(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 ep={model:!0,prompt:!0,response_format:!0,n:!0};async function Ua(t,e,n){let r=n.operatorLog??(s=>console.error(s)),o=n.maxBodyBytes??Ta;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${xa}`);let s;try{s=JSON.parse((await cr(t,o)).toString("utf8")||"{}")}catch(f){throw f instanceof ce?new G(413,f.message):new G(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new G(400,"request body must be a JSON object");let i=s;for(let f of Object.keys(i))if(!ep[f])throw new G(400,`request field "${f}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,f);let a=i.prompt;if(typeof a!="string"||a.trim().length===0)throw new G(400,"prompt is required and must be a non-empty string","prompt");let l=i.model===void 0?void 0:i.model;if(l!==void 0&&typeof l!="string")throw new G(400,"model must be a string","model");await Oa(n.turn,n.clients,l);let u=i.n??1;if(u!==1)throw new G(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=i.response_format??"b64_json";if(d!=="b64_json")throw new G(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",a.length,a.length),!await $a(n.imageModels,l,"generation",e))return;let c=[{type:"input_text",text:a}];try{let f=await Ca(n.clients,l,c,n.turn?ve(n.turn):void 0,n.turn,r);Ma(n.turn,f),Na(e,f)}catch(f){throw La(f,r)}}catch(s){if(s instanceof ce){Sn(e,new G(413,s.message));return}if(s instanceof G){Sn(e,s);return}throw s}}var tp={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Da(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??Ta,s=n.maxImagePartBytes??Zc;try{if(t.method!=="POST")throw new G(405,`${String(t.method)} is not supported on ${fr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new G(400,`the edit endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await pr(t,o)}catch(m){throw m instanceof ce?new G(413,m.message):new G(400,String(m instanceof Error?m.message:m))}let l=a.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new G(400,"prompt is required and must be a non-empty string field","prompt");let u=a.get("model");if(u!==null&&typeof u!="string")throw new G(400,"model must be a string field","model");let d=u===null?void 0:u;await Oa(n.turn,n.clients,d);let c=a.get("response_format")??"b64_json";if(c!=="b64_json")throw new G(400,`response_format ${JSON.stringify(c)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let m of a.keys())if(!tp[m])throw new G(400,`form field "${m}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,m);let f=[];for(let m of["image","image[]"])for(let _ of a.getAll(m)){if(!(_ instanceof File))throw new G(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",m);if(_.size>s)throw new G(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,m);let R=new Uint8Array(await _.arrayBuffer()),v=Pa(R);if(v===null)throw new G(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",m);f.push({bytes:R,mime:v})}if(f.length===0)throw new G(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await $a(n.imageModels,d,"edit",e))return;let h=[{type:"input_text",text:l}];for(let{bytes:m,mime:_}of f)h.push({type:"input_image",image_url:`data:${_};base64,${Buffer.from(m).toString("base64")}`});try{let m=await Ca(n.clients,d,h,n.turn?ve(n.turn):void 0,n.turn,r);Ma(n.turn,m),Na(e,m)}catch(m){throw La(m,r)}}catch(i){if(i instanceof ce){Sn(e,new G(413,i.message));return}if(i instanceof G){Sn(e,i);return}throw i}}var kn="/v1/audio/speech";function Va(t){return t===kn}var Fa=4096,Ba=18e4,Ha=5e3,np=64*1024*1024,ja=8,qa=5,Ga=1024*1024,$t="voice_applied",gr="X-Urun-Voice-Applied",B=class extends Error{status;param;retryAfterSeconds;constructor(e,n,r,o){super(n),this.status=e,this.param=r,this.retryAfterSeconds=o}};function Bo(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 hr=class extends B{constructor(e){super(502,e)}};function Ka(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 za(t){return new B(502,`the runtime's ${$t} receipt ${JSON.stringify(t)} cannot be relayed as the ${gr} 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 rp(t,e,n){if(t){if(t.model=me({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 Ya(t,e){if(!t)return;let n=e/(24e3*2);t.outputUnits=n,t.outputMinutes=n/60}var op=2;function sp(t){for(let e=0;e+1<t.byteLength;e+=2)if(Math.abs(t.readInt16LE(e))>op)return!1;return!0}function ip(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 Wa=new WeakMap,mr=new WeakMap;function ap(t,e){let n=mr.get(t)??0;if(n>=ja)throw new B(503,`this model's speech queue is full \u2014 ${ja} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${qa}s`,void 0,qa);mr.set(t,n+1);let r=Wa.get(t)??Promise.resolve(),o,s=new Promise(i=>{o=i});return Wa.set(t,s),(async()=>{await r;try{return await e()}finally{mr.set(t,(mr.get(t)??1)-1),o()}})()}async function lp(t,e,n,r){if(typeof t.evictSpeechSession!="function")throw new B(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 q))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 pt(t,e){if(t instanceof B)return t;if(t instanceof Se)throw t;return t instanceof W?new B(404,t.message):new B(502,Pt("speech",t,e))}async function Ja(t,e,n,r,o,s,i,a,l,u){let d=u??(f=>console.error(f)),c=a??(()=>{});return ap(e,async()=>{if(i?.()===!0)return null;let f=!1,h=!1,m=!1,_,R=new Promise(O=>{_=O}),v=[],b,p=!1,g=null,y=()=>{g!==null&&(clearTimeout(b),b=setTimeout(()=>{p=!0,g?.()},o.capMs))},S=()=>{h&&!m&&v.length>=o.quietRunFrames&&(m=!0,_())},x=e.onOutputAudio(O=>{let w=Buffer.from(O,"base64");if(w.byteLength===0)return;y();let A=sp(w);if(!f){if(A)return;f=!0}if(A){v.push(w),S();return}for(let T of v)c(T);v.length=0,c(w),S()}),E=null,I,k;try{k=(await t.createResponseOn(n,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let w=()=>(clearTimeout(I),new Promise(L=>{I=setTimeout(L,s.capMs)})),A=w(),T=!1;for(;;){let L=k.next(),N=await Promise.race([L,A]);if(N===void 0){T=!0,L.catch(()=>{});break}if(N.done)break;let V=N.value;if(A=w(),V.type==="error"){let H=V.error??{};await k.return?.();let Y=typeof H.message=="string"&&H.message.length>0&&Oe(H.message)?H.message:null;throw Y===null?(d(`[caller-message-boundary] speech upstream error event detail withheld from the caller: ${JSON.stringify(V)}`),new B(502,"the speech upstream failed while serving this request")):new B(502,`speech upstream error: ${Y}`)}if(V.type==="response.completed"){E=V.response??null,h=!0,l?.(E),S(),await k.return?.();break}}if(clearTimeout(I),T)throw new B(504,`the speech turn produced no terminal event within ${s.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(E===null)throw new B(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=new Promise(L=>{g=L});if(y(),await Promise.race([R,P]),clearTimeout(b),b=void 0,g=null,r.voice!==void 0){let L=E[$t];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"?`${$t} ${JSON.stringify(L)}`:`no ${$t} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw m?new hr(N):new B(502,N)}}if(!f)throw new B(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(p&&!m&&v.length<1)throw new B(502,`the upstream audio stream did not quiesce within ${o.capMs}ms of its last audio frame (no quiet run, no further frames) \u2014 refusing to serve audio whose tail cannot be vouched for`);return E}catch(O){throw O instanceof hr||await lp(t,n,k,s.returnBoundMs),O}finally{clearTimeout(b),clearTimeout(I),x()}})}function up(t,e,n,r){let o=!1,s=0,i=a=>{t.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){n()||(o||(o=!0,t.statusCode=200,t.setHeader("content-type","audio/pcm"),r&&t.setHeader("trailer",gr)),t.write(a,l=>{l||(s+=a.byteLength,Ya(e,s))}),t.writableLength>Ga&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${Ga} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>o,async finish(a){if(!n()){if(r){let l=a[$t];if(typeof l=="string"){if(!Ka(l))throw za(l);t.addTrailers({[gr]:l})}}await new Promise(l=>{t.end(()=>l())})}},fail:i}}async function dp(t,e,n,r){let o;try{o=await t(e)}catch(s){throw pt(s,r)}return o?!0:(Bo(n,new B(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 cp={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},pp="wav, pcm";async function Xa(t,e,n){let r=n.operatorLog??(a=>console.error(a)),o=n.maxBodyBytes??np,s=!1;e.once("close",()=>{s=!0});let i=()=>s||e.destroyed;try{if(t.method!=="POST")throw new B(405,`${String(t.method)} is not supported on ${kn}`);let a;try{a=JSON.parse((await cr(t,o)).toString("utf8")||"{}")}catch(g){throw g instanceof ce?new B(413,g.message):new B(400,"request body is not valid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new B(400,"request body must be a JSON object");let l=a;for(let g of Object.keys(l))if(!cp[g])throw new B(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 u=l.input;if(typeof u!="string"||u.trim().length===0)throw new B(400,"input is required and must be a non-empty string","input");if(u.length>Fa)throw new B(400,`input is ${u.length} chars \u2014 over the ${Fa}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=l.model===void 0?void 0:l.model;if(d!==void 0&&typeof d!="string")throw new B(400,"model must be a string","model");let c=l.voice;if(c!==void 0&&(typeof c!="string"||c.trim().length===0))throw new B(400,"voice must be a non-empty string","voice");if(typeof n.clients.speechVoices!="function")throw new B(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 ${kn} against a stale copy of the list`);let f;try{f=await n.clients.speechVoices(d)}catch(g){throw pt(g,r)}if(f.defect!==null)throw new B(500,`the voice set for this model cannot be resolved: ${f.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let h=typeof c=="string"?c:void 0;if(h!==void 0&&f.published.length>0&&!f.published.includes(h))throw new B(400,`voice ${JSON.stringify(h)} is not one of the voices this model publishes \u2014 accepted voices: ${f.published.join(", ")}`,"voice");let m=l.response_format??"wav";if(m!=="wav"&&m!=="pcm")throw new B(400,`response_format ${JSON.stringify(m)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${pp} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(l.stream_format!==void 0&&typeof l.stream_format!="string")throw new B(400,"stream_format, when present, must be a string","stream_format");let _=l.speed;if(_!==void 0){if(typeof _!="number"||!Number.isFinite(_))throw new B(400,"speed, when present, must be a number","speed");if(_!==1)throw new B(400,`speed=${JSON.stringify(_)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let R=l.instructions;if(R!==void 0){if(typeof R!="string")throw new B(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new B(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 rp(n.turn,n.clients,d);let v=Buffer.byteLength(JSON.stringify(l));if(n.stats?.request("audio_speech",v,v),!await dp(n.speechModels,d,e,r))return;if(typeof n.clients.openAudioOn!="function")throw new B(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 B(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 B(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(i())return;let b;try{b=await n.clients.speechSessionHandle(d)}catch(g){throw pt(g,r)}let p;try{p=await n.clients.openAudioOn(b)}catch(g){throw pt(g,r)}n.turn&&(n.turn.sessionId=p.sessionId);try{if(m==="wav"){let g=[],y=await Ja(n.clients,p,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ba,returnBoundMs:n.turnReturnBoundMs??Ha},i,x=>g.push(x),x=>{n.turn&&(n.turn.outputSeconds=Fe(x))},r);if(y===null||i())return;let S=Buffer.concat(g);if(h===void 0){let x=y[$t];if(typeof x=="string"){if(!Ka(x))throw za(x);e.setHeader(gr,x)}}Ya(n.turn,S.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([ip(S.byteLength),S]))}else{let g=up(e,n.turn,i,h===void 0),y;try{y=await Ja(n.clients,p,b,{model:d,text:u,...h!==void 0?{voice:h}:{}},{quietRunFrames:n.quietRunFrames??3,capMs:n.drainCapMs??2e3},{capMs:n.turnCapMs??Ba,returnBoundMs:n.turnReturnBoundMs??Ha},i,g.sink,S=>{n.turn&&(n.turn.outputSeconds=Fe(S))},r)}catch(S){let x=pt(S,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(S){let x=pt(S,r);n.turn&&(n.turn.streamError=!0),g.fail(x);return}}}catch(g){throw pt(g,r)}}catch(a){if(a instanceof ce){Bo(e,new B(413,a.message));return}if(a instanceof B){Bo(e,a);return}throw a}}var yr="/v1/audio/transcriptions";function Qa(t){return t===yr}var Za="/v1/audio/models",fp=16*1024*1024,mp=64*1024*1024,te=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}};function Ho(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 el(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 gp(t){if(!el(t))return null;let e=12,n=null,r=null;for(;e+8<=t.length;){let s=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=(t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24)>>>0,a=e+8;if(s==="fmt "&&a+16<=t.length){let l=t[a+2]|t[a+3]<<8,u=(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)>>>0,d=t[a+14]|t[a+15]<<8;n={sampleRate:u,channels:l,bitsPerSample:d}}else if(s==="data"){let l=t.length-a;r=Math.min(i===0||i===4294967295?l:i,l)}e=a+i+i%2}if(n===null||r===null||r===0||n.sampleRate===0||n.channels===0||n.bitsPerSample===0)return null;let o=r/(n.sampleRate*n.channels*(n.bitsPerSample/8));return!Number.isFinite(o)||o<0?null:{seconds:o,sampleRate:n.sampleRate,channels:n.channels,bitsPerSample:n.bitsPerSample}}async function hp(t,e,n){if(t){if(t.model=me({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 yp(t,e){t&&(t.outputUnits=e.seconds)}async function wp(t,e,n,r,o,s,i){let a=i??(c=>console.error(c)),l=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1,...r!==void 0?{language:r}:{}},o),u=[],d=null;for await(let c of l){if(u.push(c),c.type==="error"){let f=c.error??{},h=typeof f.type=="string"?f.type:"upstream_error",m=typeof f.message=="string"&&f.message.length>0&&Oe(f.message)?f.message:null;throw m===null?(a(`[caller-message-boundary] transcription upstream error event detail withheld from the caller: ${JSON.stringify(c)}`),new te(h==="invalid_request_error"?400:502,"the transcription upstream failed while serving this request")):new te(h==="invalid_request_error"?400:502,`transcription upstream error: ${m}`)}if(c.type==="response.completed"){d=c.response??null;break}}if(d===null)throw new te(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return s&&(s.outputSeconds=Fe(d)),Ot(u,d)}function tl(t,e){if(t instanceof te)return t;if(t instanceof Se)throw t;return t instanceof W?new te(404,t.message):new te(502,Pt("transcription",t,e))}async function _p(t,e,n,r){let o;try{o=await t(e)}catch(s){throw tl(s,r)}return o?!0:(Ho(n,new te(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var vp=new Set(["file","model","language","response_format"]);async function nl(t,e,n){let r=n.operatorLog??(i=>console.error(i)),o=n.maxBodyBytes??mp,s=n.maxAudioPartBytes??fp;try{if(t.method!=="POST")throw new te(405,`${String(t.method)} is not supported on ${yr}`);let i=String(t.headers["content-type"]??"");if(!i.toLowerCase().startsWith("multipart/form-data"))throw new te(400,`the transcriptions endpoint consumes multipart/form-data, got ${i||"none"}`);let a;try{a=await pr(t,o)}catch(b){throw b instanceof ce?new te(413,b.message):new te(400,String(b instanceof Error?b.message:b))}let l=new Map;for(let b of a.keys()){if(!vp.has(b))throw new te(400,`form field "${b}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,b);l.set(b,(l.get(b)??0)+1)}for(let[b,p]of l)if(p>1)throw new te(400,`form field "${b}" appears ${p} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,b);let u=a.get("model");if(u!==null&&typeof u!="string")throw new te(400,"model must be a string field","model");let d=u===null?void 0:u,c=a.get("language");if(c!==null&&(typeof c!="string"||c.trim().length===0))throw new te(400,"language, when present, must be a non-empty string","language");let f=c===null?void 0:c,h=a.get("response_format")??"json";if(h!=="json")throw new te(400,`response_format ${JSON.stringify(h)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let m=a.get("file");if(!(m instanceof File))throw new te(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(m.size>s)throw new te(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let _=new Uint8Array(await m.arrayBuffer());if(!el(_))throw new te(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let R=gp(_);if(R===null)throw new te(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await hp(n.turn,n.clients,d),n.stats?.request("audio_transcriptions",_.length,_.length),!await _p(n.transcriptionModels,d,e,r))return;let v=[{type:"input_audio",input_audio:{data:Buffer.from(_).toString("base64"),format:"wav"}}];try{let b=await wp(n.clients,d,v,f,n.turn?ve(n.turn):void 0,n.turn,r);yp(n.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:b}))}catch(b){throw tl(b,r)}}catch(i){if(i instanceof ce){Ho(e,new te(413,i.message));return}if(i instanceof te){Ho(e,i);return}throw i}}var _r="/v1/usage/requests",rl=1e4,bp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ye=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},oe=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},wr=class extends oe{constructor(e){super(e),this.name="UsageWithholdingError"}},al=1024*1024;function Go(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Ye(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new Ye(`"${e}" must be an array of uuid strings`);if(n.length>rl)throw new Ye(`"${e}" carries ${n.length} ids; at most ${rl} 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"||!bp.test(s))throw new Ye(`"${e}" contains ${JSON.stringify(s)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);o.has(s)||(o.add(s),r.push(s))}return r}function ll(t){return Go(t,"inference_ids")}var Sp=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function Mt(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is not a non-empty string (got ${Ut(r)})`);return r}function jo(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new oe(`${n}: ${e} is neither null nor a non-empty string (got ${Ut(r)})`);return r}function Nt(t,e,n,r){let o=t[e];if(o===null)return null;let s=typeof o=="number"?o:typeof o=="string"&&/^-?\d+(\.\d+)?$/.test(o.trim())?Number(o.trim()):NaN;if(!Number.isFinite(s))throw new oe(`${n}: ${e} is not a number (got ${Ut(o)})`);if(r&&!Number.isSafeInteger(s))throw new oe(`${n}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(s<0)throw new oe(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var kp=40,ol=64,sl=600;function ul(t){let e=Object.keys(t).sort(),r=e.slice(0,kp).map(o=>o.length>ol?`${o.slice(0,ol)}\u2026`:o).join(", ");return r.length>sl&&(r=`${r.slice(0,sl)}\u2026`),`${e.length} keys present: [${r}]`}function Ut(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function qo(t){Ke(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
|
|
31
|
+
`)}function Rp(t,e){let n;try{n=t(e)}catch{il(t,e);return}Ep(n)&&Promise.resolve(n).catch(()=>{il(t,e)})}function Ep(t){return typeof t?.then=="function"}function il(t,e){if(t!==qo)try{qo(e)}catch{}}function dl(t,e=qo){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?ul(t):Ut(t);throw new oe(`the usage surface answered without a "requests" array: got ${Ut(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(xp(n[o],s))}catch(i){if(i instanceof wr||!(i instanceof oe))throw i;Rp(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new oe(`the usage surface returned ${n.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function xp(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new oe(`${e} is not an object: got ${Ut(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new wr(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let o of Sp)if(!Object.hasOwn(n,o))throw new oe(`${e} has no "${o}" column (${ul(n)})`);let r=Nt(n,"http_status",e,!0);if(r===null)throw new oe(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Mt(n,"inference_id",e),model_id:Mt(n,"model_id",e),identity_kind:Mt(n,"identity_kind",e),variant:jo(n,"variant",e),task:Mt(n,"task",e),http_status:r,started_at:Mt(n,"started_at",e),completed_at:Mt(n,"completed_at",e),prompt_tokens:Nt(n,"prompt_tokens",e,!0),completion_tokens:Nt(n,"completion_tokens",e,!0),output_units:Nt(n,"output_units",e,!1),output_minutes:Nt(n,"output_minutes",e,!1),cost_nano_usd:Nt(n,"cost_nano_usd",e,!0),price_version:jo(n,"price_version",e),priced_at:jo(n,"priced_at",e)}}function vr(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 oe(`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 oe(`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 Er=require("@urun-sh/core");var Rn="/partners/huggingface/v1/billing/requests";function Ap(t){return Go(t,"requestIds")}function Ip(t){return t>=200&&t<=399}function Op(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&Ip(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function cl(t,e){let n=Ap(t),r=await e(n);return vr(r,n),Op(r)}var Tp={"/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 Pp(t){return Tp[t]??null}var gl=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Cp(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Lp(t){return t==="surface"}function $p(t){let e=t?.ledgerFailureReason;return gl.includes(e)?e:"unknown"}var Mp=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],pl=["priced","unpriced"],Np={written:pl,already_written:pl,skipped:Mp,failed:gl},hl=Object.entries(Np).flatMap(([t,e])=>e.map(n=>({outcome:t,reason:n})));function Up(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Dp(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 Fp=256,fl=4096,xn=12e4,Bp=250,Hp=8e3,ft=[],ml=new Set,An=0,En=!1;function yl(){return ft.length}function wl(t=Date.now()){let e=ft[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var jp=new Set;function qp(){return An===0&&ft.length===0}function Gp(){if(qp()){En=!1;for(let t of[...jp])t()}}function _l(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
32
|
+
`}function Wp(t){Ke(process.stdout,t)}function vl(t,e){try{t(e)}catch{}}function br(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Wp,o=Pp(e.path);if(o===null)return;let s=d=>{try{n.observe(d)}catch{}},i=(d,c)=>{s({outcome:"skipped",reason:d}),vl(r,_l("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 a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let l;if(a.kind==="catalog")l={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}l={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let u={inference_id:e.inference_id,...l,task:o,http_status:e.status,started_at:Dp(e),completed_at:e.ts,billable_outcome:Up(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(ft.length>=fl){i("queue_full",`${ft.length} ledger writes are already waiting (capacity ${fl}, ${An} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}ft.push({entry:u,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),An<Fp&&(An+=1,Jp())}async function Jp(){try{for(;;){let t=Vp();if(t===void 0)return;ml.add(t);try{await Kp(t)}finally{ml.delete(t)}}}finally{An-=1,Gp()}}function Vp(){let t=Date.now();for(;;){let e=ft.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<xn)return e;Dt(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 ${xn}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 Kp(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Dt(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=Cp(o);if(s!==null){Dt(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=$p(o),a=Date.now()-t.queuedAt;if(En){Dt(t,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:t.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${o instanceof Error?o.message:String(o)}`});return}if(Lp(i)&&a<xn){if(await Yp(zp(t.attempts)),En||Date.now()-t.queuedAt>=xn){let l=Date.now()-t.queuedAt;Dt(t,{outcome:"failed",reason:En?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:En?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:l,error:`this row's backoff outlived the ${xn}ms dwell bound (waited ${l}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}Dt(t,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:t.attempts,waited_ms:a,error:o instanceof Error?o.message:String(o)});return}}}function zp(t){return Math.min(Hp,Bp*2**Math.max(0,t-1))}function Yp(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Dt(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;vl(t.report,_l(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}var Jo="x-urun-profile",In="voice";var he=class extends Error{status=400},Xp=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,Qp=/\s/;function Zp(t){return Xp.test(t)}function Wo(t,e,n){let r=t[e];if(r===void 0)return n;if(typeof r!="boolean")throw new he(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function bl(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 he(`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 he(`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 he(`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 Sl(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 he(`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 u=n.trim();if(u==="")throw new he(`the ${Jo} header is empty \u2014 the only profile this lane accepts is "${In}" (omit the header for the ordinary lane)`);if(u!==In)throw new he(`unknown profile "${u}" \u2014 the only profile this lane accepts is "${In}"`);i=!0}if(s!==void 0){if(typeof s!="string"||s!==In)throw new he(`unknown profile ${JSON.stringify(s)} \u2014 the only profile this lane accepts is "${In}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new he("the voice profile is streaming-only \u2014 send stream: true");let a=o?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new he("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let l=a??{};return{flushMaxChars:bl(l,"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:bl(l,"flush_max_ms",250,{max:2147483647}),sentenceFlush:Wo(l,"sentence_flush",!0),includeReasoning:Wo(l,"include_reasoning",!1),metadata:Wo(l,"metadata",!1)}}var Ft=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&&Zp(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(Qp.test(this.buffer[o]))return o+1;let n=Math.max(1,e),r=this.buffer.charCodeAt(n-1);return r>=55296&&r<=56319?n-1:n}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function zo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function tf(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 pe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function X(t,e,n,r="invalid_request_error",o){pe(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function Yo(t,e,n){let r=e.error,o=r?.type??"upstream_error",s=n?.operatorError??(d=>console.error(d)),i=Ne(r),a=i??Te(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 l=r?.code??null,u=o==="invalid_request_error"?400:l==="queue_timeout"?429:502;u===429&&t.setHeader("retry-after","30"),pe(t,u,{error:{message:a,type:o,code:l}})}function Ce(t,e,n,r){pe(t,e,{type:"error",error:{type:n,message:r}})}function Bt(t,e,n){if(e==="anthropic"){pe(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}pe(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var nf=64*1024*1024,On=class extends Error{};async function kl(t,e=nf){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new On(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function mt(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 El(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?l:null,o=r(n.input_tokens),s=r(n.output_tokens),i=l=>l??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let l={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:l}:{kind:"counts",usage:l}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Sr(t){let e=El(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function Rl(t){let e=Sr(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:rf(t)},completion_tokens_details:{reasoning_tokens:0}}}function rf(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 of(t,e){let n=El(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function sf(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=l=>{let u=n[l];return typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function af(t,e){let n=sf(e);n&&(t.timing=n),t.outputSeconds=Fe(e)}function gt(t,e){of(t,e),af(t,e)}async function xr(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 xl(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 lf(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 kr=class extends Error{};function uf(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 kr(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function df(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:uf(n.role,n.content)})}return e}function Vo(t){return At(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 cf(t,e,n,r,o,s,i){let a=fn(s.id),l=t.stream===!0;if(s.model=me(t),s.stream=l,await xr(s,e,typeof t.model=="string"?t.model:void 0),l){let b;try{b=await gn({body:t,clients:e,store:n,stats:o,responseId:a,turn:s})}catch(p){if(p instanceof W){Bt(r,"openai",p);return}if(p instanceof be){X(r,p.status,p.message);return}if(p instanceof Ae||p instanceof ue){r.setHeader("retry-after","2"),X(r,503,p.message,"capacity_error");return}throw p}zo(r);for await(let p of b.events){if(p.type==="error"){s.streamError=!0;let g=p.error,y=Ne(g),S=y??Te(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(p)}`),r.write(`event: error
|
|
32
33
|
data: ${JSON.stringify({error:{message:S,type:g?.type??"upstream_error",code:g?.code??null}})}
|
|
33
34
|
|
|
34
|
-
`),r.end();return}p.type==="response.completed"&&
|
|
35
|
+
`),r.end();return}p.type==="response.completed"&>(s,p.response),r.write(`event: ${String(p.type??"message")}
|
|
35
36
|
data: ${JSON.stringify(p)}
|
|
36
37
|
|
|
37
38
|
`)}r.write(`data: [DONE]
|
|
38
39
|
|
|
39
|
-
`),r.end();return}let u;try{u=
|
|
40
|
+
`),r.end();return}let u;try{u=Tt(n,t)}catch(b){if(b instanceof be){X(r,b.status,b.message);return}throw b}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,c=me(t);o.model(c);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await bo(e,t,u,!1,ve(s))}catch(b){if(b instanceof W){Bt(r,"openai",b);return}if(b instanceof be){X(r,b.status,b.message);return}if(b instanceof Ae||b instanceof ue){r.setHeader("retry-after","2"),X(r,503,b.message,"capacity_error");return}throw b}let m=[],_=null;for await(let b of o.track(h,c,s)){if(m.push(b),b.type==="error"){Yo(r,b,{inferenceId:s.id,operatorError:i});return}b.type==="response.completed"&&(_=b.response)}if(_==null){X(r,502,"upstream produced no response.completed event","upstream_error");return}gt(s,_);let R=Ot(m,_),v=dt(f,At(_).length,R);if(v){X(r,502,ut(c,v),"upstream_error");return}d&&n.remember(a,u,vo(_,R),d),pe(r,200,{..._,id:a})}async function pf(t,e,n,r,o,s,i){let a=t.messages;if(!Array.isArray(a)){X(n,400,"chat/completions requires a messages array");return}let l;try{l=Sl(s,t)}catch(k){if(k instanceof he){X(n,k.status,k.message);return}throw k}let u=String(t.model??"urun"),d=Yi(o.id),c;try{c=df(a)}catch(k){if(k instanceof kr){X(n,400,k.message);return}throw k}let f=me(t);r.model(f),o.model=f,o.stream=t.stream===!0,await xr(o,e,typeof t.model=="string"?t.model:void 0);let h=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:c,stream:!0,tools:lf(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}:{}},ve(o))}catch(k){if(k instanceof W){Bt(n,"openai",k);return}if(k instanceof Ae||k instanceof ue){n.setHeader("retry-after","2"),X(n,503,k.message,"capacity_error");return}throw k}if(t.stream===!0){l?tf(n):zo(n);let k=[],O=new We,w="",A=l?new Ft(l,P=>{n.write(`data: ${JSON.stringify(mt(d,u,{content:P},null))}
|
|
40
41
|
|
|
41
|
-
`)}):null,P
|
|
42
|
+
`)}):null,T=P=>{A?.flush(),n.write(P),n.end()};try{l?.metadata&&n.write(`data: ${JSON.stringify({object:"chat.completion.metadata",id:d,model:u,interruptible:!0,tts:{sample_rate_hz:24e3,voice_hint:null}})}
|
|
42
43
|
|
|
43
|
-
`),n.write(`data: ${JSON.stringify(
|
|
44
|
+
`),n.write(`data: ${JSON.stringify(mt(d,u,{role:"assistant"},null))}
|
|
44
45
|
|
|
45
|
-
`);for await(let H of r.track(m,f,o)){k.push(H);let Y=
|
|
46
|
+
`);for await(let H of r.track(m,f,o)){k.push(H);let Y=It(H);if(H.type==="response.output_text.delta"&&typeof H.delta=="string")w+=H.delta,A?A.push(H.delta):n.write(`data: ${JSON.stringify(mt(d,u,{content:H.delta},null))}
|
|
46
47
|
|
|
47
|
-
`);else if(H.type==="response.reasoning_text.delta"&&typeof H.delta=="string")(!l||l.includeReasoning)&&n.write(`data: ${JSON.stringify(
|
|
48
|
+
`);else if(H.type==="response.reasoning_text.delta"&&typeof H.delta=="string")(!l||l.includeReasoning)&&n.write(`data: ${JSON.stringify(mt(d,u,{reasoning_content:H.delta},null))}
|
|
48
49
|
|
|
49
|
-
`);else if(Y){A?.flush();let{call:D,isNew:j}=O.add(Y),K=j?{index:Y.tool_index,id:D.id??`call_${Y.tool_index}`,type:"function",function:{name:D.name??"",arguments:Y.delta}}:{index:Y.tool_index,function:{arguments:Y.delta}};n.write(`data: ${JSON.stringify(
|
|
50
|
+
`);else if(Y){A?.flush();let{call:D,isNew:j}=O.add(Y),K=j?{index:Y.tool_index,id:D.id??`call_${Y.tool_index}`,type:"function",function:{name:D.name??"",arguments:Y.delta}}:{index:Y.tool_index,function:{arguments:Y.delta}};n.write(`data: ${JSON.stringify(mt(d,u,{tool_calls:[K]},null))}
|
|
50
51
|
|
|
51
|
-
`)}else if(H.type==="error"){o.streamError=!0;let D=H.error??{},j=
|
|
52
|
+
`)}else if(H.type==="error"){o.streamError=!0;let D=H.error??{},j=Ne(D),K=j??Te(o.id);j===null&&i(`[caller-message-boundary] chat stream upstream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(H)}`),T(`data: ${JSON.stringify({error:{message:K,type:D.type??"upstream_error",code:D.code??null}})}
|
|
52
53
|
|
|
53
|
-
`);return}}let
|
|
54
|
+
`);return}}let P=Vo(Me(k)),L=dt(h,O.size+P.length,w);if(L){o.streamError=!0,T(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ut(f,L)}})}
|
|
54
55
|
|
|
55
|
-
`);return}A?.flush(),O.size===0&&
|
|
56
|
+
`);return}A?.flush(),O.size===0&&P.length>0&&n.write(`data: ${JSON.stringify(mt(d,u,{tool_calls:P},null))}
|
|
56
57
|
|
|
57
|
-
`);let N=O.size>0||
|
|
58
|
+
`);let N=O.size>0||P.length>0;n.write(`data: ${JSON.stringify(mt(d,u,{},N?"tool_calls":"stop"))}
|
|
58
59
|
|
|
59
|
-
`);let V=
|
|
60
|
+
`);let V=Sr(Me(k));gt(o,Me(k)),V&&n.write(`data: ${JSON.stringify({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:u,choices:[],usage:Rl(Me(k))})}
|
|
60
61
|
|
|
61
62
|
`),n.write(`data: [DONE]
|
|
62
63
|
|
|
63
|
-
`),n.end();return}finally{A?.flush(),A?.dispose()}}let _="",R="",v=[],b=new
|
|
64
|
+
`),n.end();return}finally{A?.flush(),A?.dispose()}}let _="",R="",v=[],b=new We;for await(let k of r.track(m,f,o)){v.push(k),k.type==="response.output_text.delta"&&typeof k.delta=="string"&&(_+=k.delta),k.type==="response.reasoning_text.delta"&&typeof k.delta=="string"&&(R+=k.delta);let O=It(k);if(O&&b.add(O),k.type==="error"){Yo(n,k,{inferenceId:o.id,operatorError:i});return}}let p=Me(v);gt(o,p);let g=Vo(p),y=g.length>0?g:Vo({output:b.items()}),S=dt(h,y.length,_);if(S){X(n,502,ut(f,S),"upstream_error");return}let x=y.map(({index:k,...O})=>O),E={role:"assistant",content:_||null},I=R||xl(p);I&&(E.reasoning_content=I),x.length>0&&(E.tool_calls=x),pe(n,200,{id:d,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:u,choices:[{index:0,message:E,finish_reason:x.length>0?"tool_calls":"stop"}],usage:Rl(p)})}var Ar="sense-latest";async function ff(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){X(n,400,"systemone requires a JSON object body");return}delete t.key;let i=typeof t.model=="string"&&t.model?t.model:Ar,a=me({model:i});if(o.model=a,o.stream=!1,t.state===void 0||t.state===null){X(n,400,"systemone requires a state (string or JSON structure)");return}let l=t.questions;if(l===null||typeof l!="object"||Array.isArray(l)||Object.keys(l).length===0){X(n,400,"systemone requires a questions object (question id -> {kind, options, ...})");return}if(t.media!==void 0&&!Array.isArray(t.media)){X(n,400,"systemone media, when present, must be an array");return}let u=await Al(t,i,a,e,n,r,o,s);u!==null&&pe(n,200,u.answer)}async function Al(t,e,n,r,o,s,i,a){let l={resolve_ms:null,dial_ms:null,first_event_ms:null,stream_ms:null,question_fwd_ms:null,head_ms:null};i.decision=l;let u=performance.now();s.model(n),await xr(i,r,e),l.resolve_ms=Math.round(performance.now()-u);let d,c=performance.now();try{d=await r.createResponse({model:e,input:[{role:"user",content:JSON.stringify(t)}],stream:!0},ve(i))}catch(v){if(v instanceof W)return Bt(o,"openai",v),null;if(v instanceof Ae||v instanceof ue)return o.setHeader("retry-after","2"),X(o,503,v.message,"capacity_error"),null;throw v}l.dial_ms=Math.round(performance.now()-c);let f=[],h=null;try{for await(let v of s.track(d,n,i))if(h===null&&(h=performance.now(),l.first_event_ms=Math.round(h-c)),f.push(v),v.type==="error")return Yo(o,v,{inferenceId:i.id,operatorError:a}),null}catch(v){if(v instanceof W)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),Bt(o,"openai",v),null;if(v instanceof Ae||v instanceof ue)return h!==null&&(l.stream_ms=Math.round(performance.now()-h)),o.setHeader("retry-after","2"),X(o,503,v.message,"capacity_error"),null;throw h!==null&&(l.stream_ms=Math.round(performance.now()-h)),v}h!==null&&(l.stream_ms=Math.round(performance.now()-h));let m=Me(f);if(m==null)return X(o,502,"upstream produced no response.completed event","upstream_error"),null;gt(i,m);let _=Ot(f,m),R;try{R=JSON.parse(_)}catch{return X(o,502,"systemone answer was not valid JSON","upstream_error"),null}if(R===null||typeof R!="object"||Array.isArray(R))return X(o,502,"systemone answer was not a JSON object","upstream_error"),null;if(typeof R=="object"&&R!==null&&!Array.isArray(R)&&"timing"in R){let v=R.timing;if(typeof v=="object"&&v!==null&&!Array.isArray(v)&&"question_fwd_ms"in v&&"head_ms"in v){let b=p=>typeof p=="number"&&Number.isFinite(p)&&p>=0?Math.round(p):null;l.question_fwd_ms=b(v.question_fwd_ms),l.head_ms=b(v.head_ms)}}return{answer:R,completed:m}}async function mf(t,e,n,r,o,s){if(t===null||typeof t!="object"||Array.isArray(t)){X(n,400,"decisions requires a JSON object body");return}let i=typeof t.model=="string"&&t.model?t.model:Ar,a=me({model:i});o.model=a,o.stream=!1;let l;try{l=Sa(t,i)}catch(f){if(f instanceof F){X(n,400,f.message);return}throw f}let u=await Al(l.systemone,i,a,e,n,r,o,s);if(u===null)return;let d;try{d=Ea(l.specs,u.answer)}catch(f){if(f instanceof Re){X(n,502,f.message,"upstream_error");return}throw f}let c=u.completed.usage;pe(n,200,{model:i,answers:d,...c===void 0?{}:{usage:c}})}function gf(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var Tn=class extends Error{};function Rr(t){return new Tn(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function hf(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 yf(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 Tn(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function wf(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Rr(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Rr(`tool_result > ${r}`);e+=String(n.text??"")}return e}function _f(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 Rr(typeof n);let r=[],o="",s=()=>{o&&(r.push({role:e,content:o}),o="")};for(let i of n){let a=String(i.type??"");if(a==="text")o+=String(i.text??"");else if(a==="tool_use")s(),r.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})});else if(a==="tool_result")s(),r.push({type:"function_call_output",call_id:i.tool_use_id,output:wf(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Rr(a)}}return s(),r}function Ko(t){return At(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 vf(t,e,n,r,o,s){let i=t.messages;if(!Array.isArray(i)){Ce(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){Ce(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){Ce(n,400,"invalid_request_error","top_k is not supported: the uRun serve lane exposes temperature/top_p/stop_sequences only");return}if(t.stop_sequences!==void 0&&(!Array.isArray(t.stop_sequences)||t.stop_sequences.some(E=>typeof E!="string"))){Ce(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let a=String(t.model??"urun"),l=Xi(o.id),u=[],d;try{t.system&&u.push({role:"system",content:gf(t.system)});for(let E of i)u.push(..._f(E));d=yf(t.tool_choice)}catch(E){if(E instanceof Tn){Ce(n,400,"invalid_request_error",E.message);return}throw E}let c=me(t);r.model(c),o.model=c,o.stream=t.stream===!0,await xr(o,e,typeof t.model=="string"?t.model:void 0);let f=Array.isArray(t.tools)&&t.tools.length>0,h;try{h=await e.createResponse({model:t.model,input:u,stream:!0,tools:hf(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ve(o))}catch(E){if(E instanceof W){Bt(n,"anthropic",E);return}if(E instanceof Ae||E instanceof ue){n.setHeader("retry-after","2"),Ce(n,503,"capacity_error",E.message);return}throw E}let m=(E,I)=>{n.destroyed||n.write(`event: ${E}
|
|
64
65
|
data: ${JSON.stringify({type:E,...I})}
|
|
65
66
|
|
|
66
|
-
`)};if(t.stream===!0){let E=r.track(h,c,o);Vo(n),m("message_start",{message:{id:l,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let I=0,k="",O=0,w="none",A=()=>w,P=-1,T=-1,L=new Ge,N=[],V=()=>{w!=="none"&&(w="none",m("content_block_stop",{index:P}))},H=(Q,re)=>{V(),w=Q,P=O++,m("content_block_start",{index:P,content_block:re})};for await(let Q of E){if(n.destroyed)break;N.push(Q);let re=Et(Q);if(Q.type==="response.reasoning_text.delta"&&typeof Q.delta=="string")A()!=="thinking"&&H("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:P,delta:{type:"thinking_delta",thinking:Q.delta}});else if(Q.type==="response.output_text.delta"&&typeof Q.delta=="string")A()!=="text"&&H("text",{type:"text",text:""}),I+=1,k+=Q.delta,m("content_block_delta",{index:P,delta:{type:"text_delta",text:Q.delta}});else if(re){let{call:Ee}=L.add(re);(A()!=="tool"||re.tool_index!==T)&&(T=re.tool_index,H("tool",{type:"tool_use",id:Ee.id??`call_${re.tool_index}`,name:Ee.name??"",input:{}})),re.delta&&m("content_block_delta",{index:P,delta:{type:"input_json_delta",partial_json:re.delta}})}else if(Q.type==="error"){o.streamError=!0;let Ee=Q.error,Xe=Me(Ee);Xe===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Q)}`),m("error",{error:{type:"api_error",message:Xe??Te(o.id)}}),n.end();return}}if(n.destroyed)return;let Y=$e(N),D=Rt(Y),j=at(f,L.size+D.length,k);if(j){o.streamError=!0,m("error",{error:{type:"api_error",message:it(c,j)}}),n.end();return}V();let K=[];if(L.size===0)try{K=Jo(Y)}catch(Q){o.streamError=!0;let re=we(Q,{inferenceId:o.id});re.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Q instanceof Error?Q.message:Q)}`),m("error",{error:{type:"api_error",message:re.message}}),n.end();return}O===0&&K.length===0&&(H("text",{type:"text",text:""}),V()),K.forEach(Q=>{let re=O++;m("content_block_start",{index:re,content_block:{...Q,input:{}}}),m("content_block_delta",{index:re,delta:{type:"input_json_delta",partial_json:JSON.stringify(Q.input??{})}}),m("content_block_stop",{index:re})});let Ye=L.size>0||K.length>0,yt=br(Y);pt(o,Y),m("message_delta",{delta:{stop_reason:Ye?"tool_use":"end_turn"},usage:yt?{input_tokens:yt.input_tokens,output_tokens:yt.output_tokens}:{output_tokens:I}}),m("message_stop",{}),n.end();return}let _="",R="",v=[],b=new Ge;for await(let E of r.track(h,c,o)){v.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(_+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(R+=E.delta);let I=Et(E);if(I&&b.add(I),E.type==="error"){let k=E.error,O=k?.type==="invalid_request_error",w=Me(k);w===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(E)}`),Ce(n,O?400:502,O?"invalid_request_error":"api_error",w??Te(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let p=$e(v);pt(o,p);let g;try{g=Jo(p),g.length===0&&b.size>0&&(g=Jo({output:b.items()}))}catch(E){let I=we(E,{inferenceId:o.id});I.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(E instanceof Error?E.message:E)}`),Ce(n,502,"api_error",I.message);return}let y=at(f,g.length,_);if(y){Ce(n,502,"api_error",it(c,y));return}let S=[],x=R||El(p);x&&S.push({type:"thinking",thinking:x}),(_||g.length===0)&&S.push({type:"text",text:_}),S.push(...g),pe(n,200,{id:l,type:"message",role:"assistant",content:S,model:a,stop_reason:g.length>0?"tool_use":"end_turn",usage:br(p)??{input_tokens:0,output_tokens:0}})}function vf(t){Ve(process.stdout,t)}function Al(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??vf,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new ot;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),h=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),m=(p,g,y,S,x)=>h?Ce(c,p,S,g):X(c,p,g,y,x),_=wo(f.pathname),R=f.pathname.startsWith("/partners/"),v=_||R?{id:rt(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;v&&(c.setHeader(Vi,v.id),c.once("close",()=>{let p=Xi({turn:v,method:d.method??"",path:f.pathname,res:c});i(Qi(p)),l?.(p),vr({record:p,ledger:t.ledger??null,req:d})}));let b=()=>Ki(f.pathname,v);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){pe(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){pe(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let p=f.pathname===wr?"canonical":f.pathname===Rn?"huggingface":null;if(p){if(d.method!=="POST"){m(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let x=t.usage;if(!x){m(501,`${f.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let E=x.authorize(d),I;try{I=await Sl(d,il)}catch(w){if(w instanceof On){m(413,w.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=w=>x.lookup(E,w),O;try{if(p==="canonical"){let w=al(I),A=await k(w);_r(A,w),O={requests:A}}else O=await dl(I,k)}catch(w){if(w instanceof Ke){m(w.status,w.message,"invalid_request_error","invalid_request_error");return}throw w}pe(c,200,O);return}if(d.method==="GET"&&f.pathname===et){let x=await s(d);if(v&&(v.org=x.tenant??null),!x.openRouterModels){m(501,`GET ${et} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}pe(c,200,await x.openRouterModels());return}if(f.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${Rn} and GET ${et}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(v&&(v.org=g.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:et}),c.end();return}pe(c,200,await g.listModels());return}if(d.method==="GET"&&f.pathname===Aa){if(!g.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}pe(c,200,await g.listImageModels());return}if(xa(f.pathname)){if(!g.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let x={clients:g,imageModels:g.supportsImages,stats:u,turn:b(),operatorLog:a};f.pathname===pr?await Ua(d,c,x):await Na(d,c,x);return}if(d.method==="GET"&&f.pathname===Qa){if(!g.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}pe(c,200,await g.listSpeechToTextModels());return}if(Xa(f.pathname)){if(!g.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${hr}`,"not_implemented","not_implemented_error");return}let x={clients:g,transcriptionModels:g.supportsTranscription,stats:u,turn:b(),operatorLog:a};await tl(d,c,x);return}if(Ja(f.pathname)){if(!g.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${kn}`,"not_implemented","not_implemented_error");return}let x={clients:g,speechModels:g.supportsSpeech,stats:u,turn:b(),operatorLog:a};await Ya(d,c,x);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await Sl(d)}catch(x){if(x instanceof On){m(413,x.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let S=Buffer.byteLength(JSON.stringify(y));if(f.pathname==="/v1/responses"){u.request("responses",S,S),await df(y,g,mn(g),c,u,b(),a);return}if(f.pathname==="/v1/chat/completions"){u.request("chat_completions",S,S),await cf(y,g,c,u,b(),d.headers[Go],a);return}if(f.pathname==="/v1/systemone"){u.request("systemone",S,S),await pf(y,g,c,u,b(),a);return}if(f.pathname==="/v1/decisions"){u.request("decisions",S,S),await ff(y,g,c,u,b(),a);return}if(f.pathname==="/v1/messages"){u.request("messages",S,S),await _f(y,g,c,u,b(),a);return}if(f.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",S,S),Ce(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let g=String(p instanceof Error?p.message:p);if(!c.headersSent){let x=o?.(p)??null;if(x){x.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${x.operatorDetail}`),m(x.status,g,x.openaiType,x.anthropicType,x.code);return}if(p instanceof Rr.SessionAllocationError){let I=Zn(p.code);if(I){let k=p.retryAfterSeconds??(I.status===429?30:void 0);k!==void 0&&c.setHeader("Retry-After",String(k)),m(I.status,yn(I,p.code??void 0),I.openaiType,I.anthropicType,I.code);return}}if(p instanceof Rr.SessionFailedError){let I=er(p);if(I){let k=I.status===429?30:void 0;k!==void 0&&c.setHeader("Retry-After",String(k)),m(I.status,yn(I,p.status.sessionId?`session ${p.status.sessionId}`:void 0),I.openaiType,I.anthropicType,I.code);return}}if(p instanceof oe){m(502,g,"upstream_error","api_error");return}if(p instanceof Ae){p.retryable&&c.setHeader("Retry-After","1");let I=we(p,{inferenceId:v?.id??null});I.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:Ie(p)}`),m(502,I.message,"upstream_error","api_error",p.code);return}if(p instanceof We){c.setHeader("Retry-After",String(p.retryAfterSeconds)),m(p.status,g,p.status===429?"capacity_error":"upstream_error",p.status===429?"rate_limit_error":"overloaded_error",p.code);return}let E=we(p,{inferenceId:v?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:Ie(p)}`),m(500,E.message,"proxy_error","api_error","proxy_error");return}v&&(v.streamError=!0);let y=p instanceof Ae?p.code:null,S=we(p,{inferenceId:v?.id??null});S.redacted&&a(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:Ie(p)}`),c.destroyed||(h?c.write(`event: error
|
|
67
|
+
`)};if(t.stream===!0){let E=r.track(h,c,o);zo(n),m("message_start",{message:{id:l,type:"message",role:"assistant",content:[],model:a,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let I=0,k="",O=0,w="none",A=()=>w,T=-1,P=-1,L=new We,N=[],V=()=>{w!=="none"&&(w="none",m("content_block_stop",{index:T}))},H=(Q,re)=>{V(),w=Q,T=O++,m("content_block_start",{index:T,content_block:re})};for await(let Q of E){if(n.destroyed)break;N.push(Q);let re=It(Q);if(Q.type==="response.reasoning_text.delta"&&typeof Q.delta=="string")A()!=="thinking"&&H("thinking",{type:"thinking",thinking:""}),m("content_block_delta",{index:T,delta:{type:"thinking_delta",thinking:Q.delta}});else if(Q.type==="response.output_text.delta"&&typeof Q.delta=="string")A()!=="text"&&H("text",{type:"text",text:""}),I+=1,k+=Q.delta,m("content_block_delta",{index:T,delta:{type:"text_delta",text:Q.delta}});else if(re){let{call:xe}=L.add(re);(A()!=="tool"||re.tool_index!==P)&&(P=re.tool_index,H("tool",{type:"tool_use",id:xe.id??`call_${re.tool_index}`,name:xe.name??"",input:{}})),re.delta&&m("content_block_delta",{index:T,delta:{type:"input_json_delta",partial_json:re.delta}})}else if(Q.type==="error"){o.streamError=!0;let xe=Q.error,Ze=Ne(xe);Ze===null&&s(`[caller-message-boundary] anthropic stream terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(Q)}`),m("error",{error:{type:"api_error",message:Ze??Te(o.id)}}),n.end();return}}if(n.destroyed)return;let Y=Me(N),D=At(Y),j=dt(f,L.size+D.length,k);if(j){o.streamError=!0,m("error",{error:{type:"api_error",message:ut(c,j)}}),n.end();return}V();let K=[];if(L.size===0)try{K=Ko(Y)}catch(Q){o.streamError=!0;let re=we(Q,{inferenceId:o.id});re.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(Q instanceof Error?Q.message:Q)}`),m("error",{error:{type:"api_error",message:re.message}}),n.end();return}O===0&&K.length===0&&(H("text",{type:"text",text:""}),V()),K.forEach(Q=>{let re=O++;m("content_block_start",{index:re,content_block:{...Q,input:{}}}),m("content_block_delta",{index:re,delta:{type:"input_json_delta",partial_json:JSON.stringify(Q.input??{})}}),m("content_block_stop",{index:re})});let Qe=L.size>0||K.length>0,vt=Sr(Y);gt(o,Y),m("message_delta",{delta:{stop_reason:Qe?"tool_use":"end_turn"},usage:vt?{input_tokens:vt.input_tokens,output_tokens:vt.output_tokens}:{output_tokens:I}}),m("message_stop",{}),n.end();return}let _="",R="",v=[],b=new We;for await(let E of r.track(h,c,o)){v.push(E),E.type==="response.output_text.delta"&&typeof E.delta=="string"&&(_+=E.delta),E.type==="response.reasoning_text.delta"&&typeof E.delta=="string"&&(R+=E.delta);let I=It(E);if(I&&b.add(I),E.type==="error"){let k=E.error,O=k?.type==="invalid_request_error",w=Ne(k);w===null&&s(`[caller-message-boundary] anthropic terminal error event carried no safe caller message; full event withheld from the caller: ${JSON.stringify(E)}`),Ce(n,O?400:502,O?"invalid_request_error":"api_error",w??Te(o.id));return}if(n.destroyed)break}if(n.destroyed)return;let p=Me(v);gt(o,p);let g;try{g=Ko(p),g.length===0&&b.size>0&&(g=Ko({output:b.items()}))}catch(E){let I=we(E,{inferenceId:o.id});I.redacted&&s(`[caller-message-boundary] anthropic tool-block parse failure withheld from the caller: ${String(E instanceof Error?E.message:E)}`),Ce(n,502,"api_error",I.message);return}let y=dt(f,g.length,_);if(y){Ce(n,502,"api_error",ut(c,y));return}let S=[],x=R||xl(p);x&&S.push({type:"thinking",thinking:x}),(_||g.length===0)&&S.push({type:"text",text:_}),S.push(...g),pe(n,200,{id:l,type:"message",role:"assistant",content:S,model:a,stop_reason:g.length>0?"tool_use":"end_turn",usage:Sr(p)??{input_tokens:0,output_tokens:0}})}function bf(t){Ke(process.stdout,t)}function Il(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??bf,a=t.operatorLog??(d=>console.error(d)),l=t.observe,u=new at;return(d,c)=>{let f=new URL(d.url??"/","http://localhost"),h=f.pathname==="/v1/messages"||f.pathname.startsWith("/v1/messages/"),m=(p,g,y,S,x)=>h?Ce(c,p,S,g):X(c,p,g,y,x),_=_o(f.pathname),R=f.pathname.startsWith("/partners/"),v=_||R?{id:it(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,outputMinutes:null,outputSeconds:null,sessionId:null,timing:null}:null;v&&(c.setHeader(Ki,v.id),c.once("close",()=>{let p=Qi({turn:v,method:d.method??"",path:f.pathname,res:c});i(Zi(p)),l?.(p),br({record:p,ledger:t.ledger??null,req:d})}));let b=()=>zi(f.pathname,v);(async()=>{if(d.method==="GET"&&f.pathname==="/healthz"){pe(c,200,{ok:!0});return}if(d.method==="GET"&&f.pathname==="/stats"){pe(c,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){m(401,"invalid local proxy api key","authentication_error","authentication_error");return}let p=f.pathname===_r?"canonical":f.pathname===Rn?"huggingface":null;if(p){if(d.method!=="POST"){m(405,`${f.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let x=t.usage;if(!x){m(501,`${f.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let E=x.authorize(d),I;try{I=await kl(d,al)}catch(w){if(w instanceof On){m(413,w.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let k=w=>x.lookup(E,w),O;try{if(p==="canonical"){let w=ll(I),A=await k(w);vr(A,w),O={requests:A}}else O=await cl(I,k)}catch(w){if(w instanceof Ye){m(w.status,w.message,"invalid_request_error","invalid_request_error");return}throw w}pe(c,200,O);return}if(d.method==="GET"&&f.pathname===nt){let x=await s(d);if(v&&(v.org=x.tenant??null),!x.openRouterModels){m(501,`GET ${nt} needs a router-backed client (openRouterModels)`,"not_implemented","not_implemented_error");return}pe(c,200,await x.openRouterModels());return}if(f.pathname.startsWith("/partners/")){m(404,`no partner adapter for ${d.method} ${f.pathname} \u2014 the partner surface currently carries ${Rn} and GET ${nt}`,"invalid_request_error","not_found_error");return}let g=await s(d);if(v&&(v.org=g.tenant??null),d.method==="GET"&&f.pathname==="/v1/models"){if(f.searchParams.get("format")==="openrouter"){c.writeHead(308,{location:nt}),c.end();return}pe(c,200,await g.listModels());return}if(d.method==="GET"&&f.pathname===Ia){if(!g.listImageModels){m(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}pe(c,200,await g.listImageModels());return}if(Aa(f.pathname)){if(!g.supportsImages){m(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${f.pathname}`,"not_implemented","not_implemented_error");return}let x={clients:g,imageModels:g.supportsImages,stats:u,turn:b(),operatorLog:a};f.pathname===fr?await Da(d,c,x):await Ua(d,c,x);return}if(d.method==="GET"&&f.pathname===Za){if(!g.listSpeechToTextModels){m(501,"GET /v1/audio/models needs a router-backed client (listSpeechToTextModels)","not_implemented","not_implemented_error");return}pe(c,200,await g.listSpeechToTextModels());return}if(Qa(f.pathname)){if(!g.supportsTranscription){m(501,`the transcription lane needs a router-backed client (supportsTranscription) to gate model capability for ${yr}`,"not_implemented","not_implemented_error");return}let x={clients:g,transcriptionModels:g.supportsTranscription,stats:u,turn:b(),operatorLog:a};await nl(d,c,x);return}if(Va(f.pathname)){if(!g.supportsSpeech){m(501,`the speech lane needs a router-backed client (supportsSpeech) to gate model capability for ${kn}`,"not_implemented","not_implemented_error");return}let x={clients:g,speechModels:g.supportsSpeech,stats:u,turn:b(),operatorLog:a};await Xa(d,c,x);return}if(d.method!=="POST"){m(404,`no route for ${d.method} ${f.pathname}`,"invalid_request_error","not_found_error");return}let y;try{y=await kl(d)}catch(x){if(x instanceof On){m(413,x.message,"request_too_large","request_too_large");return}m(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let S=Buffer.byteLength(JSON.stringify(y));if(f.pathname==="/v1/responses"){u.request("responses",S,S),await cf(y,g,mn(g),c,u,b(),a);return}if(f.pathname==="/v1/chat/completions"){u.request("chat_completions",S,S),await pf(y,g,c,u,b(),d.headers[Jo],a);return}if(f.pathname==="/v1/systemone"){u.request("systemone",S,S),await ff(y,g,c,u,b(),a);return}if(f.pathname==="/v1/decisions"){u.request("decisions",S,S),await mf(y,g,c,u,b(),a);return}if(f.pathname==="/v1/messages"){u.request("messages",S,S),await vf(y,g,c,u,b(),a);return}if(f.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",S,S),Ce(c,404,"not_found_error","token counting (count_tokens) is not supported on this endpoint");return}m(404,`no route for POST ${f.pathname}`,"invalid_request_error","not_found_error")})().catch(p=>{let g=String(p instanceof Error?p.message:p);if(!c.headersSent){let x=o?.(p)??null;if(x){x.operatorDetail!==void 0&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} classified failure; detail withheld from the caller: ${x.operatorDetail}`),m(x.status,g,x.openaiType,x.anthropicType,x.code);return}if(p instanceof Er.SessionAllocationError){let I=er(p.code);if(I){let k=p.retryAfterSeconds??(I.status===429?30:void 0);k!==void 0&&c.setHeader("Retry-After",String(k)),m(I.status,yn(I,p.code??void 0),I.openaiType,I.anthropicType,I.code);return}}if(p instanceof Er.SessionFailedError){let I=tr(p);if(I){let k=I.status===429?30:void 0;k!==void 0&&c.setHeader("Retry-After",String(k)),m(I.status,yn(I,p.status.sessionId?`session ${p.status.sessionId}`:void 0),I.openaiType,I.anthropicType,I.code);return}}if(p instanceof oe){m(502,g,"upstream_error","api_error");return}if(p instanceof Ie){p.retryable&&c.setHeader("Retry-After","1");let I=we(p,{inferenceId:v?.id??null});I.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} pre-head decision stream failure; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:ke(p)}`),m(502,I.message,"upstream_error","api_error",p.code);return}if(p instanceof Je){c.setHeader("Retry-After",String(p.retryAfterSeconds)),m(p.status,g,p.status===429?"capacity_error":"upstream_error",p.status===429?"rate_limit_error":"overloaded_error",p.code);return}let E=we(p,{inferenceId:v?.id??null});E.redacted&&a(`[caller-message-boundary] ${d.method??""} ${f.pathname} failed; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:ke(p)}`),m(500,E.message,"proxy_error","api_error","proxy_error");return}v&&(v.streamError=!0);let y=p instanceof Ie?p.code:null,S=we(p,{inferenceId:v?.id??null});S.redacted&&a(`[caller-message-boundary] the stream for ${f.pathname} failed after the head went out; raw error withheld from the caller: ${p instanceof Error?`${p.name}: ${p.message}`:ke(p)}`),c.destroyed||(h?c.write(`event: error
|
|
67
68
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:S.message}})}
|
|
68
69
|
|
|
69
70
|
`):c.write(`data: ${JSON.stringify({error:{message:S.message,type:"upstream_error",code:y}})}
|
|
70
71
|
|
|
71
|
-
`)),c.end()})}}var Fe=(t,e)=>Object.assign(new Error(e),{status:t}),kf='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Yo=(t,e,n)=>new q(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),zo=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof W?Fe(404,n.message):n}};async function Il(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Fe(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${kf}`);if(o==="transcription")throw Fe(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!t.openAudioOn)throw Fe(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 Fe(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof W?Fe(404,h.message):h}if(!f)throw Fe(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof W?Fe(404,h.message):h}if(f!=="stt")throw Fe(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await zo(t,n.stt),i=await zo(t,e),a=await zo(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,Rf({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof q?Yo("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Xo(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Ar=class extends Error{};async function*Rf(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,_=null,R=[],v=null,b=new Promise((O,w)=>{n&&n.addEventListener("abort",()=>w(new Ar),{once:!0})}),p=()=>h||n?.aborted===!0,g=async O=>{if(p())return;let w;try{w=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:O}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch(P){throw P instanceof q?Yo("tts",l.tts,P):P}let A=w[Symbol.asyncIterator]();_=A;try{for(;;){let P=A.next(),T;try{T=await Promise.race([P,b])}catch(N){if(P.catch(()=>{}),N instanceof Ar)return;throw N}if(T.done)return;let L=T.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(l.tts)}) errored: ${N}`)}if(L.type==="response.completed")return}}finally{_===A&&(_=null)}},y=async()=>{for(;R.length>0&&!p();){let O=R.shift();await g(O)}},S=O=>{if(O===""||p()||(R.push(O),v!==null))return;let w=y();v=w,w.then(()=>{v===w&&(v=null)},A=>{v===w&&(v=null),m??=A})},x=()=>{h=!0,R.length=0;let O=_;if(_=null,O){let w=O.return?.();w&&w.catch(()=>{})}},E=async()=>{for(;R.length>0||v!==null;){let O=v;if(O===null){await g(R.shift());continue}await O}},I=f?new Nt({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},O=>S(O)):null,k=null;try{let O;try{O=await o.createResponseOn(s,d)}catch(w){throw w instanceof q?Yo("chat",a,w):w}for await(let w of O){if(p())return;let A=w;if(A.type==="error"){yield w;return}if(A.type==="response.output_text.delta"&&typeof A.delta=="string"){yield w,I?.push(A.delta);continue}if(A.type==="response.function_call_arguments.delta"){I?.flush(),yield w;continue}if(A.type==="response.completed"){k=w.response;continue}}I?.flush(),I?.dispose(),f&&await E(),k!==null&&(yield{type:"response.completed",response:k})}finally{I?.dispose(),x();try{if(m instanceof q)throw m}finally{r?.()}}}var Re=(t,e)=>Object.assign(new Error(e),{status:t});function Tl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Pl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function Cl(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var Ef='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function Ll(t,e,n,r,o){if(!t.supportsAudio)throw Re(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(h){throw h instanceof W?Re(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof W?Re(404,m.message):m}if(h!==null)return await Il(t,e,h,n,r);throw Re(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 Re(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(h){throw h instanceof W?Re(404,h.message):h}if(i&&!t.openTurnsOn)throw Re(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 h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof W?Re(404,m.message):m}if(h!=="stt")throw Re(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \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 Re(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${Ef}`);if(r==="transcription"&&!i)throw Re(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 a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof ue?Re(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,Ol.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}var eu=require("@urun-sh/core"),tu=require("@urun-sh/core/internal"),nu=fe(require("ws"),1);var Ul=require("http");var xf=require("@urun-sh/core"),Af=require("bullmq"),If=require("crypto");var $l=12e4;var Of="/pooler/v1/lanes/pick",Tf="/pooler/v1/lanes/status",Pf=1e4,Pn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function Ml(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,Ul.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",i)});u.on("timeout",()=>{u.destroy(new Pn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",i),u.end(l)})}function Nl(t,e,n){if(t===503)return new ue(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function Dl(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,model:s,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),$l),l=await Ml(t,"POST",Of,{pool:e,app:n,fn:r,model:s,hold_ms:a,...o?{shared_app:!0}:{}},a+Pf);if(l.status!==200)throw Nl(l.status,l.json,e);return(l.json?.lanes??[]).filter(d=>typeof d.lane_id=="string"&&d.lane_id!==""&&typeof d.host=="string"&&d.host!=="").map(d=>({laneId:d.lane_id,host:d.host}))},async status(){let e=await Ml(t,"GET",Tf,void 0,5e3);if(e.status!==200)throw Nl(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}async function Fl(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 Bl(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 Ir(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 Hl(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 jl=require("@urun-sh/core/internal");function ql(t,e){let n=t.delete;if(typeof n=="function"){(0,jl.gcRequest)({get:r=>t.get(r),delete:r=>n.call(t,r),on:(r,o)=>t.on(r,o)},e);return}t.set({requests:{[e]:null}})}var Cf="llm-resp";async function*Tr(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 a=typeof i.index=="number"?i.index:0,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.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 Hl(s);return}}}async function*Qo(t,e){let n=`${Cf}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Tr(e,t.stream(n).messages())}finally{try{ql(t.doc("llm"),e)}catch{}}}var Pr=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=Ir(e,n,this.consumerId);return this.write(r),Qo(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Bl(e,n,r,this.consumerId);return this.write(o),Qo(this.session,r)})}async writeGated(e,n){try{await Fl(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 Gl=0;function $f(){return Gl+=1,`req_${Date.now().toString(36)}_${Gl.toString(36)}`}var ft=class{transport;constructor(e,n){this.transport=new Pr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=$f(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var Dt=fe(require("yjs"),1),Wl=require("@urun-sh/core/internal"),Mf=3e4;function Nf(t){return(e,n,r)=>{let o=t(e);Dt.applyUpdate(n,Dt.encodeStateAsUpdate(o));let s=a=>Dt.applyUpdate(o,a),i=a=>Dt.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function Zo(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Nf(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new Wl.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??Mf;await new Promise((h,m)=>{let _=setTimeout(()=>{R(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),R=c.onSynced(()=>{clearTimeout(_),d?.signal?.removeEventListener("abort",v),h()}),v=()=>{clearTimeout(_),R(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",v,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}var mt=fe(require("ws"),1),gt=require("@urun-sh/core"),Jl="/stream/";function Vl(t){if(!t.startsWith(Jl))return null;let e=t.slice(Jl.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function $r(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Cr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>gt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Lr=class{reassembler=new gt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===gt.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},ts=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;a.bytes+o.byteLength>Kl&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Kl} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Kl=8*1024*1024,Ne=new ts;function zl(t,e){let n=new Lr,r={send(o){Ne.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Cr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),Ne.detach(t,e,r)}};return Ne.attach(t,e,r),r}function Uf(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function Yl(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new mt.default(r,$r(e)),s=new Lr;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Cr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Cr(i),o.readyState!==mt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function es(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
|
|
72
|
+
`)),c.end()})}}var Be=(t,e)=>Object.assign(new Error(e),{status:t}),Rf='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Qo=(t,e,n)=>new q(`the composite ${t} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${n instanceof Error?n.message:String(n)}`),Xo=async(t,e)=>{try{return await t.sessionHandle(e)}catch(n){throw n instanceof W?Be(404,n.message):n}};async function Ol(t,e,n,r,o){if(o!==void 0&&o!=="transcription")throw Be(400,`intent ${JSON.stringify(o)} is not supported on this realtime lane \u2014 accepted values: ${Rf}`);if(o==="transcription")throw Be(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 Be(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 Be(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(t.supportsTranscription){let f;try{f=await t.supportsTranscription(n.stt)}catch(h){throw h instanceof W?Be(404,h.message):h}if(!f)throw Be(501,`the configured stt companion ${JSON.stringify(n.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(t.transcriptStreamFor){let f;try{f=await t.transcriptStreamFor(n.stt)}catch(h){throw h instanceof W?Be(404,h.message):h}if(f!=="stt")throw Be(501,`the configured stt companion ${JSON.stringify(n.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(f)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let s=await Xo(t,n.stt),i=await Xo(t,e),a=await Xo(t,n.tts),l=await t.openAudioOn(s,r),u=await t.openAudioOn(a,r),d=null,c={clients:{createResponse:f=>{let h=new AbortController;return d=h,Ef({clients:t,chatHandle:i,ttsHandle:a,chatModel:e,companions:n},f,h.signal,()=>{d===h&&(d=null)})}},cancelActiveTurn:()=>{let f=d;d=null,f?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:f=>{l.appendInputAudio(f)},onOutputAudio:f=>u.onOutputAudio(f),sessionId:u.sessionId}},turns:async function*(f){try{yield*t.openTurnsOn(s,f)}catch(h){throw h instanceof q?Qo("stt",n.stt,h):h}},composite:!0};return e!==void 0&&(c.model=e),c}function Zo(t,e){return Object.assign(Object.create(t),{realtimeCompanionsFor:e??(async()=>null)})}var Ir=class extends Error{};async function*Ef(t,e,n,r){let{clients:o,chatHandle:s,ttsHandle:i,chatModel:a,companions:l}=t;if(n?.aborted){r?.();return}let{output_modalities:u,...d}=e,c=e.output_modalities,f=!Array.isArray(c)||c.includes("audio"),h=!1,m=null,_=null,R=[],v=null,b=new Promise((O,w)=>{n&&n.addEventListener("abort",()=>w(new Ir),{once:!0})}),p=()=>h||n?.aborted===!0,g=async O=>{if(p())return;let w;try{w=await o.createResponseOn(i,{model:l.tts,input:[{role:"user",content:[{type:"input_text",text:O}]}],stream:!1,...l.voice!==void 0?{voice:l.voice}:{}})}catch(T){throw T instanceof q?Qo("tts",l.tts,T):T}let A=w[Symbol.asyncIterator]();_=A;try{for(;;){let T=A.next(),P;try{P=await Promise.race([T,b])}catch(N){if(T.catch(()=>{}),N instanceof Ir)return;throw N}if(P.done)return;let L=P.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(l.tts)}) errored: ${N}`)}if(L.type==="response.completed")return}}finally{_===A&&(_=null)}},y=async()=>{for(;R.length>0&&!p();){let O=R.shift();await g(O)}},S=O=>{if(O===""||p()||(R.push(O),v!==null))return;let w=y();v=w,w.then(()=>{v===w&&(v=null)},A=>{v===w&&(v=null),m??=A})},x=()=>{h=!0,R.length=0;let O=_;if(_=null,O){let w=O.return?.();w&&w.catch(()=>{})}},E=async()=>{for(;R.length>0||v!==null;){let O=v;if(O===null){await g(R.shift());continue}await O}},I=f?new Ft({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},O=>S(O)):null,k=null;try{let O;try{O=await o.createResponseOn(s,d)}catch(w){throw w instanceof q?Qo("chat",a,w):w}for await(let w of O){if(p())return;let A=w;if(A.type==="error"){yield w;return}if(A.type==="response.output_text.delta"&&typeof A.delta=="string"){yield w,I?.push(A.delta);continue}if(A.type==="response.function_call_arguments.delta"){I?.flush(),yield w;continue}if(A.type==="response.completed"){k=w.response;continue}}I?.flush(),I?.dispose(),f&&await E(),k!==null&&(yield{type:"response.completed",response:k})}finally{I?.dispose(),x();try{if(m instanceof q)throw m}finally{r?.()}}}var Ee=(t,e)=>Object.assign(new Error(e),{status:t});function Pl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}function Cl(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("intent")?.trim();return n===""?void 0:n}function Ll(t){let e=new URL(t.url??"/","http://localhost").searchParams.get("session"),n=t.headers?.["x-urun-session"],r=(e??(typeof n=="string"?n:n?.[0]))?.trim();if(!(r===void 0||r==="")){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r))throw Object.assign(new Error(`invalid realtime session id "${r.slice(0,32)}" \u2014 use at most 128 URL-safe characters ([A-Za-z0-9._:-])`),{status:400});return r}}var xf='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function $l(t,e,n,r,o){if(!t.supportsAudio)throw Ee(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(h){throw h instanceof W?Ee(404,h.message):h}if(!s){let h=null;if(t.realtimeCompanionsFor)try{h=await t.realtimeCompanionsFor(e)}catch(m){throw m instanceof W?Ee(404,m.message):m}if(h!==null)return await Ol(t,e,h,n,r);throw Ee(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 Ee(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(h){throw h instanceof W?Ee(404,h.message):h}if(i&&!t.openTurnsOn)throw Ee(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 h;try{h=await t.transcriptStreamFor(e)}catch(m){throw m instanceof W?Ee(404,m.message):m}if(h!=="stt")throw Ee(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(h)} \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 Ee(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${xf}`);if(r==="transcription"&&!i)throw Ee(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 a;try{a=t.dedicatedSessionHandle?await t.dedicatedSessionHandle(e):await t.sessionHandle(e)}catch(h){throw h instanceof ue?Ee(503,h.message):h}let l=t.realtimeBillingIdentityFor?await t.realtimeBillingIdentityFor(e):null,u=`conn_${(0,Tl.randomUUID)()}`,c={audio:await t.openAudioOn(a,n,u,o).catch(h=>{throw t.releaseSessionHandle?.(a),h})},f={clients:{createResponse:async h=>await t.createResponseOn(a,h,u)},voice:s,audioSession:c};return t.openVideoOn&&(f.video=()=>t.openVideoOn(a,n)),i&&(f.turns=h=>t.openTurnsOn(a,h)),r==="transcription"&&(f.intent="transcription"),t.releaseSessionHandle&&(f.release=()=>t.releaseSessionHandle(a)),e!==void 0&&(f.model=e),l!==null&&(f.catalog=l),f}var ou=require("@urun-sh/core"),su=require("@urun-sh/core/internal"),iu=fe(require("ws"),1);var Wl=require("http");var Fl=require("http");function Ml(t,e,n,r){let o=t.response??{},s={request_id:n,consumer_id:r,stream:!0,kind:"chat",messages:e};return typeof o.instructions=="string"&&(s.instructions=o.instructions),Array.isArray(o.modalities)&&(s.modalities=o.modalities),typeof o.temperature=="number"&&(s.temperature=o.temperature),typeof o.max_output_tokens=="number"&&(s.max_output_tokens=o.max_output_tokens),o.tools!==void 0&&(s.tools=o.tools),s}function Or(t,e,n){let r={request_id:e,consumer_id:n,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(r.model=t.model),t.tools!==void 0&&(r.tools=t.tools),t.tool_choice!==void 0&&(r.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(r.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(r.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(r.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(r.stop=t.stop),typeof t.reasoning_effort=="string"&&(r.reasoning_effort=t.reasoning_effort),typeof t.instructions=="string"&&(r.instructions=t.instructions),t.chat_template_kwargs!==void 0&&(r.chat_template_kwargs=t.chat_template_kwargs),t.response_format!==void 0&&(r.response_format=t.response_format),typeof t.voice=="string"&&(r.voice=t.voice),typeof t.language=="string"&&(r.language=t.language),r}function Nl(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 Ul=require("@urun-sh/core/internal");var Af="llm-resp";async function*Pr(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 a=typeof i.index=="number"?i.index:0,l=r.get(a)??{};i.id&&(l.id=i.id),i.function?.name&&(l.name=i.function.name),r.set(a,l),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${a}`,tool_index:a,call_id:l.id,name:l.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 Nl(s);return}}}async function*es(t,e){let n=`${Af}:${e}`;yield{type:"response.created",response:{id:`resp_${e}`,status:"in_progress"}};try{yield*Pr(e,t.stream(n).messages())}finally{try{(0,Ul.gcRequest)(t.doc("llm"),e)}catch{}}}var If="/pooler/v1/inference",Le=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},Of=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Tf=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},Bl=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Pf=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Bl(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new Le(t.status,e,n,t.retryAfterSeconds)};async function Cf(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${If}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Of(e),firstMessage:Tf(e)}});return new Promise((a,l)=>{let u=(0,Fl.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});u.on("error",d=>l(new Le(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var Dl=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Lf(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
|
|
73
|
+
|
|
74
|
+
`);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=Dl(s);i!==null&&(yield i)}let n=Dl(e);n!==null&&(yield n)}async function Hl(t,e,n,r){let o=Or(e,n,r),s=o.model??"";if(s==="")throw new Le(400,"missing_model","the pooler submit requires a model");let i=await Cf(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Pf(i);let a=e.stream===!0?Pr(n,Lf(i)):await $f(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function $f(t,e){let n=await Bl(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new Le(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Pr(e,(async function*(){yield o})())}var Mf=require("@urun-sh/core"),Nf=require("bullmq"),Uf=require("crypto");var jl=12e4;var Df="/pooler/v1/lanes/pick",Ff="/pooler/v1/lanes/status",Bf=1e4,Pn=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function ql(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=(0,Wl.request)({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),h=null;try{h=f===""?null:JSON.parse(f)}catch{h=null}s({status:d.statusCode??0,json:h})}),d.on("error",f=>i(new Le(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`)))});u.on("timeout",()=>{u.destroy(new Pn(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",d=>i(new Le(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(l)})}function Gl(t,e,n,r){if(t===400&&Hf(e)?.code==="lane_target")return new ct(n,r);if(t===503)return new ue(n);let o=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${o}`)}function Hf(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function Jl(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,model:s,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),jl),l=await ql(t,"POST",Df,{pool:e,app:n,fn:r,model:s,hold_ms:a,...o?{shared_app:!0}:{}},a+Bf);if(l.status!==200)throw Gl(l.status,l.json,e,s);return(l.json?.lanes??[]).filter(d=>typeof d.lane_id=="string"&&d.lane_id!==""&&typeof d.host=="string"&&d.host!=="").map(d=>({laneId:d.lane_id,host:d.host}))},async status(){let e=await ql(t,"GET",Ff,void 0,5e3);if(e.status!==200)throw Gl(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}async function Vl(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 Cr=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=Or(e,n,this.consumerId);return this.write(r),es(this.session,n)})}sendResponseCreate(e,n,r){return this.writeGated(r,()=>{let o=Ml(e,n,r,this.consumerId);return this.write(o),es(this.session,r)})}async writeGated(e,n){try{await Vl(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 Kl=0;function qf(){return Kl+=1,`req_${Date.now().toString(36)}_${Kl.toString(36)}`}var ht=class{transport;constructor(e,n){this.transport=new Cr(e,void 0,n?.sessionTag)}responses={create:async e=>{let n=qf(),r=await this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var Ht=fe(require("yjs"),1),zl=require("@urun-sh/core/internal"),Gf=3e4;function Wf(t){return(e,n,r)=>{let o=t(e);Ht.applyUpdate(n,Ht.encodeStateAsUpdate(o));let s=a=>Ht.applyUpdate(o,a),i=a=>Ht.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function ts(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Wf(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=r.get(d);return c||(c=new zl.SessionDocumentImpl(d,e,n),r.set(d,c)),c},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let c=i.get(d);if(!c){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);c=t.streamEndpoint(d),i.set(d,c)}return c},l=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);async function*f(){let h=a(d);try{yield*h.messages()}finally{i.delete(d),await h.close()}}return{messages:()=>f(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let c=s("llm");if(c.synced===!0)return;let f=d?.timeout??t.whenLiveTimeoutMs??Gf;await new Promise((h,m)=>{let _=setTimeout(()=>{R(),m(new Error(`lane ${e} llm doc never synced within ${f}ms`))},f),R=c.onSynced(()=>{clearTimeout(_),d?.signal?.removeEventListener("abort",v),h()}),v=()=>{clearTimeout(_),R(),m(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",v,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,c]of i)i.delete(d),c.close()}}}var yt=fe(require("ws"),1),wt=require("@urun-sh/core"),Yl="/stream/";function Xl(t){if(!t.startsWith(Yl))return null;let e=t.slice(Yl.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Mr(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Lr(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>wt.ENVELOPE_KIND.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var $r=class{reassembler=new wt.StreamFragmentReassembler;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===wt.STREAM_END&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},rs=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;a.bytes+o.byteLength>Ql&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Ql} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Ql=8*1024*1024,Ue=new rs;function Zl(t,e){let n=new $r,r={send(o){Ue.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Lr(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),Ue.detach(t,e,r)}};return Ue.attach(t,e,r),r}function Jf(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function eu(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new yt.default(r,Mr(e)),s=new $r;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Lr(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Lr(i),o.readyState!==yt.default.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function ns(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
|
|
72
75
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
73
76
|
Connection: close\r
|
|
74
77
|
Content-Type: text/plain; charset=utf-8\r
|
|
75
78
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
76
79
|
\r
|
|
77
|
-
${o}`)}function Xl(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new mt.WebSocketServer({noServer:!0,handleProtocols:(m,_)=>{let R=Vl(new URL(_.url??"/","http://localhost").pathname);if(!R)return!1;let v=$r(R.name);return m.has(v)?v:!1}}),s=new Map,i=new Set,a=!1,l=new Map,u=(m,_,R)=>{r>0&&l.set(m,{at:Date.now(),label:_,reap:R})},d=m=>{let _=l.get(m);_&&(_.at=Date.now())},c=r>0?setInterval(()=>{let m=Date.now();for(let[_,R]of l)m-R.at<r||(l.delete(_),console.warn(`[lane-stream] ${R.label}: lease expired (no data for ${r} ms) \u2014 terminating`),R.reap())},Math.max(10,Math.floor(r/4))):void 0;c?.unref?.();let f=(m,_,R,v)=>{let b={client:R,upstream:v,laneId:m,name:_};i.add(b);let p=g=>{if(i.delete(b)){l.delete(R),console.warn(`[lane-stream] ${m}/${_}: host-affinity pump torn down (${g})`);for(let y of[R,v])try{(y.readyState===mt.default.OPEN||y.readyState===mt.default.CONNECTING)&&y.close(1001,"lane stream pump closed")}catch{}}};if(u(R,`${m}/${_} pump`,()=>{for(let g of[R,v])try{g.terminate()}catch{}p("lease expired")}),n>0){let g=(y,S)=>{let x=!0,E=()=>{x=!0};y.on("pong",E),y.on("message",E);let I=setInterval(()=>{if(!x){console.warn(`[lane-stream] ${m}/${_}: pong timeout on ${S} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${S} dial never sends a close)`),clearInterval(I);try{y.terminate()}catch{}p(`${S} pong timeout`);return}x=!1;try{y.ping()}catch{}},n);I.unref?.();let k=()=>clearInterval(I);y.once("close",k),y.once("error",k)};g(R,"client"),g(v,"host")}R.on("message",g=>{d(R);try{v.send(g,{binary:!0})}catch(y){p(`upstream send failed: ${String(y)}`)}}),v.on("message",g=>{d(R);try{R.send(g,{binary:!0})}catch(y){p(`client send failed: ${String(y)}`)}}),R.on("close",()=>p("client socket closed")),R.on("error",()=>p("client socket error")),v.on("close",()=>p("host socket closed")),v.on("error",()=>p("host socket error"))},h=(m,_,R)=>{let v;try{v=new URL(m.url??"/","http://localhost")}catch{es(_,400,"malformed upgrade URL");return}_.on("error",()=>_.destroy());let b=Vl(v.pathname);b&&(a||_.destroyed||(async()=>{let p=v.searchParams.get("token")??"",g=null;try{g=p===""?null:await e.verifyToken(p,b.laneId,b.name)}catch{g=null}if(g===null){es(_,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let y=await e.hostOf(b.laneId).catch(()=>null);if(y&&y!==e.selfAddress)try{let S=await e.podToPodDial(b.laneId,b.name,y);o.handleUpgrade(m,_,R,x=>{f(b.laneId,b.name,x,S)});return}catch(S){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${y} failed (${String(S)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(m,_,R,y=>{let S=Uf(y,()=>d(y));if(s.set(y,S),Ne.attach(b.laneId,b.name,S),u(y,`${b.laneId}/${b.name}`,()=>y.terminate()),n>0){let E=!0,I=()=>{E=!0};y.on("pong",I),y.on("message",I);let k=setInterval(()=>{if(!E){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(k),y.terminate();return}E=!1;try{y.ping()}catch{}},n);k.unref?.();let O=()=>clearInterval(k);y.once("close",O),y.once("error",O)}y.on("message",E=>{d(y);let I=new Uint8Array(E);try{Cr(I)}catch(k){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(k)}`);return}Ne.deliver(b.laneId,b.name,S,I),I[1]===gt.ENVELOPE_KIND.END&&Ne.detach(b.laneId,b.name,S)});let x=()=>{s.delete(y),l.delete(y),Ne.detach(b.laneId,b.name,S)};y.on("close",x),y.on("error",x)})})().catch(()=>{_.destroyed||es(_,500,"lane stream upgrade failed")}))};return t.on("upgrade",h),{async close(){a=!0,t.off("upgrade",h),clearInterval(c),l.clear(),Ne.clear();for(let m of s.values())m.close(1001,"lane stream host shutting down");s.clear();for(let m of i)for(let _ of[m.client,m.upstream])try{_.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}var ze=require("crypto"),Df=["sfu","urun-doc"],Zl="runtime:lease",Ff="lane:join",Bf="urun-runtime-key-v1";function ns(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,ze.createHmac)("sha256",t).update(`${Bf}|${e}`).digest("base64url")}var Hf=120;function Ql(t){return Buffer.from(t).toString("base64url")}function jf(t,e,n){let r=Ql(JSON.stringify(t)),o=Ql(JSON.stringify(e)),s=(0,ze.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Cn(t,e,n=Hf,r=Ff,o){let s=o?ns(e,o):e;return qf(t,s,n,r,o)}function qf(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return jf({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,ze.randomUUID)()},e)}function rs(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let f=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(f!==void 0?(h.push(ns(n,f)),o&&h.push(ns(o,f))):(h.push(n),o&&h.push(o)),!h.some(b=>{let p=(0,ze.createHmac)("sha256",b).update(`${i}.${a}`).digest();return c.length===p.length&&(0,ze.timingSafeEqual)(c,p)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&Df.some(b=>b===_||Array.isArray(_)&&_.includes(b))))return null;let v=d.session_id??d.sub;return typeof v!="string"||v!==e?null:{sessionId:v,aud:_,scope:typeof d.scope=="string"?d.scope:void 0,tenant:f,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}var Gf=3,Wf="llm",Jf=new Set(["paused","error"]);function Mr(t,e,n){let r=t.doc(Wf),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,a=!1,l=new Set,u=[],d=c=>{if(!i){i=c;for(let f of[...l])f(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Gf||d(new q(`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"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&Jf.has(c.name)&&d(new q(`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),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*os(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function Vf(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Se(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}var Kf={"prod-usw2":["us-west1"]};function ru(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,_,R,v,b,p)=>{let g=R?E=>zl(m,E):E=>Yl(m,E,{hostUrl:`ws://${v}/stream/${m}`,token:()=>Cn(m,t.tokenSecret,void 0,void 0,p)}),y=R?Zo({laneId:m,roomDoc:E=>t.roomDoc(m,E),streamEndpoint:g}):Zo({laneId:m,streamEndpoint:g,connector:(0,tu.createWebsocketDocConnector)({serverUrl:`ws://${v}/doc`,sessionId:m,token:()=>Cn(m,t.tokenSecret,void 0,void 0,p),WebSocketPolyfill:nu.default})}),S=R?l(m):Mr(y,`lane:${m}`,{armOnFirstSync:!0}),x={session:y,responses:new ft(y,{sessionTag:null}),gone:S,goneWatch:S,laneId:m,pool:_,inFlight:0,laneSession:y,self:R,host:v??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(m,x),S.onGone(()=>u(x)),x},l=m=>{let _=null,R=!1,v=new Set,b=g=>{if(!_){_=g;for(let y of[...v])y(g);v.clear()}},p=t.hostedSignal?.(m,g=>{if(g){R=!0;return}R&&b(new q(`the lane ${m} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>_,onGone(g){return _?(g(_),()=>{}):(v.add(g),()=>v.delete(g))},dispose(){p?.(),v.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),Ne.forgetLane(m.laneId))},d=m=>{let _=m.laneId;return typeof _=="string"&&n.get(_)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},f=(m,_)=>{throw t.metrics?.observeLane503Fast(_??""),s.set(m,e()),new ue(m)},h=async(m,_)=>{let R=Vf(_);o.add(R);let v=e();try{let b=await t.laneWarmWaitMsFor?.(m,_)??t.laneColdWakeDefaultMs??0,p;try{p=await t.plane.pick({pool:R,app:_.appSlug,fn:_.fnName??"",model:m,holdMs:b,..._.sharedApp?{sharedApp:!0}:{}})}catch(I){throw I instanceof Pn?new eu.SessionAllocationError(`lane pick hold expired for ${R}: ${I.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):I}t.metrics?.observeLaneReady(m??"",p.length);let g=await t.currentReleaseOf?.(_)??null,y=new Set(p.map(I=>I.laneId));for(let I of i)y.has(I)||i.delete(I);let x=p.filter(I=>{let k=n.get(I.laneId);return k!==void 0&&g!==null&&k.mintedRelease!==""&&k.mintedRelease!==g&&(k.retireWhenIdle=!0,k.inFlight===0)?(c(k),!1):!i.has(I.laneId)}).map(I=>({laneId:I.laneId,self:I.host===t.selfAddress,host:I.host,region:I.region})).sort((I,k)=>{let O=Kf[t.seatRegion??""]??[],w=new Map(O.map((T,L)=>[T,L])),A=O.length===0?0:(I.region!==void 0?w.get(I.region):void 0)??O.length,P=O.length===0?0:(k.region!==void 0?w.get(k.region):void 0)??O.length;return A!==P?A-P:I.self!==k.self?I.self?-1:1:(r.get(I.laneId)??0)-(r.get(k.laneId)??0)})[0];x||f(R,m);let E=n.get(x.laneId);return E?.goneWatch?.gone()&&(u(E),E=void 0),E&&(E.pool!==R||E.self!==x.self||E.host!==x.host)&&(u(E),E=void 0),E||(E=a(x.laneId,R,x.self,x.host,g,_.sharedOrgId??void 0)),E.inFlight+=1,r.set(x.laneId,(r.get(x.laneId)??0)+1),{app:R,entry:E,identity:{kind:"catalog",model_id:_.modelId??m??"",variant:_.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-v)}};return{sessionFor(m,_){return h(m,_)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(v=>v.pool)])].sort(),_=await t.plane.status().catch(()=>[]),R=new Map(zf(_));return Promise.all(m.map(async v=>{let b=R.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(p=>p.pool===v).map(p=>({laneId:p.laneId,inFlight:p.inFlight,self:p.self,host:p.host})),lastRefusalAt:s.get(v)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function zf(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}var Yf="urun:node-scheduler:apps:v1";function Xf(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function ou(t){return async e=>{let n=Xf(e);if(n===null)return null;try{let r=await t.hget(Yf,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}var cu=require("ws");var iu=fe(require("yjs"),1),Ht=fe(require("y-protocols/sync"),1),Be=fe(require("y-protocols/awareness"),1),ne=fe(require("lib0/encoding"),1),jt=fe(require("lib0/decoding"),1),au=fe(require("lib0/map"),1),lu=fe(require("lodash.debounce"),1);var su=()=>{};var Zf=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,em=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,tm=0,nm=1;var rm=process.env.GC!=="false"&&process.env.GC!=="0",om=process.env.YPERSISTENCE,Nr=null;if(typeof om=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Bt=new Map,Ur=0,is=1,sm=(t,e,n)=>{let r=ne.createEncoder();ne.writeVarUint(r,Ur),Ht.writeUpdate(r,t);let o=ne.toUint8Array(r);n.conns.forEach((s,i)=>Ln(n,i,o))},ss=class extends iu.Doc{constructor(e){super({gc:rm}),this.name=e,this.conns=new Map,this.awareness=new Be.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let l=ne.createEncoder();ne.writeVarUint(l,is),ne.writeVarUint8Array(l,Be.encodeAwarenessUpdate(this.awareness,a));let u=ne.toUint8Array(l);this.conns.forEach((d,c)=>{Ln(this,c,u)})};this.awareness.on("update",n),this.on("update",sm),!1}},as=(t,e=!0)=>au.setIfUndefined(Bt,t,()=>{let n=new ss(t);return n.gc=e,Nr!==null&&Nr.bindState(t,n),Bt.set(t,n),n}),im=(t,e,n)=>{try{let r=ne.createEncoder(),o=jt.createDecoder(n);switch(jt.readVarUint(o)){case Ur:ne.writeVarUint(r,Ur),Ht.readSyncMessage(o,r,e,t),ne.length(r)>1&&Ln(e,t,ne.toUint8Array(r));break;case is:{Be.applyAwarenessUpdate(e.awareness,jt.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},Ft=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),Be.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Nr!==null&&(Nr.writeState(t.name,t).then(()=>{t.destroy()}),Bt.delete(t.name))}e.close()},Ln=(t,e,n)=>{e.readyState!==tm&&e.readyState!==nm&&Ft(t,e);try{e.send(n,r=>{r!=null&&Ft(t,e)})}catch{Ft(t,e)}},am=3e4,uu=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=as(n,r);o.conns.set(t,new Set),t.on("message",a=>im(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&Ft(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{Ft(o,t),clearInterval(i)}}},am);t.on("close",()=>{Ft(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ne.createEncoder();ne.writeVarUint(a,Ur),Ht.writeSyncStep1(a,o),Ln(o,t,ne.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ne.createEncoder();ne.writeVarUint(u,is),ne.writeVarUint8Array(u,Be.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),Ln(o,t,ne.toUint8Array(u))}}};var ls="/doc/",pu=30,lm=1e4,du="llm";function um(t){if(!t.startsWith(ls))return null;let e=t.slice(ls.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function qt(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
80
|
+
${o}`)}function tu(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new yt.WebSocketServer({noServer:!0,handleProtocols:(m,_)=>{let R=Xl(new URL(_.url??"/","http://localhost").pathname);if(!R)return!1;let v=Mr(R.name);return m.has(v)?v:!1}}),s=new Map,i=new Set,a=!1,l=new Map,u=(m,_,R)=>{r>0&&l.set(m,{at:Date.now(),label:_,reap:R})},d=m=>{let _=l.get(m);_&&(_.at=Date.now())},c=r>0?setInterval(()=>{let m=Date.now();for(let[_,R]of l)m-R.at<r||(l.delete(_),console.warn(`[lane-stream] ${R.label}: lease expired (no data for ${r} ms) \u2014 terminating`),R.reap())},Math.max(10,Math.floor(r/4))):void 0;c?.unref?.();let f=(m,_,R,v)=>{let b={client:R,upstream:v,laneId:m,name:_};i.add(b);let p=g=>{if(i.delete(b)){l.delete(R),console.warn(`[lane-stream] ${m}/${_}: host-affinity pump torn down (${g})`);for(let y of[R,v])try{(y.readyState===yt.default.OPEN||y.readyState===yt.default.CONNECTING)&&y.close(1001,"lane stream pump closed")}catch{}}};if(u(R,`${m}/${_} pump`,()=>{for(let g of[R,v])try{g.terminate()}catch{}p("lease expired")}),n>0){let g=(y,S)=>{let x=!0,E=()=>{x=!0};y.on("pong",E),y.on("message",E);let I=setInterval(()=>{if(!x){console.warn(`[lane-stream] ${m}/${_}: pong timeout on ${S} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${S} dial never sends a close)`),clearInterval(I);try{y.terminate()}catch{}p(`${S} pong timeout`);return}x=!1;try{y.ping()}catch{}},n);I.unref?.();let k=()=>clearInterval(I);y.once("close",k),y.once("error",k)};g(R,"client"),g(v,"host")}R.on("message",g=>{d(R);try{v.send(g,{binary:!0})}catch(y){p(`upstream send failed: ${String(y)}`)}}),v.on("message",g=>{d(R);try{R.send(g,{binary:!0})}catch(y){p(`client send failed: ${String(y)}`)}}),R.on("close",()=>p("client socket closed")),R.on("error",()=>p("client socket error")),v.on("close",()=>p("host socket closed")),v.on("error",()=>p("host socket error"))},h=(m,_,R)=>{let v;try{v=new URL(m.url??"/","http://localhost")}catch{ns(_,400,"malformed upgrade URL");return}_.on("error",()=>_.destroy());let b=Xl(v.pathname);b&&(a||_.destroyed||(async()=>{let p=v.searchParams.get("token")??"",g=null;try{g=p===""?null:await e.verifyToken(p,b.laneId,b.name)}catch{g=null}if(g===null){ns(_,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let y=await e.hostOf(b.laneId).catch(()=>null);if(y&&y!==e.selfAddress)try{let S=await e.podToPodDial(b.laneId,b.name,y);o.handleUpgrade(m,_,R,x=>{f(b.laneId,b.name,x,S)});return}catch(S){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${y} failed (${String(S)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(m,_,R,y=>{let S=Jf(y,()=>d(y));if(s.set(y,S),Ue.attach(b.laneId,b.name,S),u(y,`${b.laneId}/${b.name}`,()=>y.terminate()),n>0){let E=!0,I=()=>{E=!0};y.on("pong",I),y.on("message",I);let k=setInterval(()=>{if(!E){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(k),y.terminate();return}E=!1;try{y.ping()}catch{}},n);k.unref?.();let O=()=>clearInterval(k);y.once("close",O),y.once("error",O)}y.on("message",E=>{d(y);let I=new Uint8Array(E);try{Lr(I)}catch(k){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(k)}`);return}Ue.deliver(b.laneId,b.name,S,I),I[1]===wt.ENVELOPE_KIND.END&&Ue.detach(b.laneId,b.name,S)});let x=()=>{s.delete(y),l.delete(y),Ue.detach(b.laneId,b.name,S)};y.on("close",x),y.on("error",x)})})().catch(()=>{_.destroyed||ns(_,500,"lane stream upgrade failed")}))};return t.on("upgrade",h),{async close(){a=!0,t.off("upgrade",h),clearInterval(c),l.clear(),Ue.clear();for(let m of s.values())m.close(1001,"lane stream host shutting down");s.clear();for(let m of i)for(let _ of[m.client,m.upstream])try{_.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}var Xe=require("crypto"),Vf=["sfu","urun-doc"],ru="runtime:lease",Kf="lane:join",zf="urun-runtime-key-v1";function os(t,e){if(!t)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!e)throw new Error("deriveOrgRuntimeKey requires an orgId");return(0,Xe.createHmac)("sha256",t).update(`${zf}|${e}`).digest("base64url")}var Yf=120;function nu(t){return Buffer.from(t).toString("base64url")}function Xf(t,e,n){let r=nu(JSON.stringify(t)),o=nu(JSON.stringify(e)),s=(0,Xe.createHmac)("sha256",n).update(`${r}.${o}`).digest("base64url");return`${r}.${o}.${s}`}function Cn(t,e,n=Yf,r=Kf,o){let s=o?os(e,o):e;return Qf(t,s,n,r,o)}function Qf(t,e,n,r,o){let s=Math.floor(Date.now()/1e3);return Xf({alg:"HS256",typ:"JWT"},{session_id:t,aud:"sfu",sub:t,scope:r,...o?{tenant:o}:{},iat:s,exp:s+n,jti:(0,Xe.randomUUID)()},e)}function ss(t,e,n,r=Math.floor(Date.now()/1e3),o){let s=t.split(".");if(s.length!==3)return null;let[i,a,l]=s,u,d;try{u=JSON.parse(Buffer.from(i,"base64url").toString()),d=JSON.parse(Buffer.from(a,"base64url").toString())}catch{return null}if(u.alg!=="HS256")return null;let c;try{c=Buffer.from(l,"base64url")}catch{return null}let f=typeof d.tenant=="string"&&d.tenant!==""?d.tenant:void 0,h=[];if(f!==void 0?(h.push(os(n,f)),o&&h.push(os(o,f))):(h.push(n),o&&h.push(o)),!h.some(b=>{let p=(0,Xe.createHmac)("sha256",b).update(`${i}.${a}`).digest();return c.length===p.length&&(0,Xe.timingSafeEqual)(c,p)}))return null;let m=d.exp;if(typeof m!="number"||m<=r)return null;let _=typeof d.aud=="string"||Array.isArray(d.aud)?d.aud:void 0;if(!(_!==void 0&&Vf.some(b=>b===_||Array.isArray(_)&&_.includes(b))))return null;let v=d.session_id??d.sub;return typeof v!="string"||v!==e?null:{sessionId:v,aud:_,scope:typeof d.scope=="string"?d.scope:void 0,tenant:f,app:typeof d.app=="string"?d.app:void 0,fn:typeof d.fn=="string"?d.fn:void 0,exp:m}}var Zf=3,em="llm",tm=new Set(["paused","error"]);function Nr(t,e,n){let r=t.doc(em),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,a=!1,l=new Set,u=[],d=c=>{if(!i){i=c;for(let f of[...l])f(c);l.clear()}};return o&&u.push(r.onConnectionState(c=>{a&&(c.consecutiveFailures<Zf||d(new q(`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"?u.push(r.onSynced(()=>{a=!0})):s&&u.push(t.onPhase(c=>{if(c.name==="live"){a=!0;return}a&&tm.has(c.name)&&d(new q(`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),()=>{}):(l.add(c),()=>l.delete(c))},dispose(){l.clear();for(let c of u.splice(0))c()}}}async function*is(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(l=>a(l))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function nm(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Se(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}var rm={"prod-usw2":["us-west1"]};function au(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(m,_,R,v,b,p)=>{let g=R?E=>Zl(m,E):E=>eu(m,E,{hostUrl:`ws://${v}/stream/${m}`,token:()=>Cn(m,t.tokenSecret,void 0,void 0,p)}),y=R?ts({laneId:m,roomDoc:E=>t.roomDoc(m,E),streamEndpoint:g}):ts({laneId:m,streamEndpoint:g,connector:(0,su.createWebsocketDocConnector)({serverUrl:`ws://${v}/doc`,sessionId:m,token:()=>Cn(m,t.tokenSecret,void 0,void 0,p),WebSocketPolyfill:iu.default})}),S=R?l(m):Nr(y,`lane:${m}`,{armOnFirstSync:!0}),x={session:y,responses:new ht(y,{sessionTag:null}),gone:S,goneWatch:S,laneId:m,pool:_,inFlight:0,laneSession:y,self:R,host:v??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(m,x),S.onGone(()=>u(x)),x},l=m=>{let _=null,R=!1,v=new Set,b=g=>{if(!_){_=g;for(let y of[...v])y(g);v.clear()}},p=t.hostedSignal?.(m,g=>{if(g){R=!0;return}R&&b(new q(`the lane ${m} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>_,onGone(g){return _?(g(_),()=>{}):(v.add(g),()=>v.delete(g))},dispose(){p?.(),v.clear()}}},u=m=>{d(m)&&(n.delete(m.laneId),r.delete(m.laneId),m.goneWatch?.dispose(),Ue.forgetLane(m.laneId))},d=m=>{let _=m.laneId;return typeof _=="string"&&n.get(_)===m},c=m=>{d(m)&&(m.self&&!t.closeLane||(i.add(m.laneId),m.self&&t.closeLane?.(m.laneId),u(m)))},f=(m,_)=>{throw t.metrics?.observeLane503Fast(_??""),s.set(m,e()),new ue(m)},h=async(m,_)=>{let R=nm(_);o.add(R);let v=e();try{let b=await t.laneWarmWaitMsFor?.(m,_)??t.laneColdWakeDefaultMs??0,p;try{p=await t.plane.pick({pool:R,app:_.appSlug,fn:_.fnName??"",model:m,holdMs:b,..._.sharedApp?{sharedApp:!0}:{}})}catch(I){throw I instanceof Pn?new ou.SessionAllocationError(`lane pick hold expired for ${R}: ${I.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):I}t.metrics?.observeLaneReady(m??"",p.length);let g=await t.currentReleaseOf?.(_)??null,y=new Set(p.map(I=>I.laneId));for(let I of i)y.has(I)||i.delete(I);let x=p.filter(I=>{let k=n.get(I.laneId);return k!==void 0&&g!==null&&k.mintedRelease!==""&&k.mintedRelease!==g&&(k.retireWhenIdle=!0,k.inFlight===0)?(c(k),!1):!i.has(I.laneId)}).map(I=>({laneId:I.laneId,self:I.host===t.selfAddress,host:I.host,region:I.region})).sort((I,k)=>{let O=rm[t.seatRegion??""]??[],w=new Map(O.map((P,L)=>[P,L])),A=O.length===0?0:(I.region!==void 0?w.get(I.region):void 0)??O.length,T=O.length===0?0:(k.region!==void 0?w.get(k.region):void 0)??O.length;return A!==T?A-T:I.self!==k.self?I.self?-1:1:(r.get(I.laneId)??0)-(r.get(k.laneId)??0)})[0];x||f(R,m);let E=n.get(x.laneId);return E?.goneWatch?.gone()&&(u(E),E=void 0),E&&(E.pool!==R||E.self!==x.self||E.host!==x.host)&&(u(E),E=void 0),E||(E=a(x.laneId,R,x.self,x.host,g,_.sharedOrgId??void 0)),E.inFlight+=1,r.set(x.laneId,(r.get(x.laneId)??0)+1),{app:R,entry:E,identity:{kind:"catalog",model_id:_.modelId??m??"",variant:_.variant??""}}}finally{t.metrics?.observeLanePick(m??"",e()-v)}};return{sessionFor(m,_){return h(m,_)},release(m){d(m)&&(m.inFlight=Math.max(0,m.inFlight-1),r.set(m.laneId,m.inFlight),m.inFlight===0&&m.retireWhenIdle&&c(m))},owns(m){return d(m)},entryFor(m){return n.get(m)??null},evict(m){d(m)&&(m.gone.dispose(),n.delete(m.laneId),r.set(m.laneId,0),m.laneSession.destroy())},async status(){let m=[...new Set([...o,...[...n.values()].map(v=>v.pool)])].sort(),_=await t.plane.status().catch(()=>[]),R=new Map(om(_));return Promise.all(m.map(async v=>{let b=R.get(v)??{pool:v,lanes:[],lastDemandAt:null};return{pool:v,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(p=>p.pool===v).map(p=>({laneId:p.laneId,inFlight:p.inFlight,self:p.self,host:p.host})),lastRefusalAt:s.get(v)??null}}))},async close(){for(let m of n.values())m.gone.dispose(),m.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(m=>({pool:m.pool,laneId:m.laneId,inFlight:m.inFlight}))}}}function om(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}var sm="urun:node-scheduler:apps:v1";function im(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function lu(t){return async e=>{let n=im(e);if(n===null)return null;try{let r=await t.hget(sm,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}var gu=require("ws");var du=fe(require("yjs"),1),Gt=fe(require("y-protocols/sync"),1),He=fe(require("y-protocols/awareness"),1),ne=fe(require("lib0/encoding"),1),Wt=fe(require("lib0/decoding"),1),cu=fe(require("lib0/map"),1),pu=fe(require("lodash.debounce"),1);var uu=()=>{};var lm=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,um=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,dm=0,cm=1;var pm=process.env.GC!=="false"&&process.env.GC!=="0",fm=process.env.YPERSISTENCE,Ur=null;if(typeof fm=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var qt=new Map,Dr=0,ls=1,mm=(t,e,n)=>{let r=ne.createEncoder();ne.writeVarUint(r,Dr),Gt.writeUpdate(r,t);let o=ne.toUint8Array(r);n.conns.forEach((s,i)=>Ln(n,i,o))},as=class extends du.Doc{constructor(e){super({gc:pm}),this.name=e,this.conns=new Map,this.awareness=new He.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(c=>{d.add(c)}),s.forEach(c=>{d.delete(c)}))}let l=ne.createEncoder();ne.writeVarUint(l,ls),ne.writeVarUint8Array(l,He.encodeAwarenessUpdate(this.awareness,a));let u=ne.toUint8Array(l);this.conns.forEach((d,c)=>{Ln(this,c,u)})};this.awareness.on("update",n),this.on("update",mm),!1}},us=(t,e=!0)=>cu.setIfUndefined(qt,t,()=>{let n=new as(t);return n.gc=e,Ur!==null&&Ur.bindState(t,n),qt.set(t,n),n}),gm=(t,e,n)=>{try{let r=ne.createEncoder(),o=Wt.createDecoder(n);switch(Wt.readVarUint(o)){case Dr:ne.writeVarUint(r,Dr),Gt.readSyncMessage(o,r,e,t),ne.length(r)>1&&Ln(e,t,ne.toUint8Array(r));break;case ls:{He.applyAwarenessUpdate(e.awareness,Wt.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},jt=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),He.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Ur!==null&&(Ur.writeState(t.name,t).then(()=>{t.destroy()}),qt.delete(t.name))}e.close()},Ln=(t,e,n)=>{e.readyState!==dm&&e.readyState!==cm&&jt(t,e);try{e.send(n,r=>{r!=null&&jt(t,e)})}catch{jt(t,e)}},hm=3e4,fu=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=us(n,r);o.conns.set(t,new Set),t.on("message",a=>gm(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&jt(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{jt(o,t),clearInterval(i)}}},hm);t.on("close",()=>{jt(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=ne.createEncoder();ne.writeVarUint(a,Dr),Gt.writeSyncStep1(a,o),Ln(o,t,ne.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let u=ne.createEncoder();ne.writeVarUint(u,ls),ne.writeVarUint8Array(u,He.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),Ln(o,t,ne.toUint8Array(u))}}};var ds="/doc/",hu=30,ym=1e4,mu="llm";function wm(t){if(!t.startsWith(ds))return null;let e=t.slice(ds.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function Jt(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
78
81
|
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
79
82
|
Connection: close\r
|
|
80
83
|
Content-Type: text/plain; charset=utf-8\r
|
|
81
84
|
Content-Length: ${Buffer.byteLength(o)}\r
|
|
82
85
|
\r
|
|
83
|
-
${o}`)}function
|
|
84
|
-
`)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var se=require("@prometheus-io/client"),
|
|
86
|
+
${o}`)}function yu(t,e){let n=new gu.WebSocketServer({noServer:!0}),r=new Set,o=new Map,s=new Map,i=g=>o.get(`${g}/${mu}`)??0,a=g=>s.get(g)??0,l=new Map,u=new Map,d=new Set,c=new Set,f=new Map,h=new Map,m=4096,_=!1,R=(g,y,S)=>{let x=i(g)>0,E=a(g),I=E>0,k=`${g}/${y}`,O=o.get(k)??0;S>0?o.set(k,S):o.delete(k);let w=E+S-O;w>0?s.set(g,w):s.delete(g);let A=i(g)>0,T=w>0;if(x!==A){A?v(g):b(g);for(let P of l.get(g)??[])P(A)}I&&!T&&queueMicrotask(()=>{let P=`${g}/`;for(let[L,N]of[...qt.entries()])!L.startsWith(P)||N.conns.size>0||(qt.delete(L),N.destroy())})},v=g=>{if(!e.hostRegistry||u.has(g))return;let y=()=>{e.hostRegistry?.setHost(g,e.selfAddress).catch(()=>{})};y();let S=setInterval(y,ym);S.unref?.(),u.set(g,S)},b=g=>{let y=u.get(g);y&&(clearInterval(y),u.delete(g)),e.hostRegistry&&e.hostRegistry.delHost(g,e.selfAddress).catch(()=>{})},p=(g,y,S)=>{let x;try{x=new URL(g.url??"/","http://localhost")}catch{Jt(y,400,"malformed upgrade URL");return}y.on("error",()=>y.destroy()),y.on("close",()=>c.delete(y));let E=wm(x.pathname);if(!E){if(x.pathname.startsWith(ds)){Jt(y,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}c.add(y);return}d.add(y);let I=!1;(async()=>{if(h.has(E.laneId)){Jt(y,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let k=x.searchParams.get("token")??"",O=null;try{O=k===""?null:await e.verifyToken(k,E.laneId,E.docName)}catch{O=null}if(O===null){Jt(y,401,"invalid or missing lane doc token");return}let w=O;if(w.tenant!==void 0&&e.laneTenantOf){let A=null;try{A=await e.laneTenantOf(E.laneId)}catch{A=null}if(A==null||A==="")e.onLaneTenantMissing?.();else if(w.tenant!==A){Jt(y,403,"lane doc token org does not match the lane record");return}}_||y.destroyed||(I=!0,n.handleUpgrade(g,y,S,A=>{d.delete(y),r.add(A),A.on("close",()=>r.delete(A));let T=f.get(E.laneId);T||(T=new Set,f.set(E.laneId,T)),T.add(A),A.on("close",()=>{T.delete(A),T.size===0&&f.delete(E.laneId)});let P=w.scope===ru||w.scope===void 0&&typeof w.app=="string"&&typeof w.fn=="string"&&w.aud==="sfu";if(P){let N=`${E.laneId}/${E.docName}`,V=(o.get(N)??0)+1;R(E.laneId,E.docName,V),V>1&&E.docName===mu&&e.hostRegistry?.setHost(E.laneId,e.selfAddress).catch(()=>{})}A.on("close",()=>{if(!P)return;let N=`${E.laneId}/${E.docName}`;R(E.laneId,E.docName,Math.max(0,(o.get(N)??1)-1))}),fu(A,g,{docName:`${E.laneId}/${E.docName}`,gc:!0})}))})().catch(()=>{!I&&!y.destroyed&&Jt(y,500,"lane doc upgrade failed")}).finally(()=>d.delete(y))};return t.on("upgrade",p),{async close(){_=!0,t.off("upgrade",p);for(let y of[...u.keys()])b(y);await new Promise(y=>{if(r.size===0&&d.size===0){y();return}let S=r.size+d.size,x=()=>{S-=1,S<=0&&y()};for(let E of r)E.once("close",x);for(let E of d)E.once("close",x);for(let E of r)E.close(1001,"lane doc host shutting down");for(let E of d)E.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(g,y){return us(`${g}/${y}`,!0)},isHosted(g){return i(g)>0},onHostedChange(g,y){let S=l.get(g);return S||(S=new Set,l.set(g,S)),S.add(y),y(i(g)>0),()=>{S.delete(y)}},closeLane(g){if(h.set(g,!0),h.size>m){let y=h.keys().next().value;y!==void 0&&h.delete(y)}b(g);for(let y of f.get(g)??[])y.close(1001,`lane ${g} retired \u2014 the app's release moved`)}}}var Wu=fe(require("ws"),1);var _m="urun:catalog:v1";function wu(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let l=await t.redis.hgetall(_m),u=[];for(let d of Object.values(l))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
87
|
+
`)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}var se=require("@prometheus-io/client"),_u=require("http");var vu=9464,Fr="/metrics",Vt="(other)",cs="(none)",ps=64,fs=128,vm=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",_r,Rn,nt],bm=new Set(vm);function ms(t){return bm.has(t)?t:Vt}function gs(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var Kt=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?cs:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Vt):(this.admitted.add(e),e):Vt}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},zt=class{registry=new se.Registry;modelLabel=new Kt(ps);orgLabel=new Kt(fs);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new se.Gauge({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new se.Counter({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new se.Histogram({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new se.Histogram({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new se.Counter({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new se.Counter({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new se.Counter({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of hl)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new se.Gauge({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},yl()),this.ledgerQueue.set({measure:"oldest_age_seconds"},wl()/1e3)}}),this.labelCardinality=new se.Gauge({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new se.Counter({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new se.Gauge({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new se.Histogram({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new se.Histogram({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new se.Counter({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new se.Counter({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&(0,se.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=ms(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?Vt:e.method,status_class:gs(e.status),stream:l,model:s,org:i}),this.duration.observe({lane:n,stream:l,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Br(t){return(0,_u.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Fr){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Fr}
|
|
85
88
|
`);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
|
|
86
|
-
`);return}n.end()})})}var Wu=fe(require("ioredis"),1);var ms=require("crypto"),yu=require("http"),wu=9465,gs="x-urun-key-id",hs="x-urun-key-fingerprint",ys="urun-ratelimit-bucket:",ws="urun-ratelimit-tier:",Br="anonymous",fm=/^urun_sk_[A-Za-z0-9_-]{43}$/;function _s(t){return(0,ms.createHash)("sha256").update(`${ys}${t}`).digest("hex")}function vs(t){return(0,ms.createHash)("sha256").update(`${ws}${t}`).digest("hex")}function bs(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return fm.test(n)?n:null}function Hr(){return(0,yu.createServer)((t,e)=>{let n=bs(t.headers.authorization);e.setHeader(gs,n===null?Br:_s(n)),e.setHeader(hs,n===null?Br:vs(n)),e.writeHead(200),e.end()})}var Mn=require("@urun-sh/core"),Wr=require("crypto"),_u="urun-session-gateway",mm="machine",gm=3e5;function bu(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var J=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Vt=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},Le=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Kt(t){let e=(t??"").trim();if(e==="")throw new J("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new J("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var hm=60,ks=6e4,Rs=4096;function ym(t){return t===401||t===403}var ht=class{constructor(e){this.opts=e;this.mint=e.mint??Mn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new J("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<ks)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:hm});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Mn.ClientTokenError&&i.status===402?(this.cache.delete(e),new Vt(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof Mn.ClientTokenError&&ym(i.status)?(this.cache.delete(e),new J(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new Le(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new Le(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=Rs){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function $n(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function vu(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var jr=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof Le?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<gm)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&vu(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&vu(s))),o}};function Su(t,e,n){try{let r=(0,Wr.createPublicKey)({key:n,format:"jwk"});return(0,Wr.verify)("RSA-SHA256",t,r,e)}catch{return!1}}var qr=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new jr(e.fetchImpl??fetch,e.now??Date.now,n=>new Le("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new J("malformed machine token");let s,i;try{s=$n(n),i=$n(r)}catch{throw new J("malformed machine token")}if(s.alg!=="RS256")throw new J(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new J(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==_u)throw new J(`machine token audience must be ${_u} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==mm)throw new J(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new J("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new J("machine token is expired \u2014 re-mint and retry");let c=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(c===void 0)throw new J(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Su(f,h,c))throw new J("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new J("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:u,credential:"machine"}}},wm="https://api.workos.com/sso/jwks/";function _m(t){return`${wm}${t.slice(t.lastIndexOf("/")+1)}`}var Ss=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new jr(e.fetchImpl??fetch,this.now,n=>new Le("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!bu(e))return!1;try{let n=$n(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new J("malformed user token");let s,i;try{s=$n(n),i=$n(r)}catch{throw new J("malformed user token")}if(s.alg!=="RS256")throw new J(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new J(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new J("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new J("user token is expired \u2014 re-authenticate and retry");let c=await this.cache.keyFor(_m(l),a);if(c===void 0)throw new J(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Su(f,h,c))throw new J("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new J("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:u,credential:"user"}}},Gr=class{verifier;bindings;constructor(e){this.verifier=new Ss({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new ht({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new J("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Es(t,e,n,r){if(bu(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}var Un=require("crypto");var le=require("@urun-sh/core");async function ku(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 Ru=require("@urun-sh/core"),xs=2;function vm(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function bm(t){let e=t?.type;return e==="response.completed"||e==="error"}function Eu(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=xs;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let f=await t.createStream(l,n);for await(let h of f){if(bm(h)&&(d=!0),vm(h)){if(i>1)continue}else c=!0;yield h}}catch(f){if(f instanceof Ru.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,f)}catch{}throw f}if(i<xs&&!c){await t.evict(a,l);continue}throw f}if(d)return;if(i<xs&&!c){await t.evict(a,l);continue}return}})()}}var Ts=require("crypto");var As=require("@urun-sh/core"),Sm="audio";function xu(t){let e=t.streamEndpoint(Sm);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,As.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,As.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var Au=require("@urun-sh/core"),km="rt-video-in";function Iu(t){let e=t.streamEndpoint(km);return{sendInputFrame:async n=>{e.send((0,Au.encodeStreamEnvelope)(n))}}}var Em=0,xm=4,Am=4;function Ou(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):Em;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,xm));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Am),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Is(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 Tu(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u=r||l||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...l,...r}:void 0,d=_=>({session:_,responses:new ft(_),gone:Mr(_,n)});if(i.lane==="jwt"){let _=(0,le.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Is(_,e.appSlug,a,u))}if(i.lane==="machine"||i.lane==="user"){let _=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:R}=i,v=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ts.randomUUID)(),b=(0,le.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,le.createClientToken)(_,{baseUrl:R,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:v,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Is(b,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:f}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ts.randomUUID)(),m=(0,le.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,le.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Is(m,e.appSlug,a,u))}function Pu(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 Ps(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 Im=new Set(["error","paused"]);function Cs(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=Tu(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new zn({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"?()=>Hi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>ku(n):null),listPrices:n?()=>Ei(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return _i(i)}:e.lane==="api-key"?()=>vi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Pu});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},qe({appSlug:t.defaultApp}))),s}function Cu(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,a=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
87
|
-
`)},l=(d,c)=>{let f=o.get(c);if(f)return f;let h=new Yn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async m=>{let _=Tu(t,d,c,{concurrencyKey:m.concurrencyKey});return _.gone.onGone(()=>h.markSessionDead(_)),await Vr(_.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async m=>{m.gone.dispose(),m.audioDispose?.(),await m.session.end()},onDetach:(m,_)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${_}`),terminalOpenFailure:m=>m instanceof le.SessionFailedError&&Ps(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},u=async(d,c)=>{let f=s.get(c);if(f)try{let h=await e.poolTuningFor(d);l(d,c).retune({min:h?.min??f.env.min,max:h?.max??f.env.max,inFlightCap:h?.in_flight_cap??f.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,qe(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),f=qe(c),h=l(c,f);await u(c,f);let m=await h.acquire({timeoutMs:h.requestWaitMs}),_=i.get(m.entry)??[];return _.push(m),i.set(m.entry,_),{app:f,entry:m.entry,identity:un(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,qe(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)u(c,d).then(()=>{let f=o.get(d);f&&f.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 Om(t){return(0,le.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?le.DEFAULT_WHEN_LIVE_TIMEOUT_MS:le.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:le.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Vr(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:Om(t.phase),signal:e})}async function Os(t){if(typeof t.cancel=="function")try{await t.cancel();return}catch{}if(typeof t.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");t.detach()}function Jr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function Ls(t,e=Zs,n,r,o=ko,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,c=p=>{let g=p.session.id;return typeof g=="string"&&g.length>0?g:null},f="lane",h=p=>{let g=cn(p);if(!s||!g||g.app!==f)return null;let y=s.entryFor(g.key);if(!y)throw new q(`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}},m=async p=>h(p)?.entry??(await t.sessionForHandle(p)).entry,_=p=>{let g=i.get(p);if(!g){let y={waiting:0,gone:new AbortController};d.set(p,y),g=(async()=>{if(await Vr(p.session,y.gone.signal),y.gone.signal.aborted)throw Jr(y.gone.signal);d.get(p)===y&&d.delete(p);let S=await Qs(p.session,await e());return Object.assign(S,{sessionId:p.session.id})})(),i.set(p,g),g.then(S=>{i.get(p)===g&&(p.audioDispose=()=>S.dispose())},()=>{}),g.catch(()=>{i.get(p)===g&&i.delete(p)}),g.then(()=>{d.get(p)===y&&d.delete(p)},()=>{d.get(p)===y&&d.delete(p)})}return g},R=p=>{let g=u.get(p);return g||(g=(async()=>{let y=await _(p);return{appendInputAudio:(S,x)=>y.appendInputAudio(S,x),onOutputAudio:S=>y.onOutputAudio(S),sessionId:c(p)}})(),u.set(p,g),g.catch(()=>{u.get(p)===g&&u.delete(p)})),g},v=async(p,g,y)=>{if(y?.aborted){let E=d.get(p);throw(i.get(p)===void 0||E!==void 0&&E.waiting===0)&&await Os(p.session),Jr(y)}let S=g(p),x=d.get(p);return x!==void 0&&x.waiting++,y===void 0?S:new Promise((E,I)=>{let k=()=>{x!==void 0&&--x.waiting===0&&d.get(p)===x&&(x.gone.abort(),d.delete(p),i.delete(p),u.delete(p),Os(p.session).catch(()=>{})),I(Jr(y))};y.addEventListener("abort",k,{once:!0});let O=()=>y.removeEventListener("abort",k);S.then(w=>{O(),E(w)},w=>{O(),I(w)})})},b=async(p,g,y)=>{try{return await y}catch(S){throw(S instanceof q||S instanceof le.SessionFailedError&&Ps(S))&&(t.evict(p,g),S instanceof le.SessionFailedError&&n?.(p,S.kind==="never-live"?"never-live":"create-failed")),S}};return{createResponse:Eu({sessionFor:s?async p=>{let g=await t.resolveTargetFor(p);if(g.sharedApp){let y=await s.sessionFor(p,g);return{app:y.app,entry:y.entry,identity:y.identity}}return r?r.sessionFor(p):t.sessionFor(p)}:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>c(p),evict:(p,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(p,g)},onAdmissionVerdict:(p,g,y)=>{Ps(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(p,g),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,g)=>{try{await Vr(p.session);let y=ta(os(await p.responses.responses.create(g),p.gone),o);if(!r&&!s)return y;let S=p;return(async function*(){try{yield*y}catch(E){throw na(E)&&(s&&s.owns(S)?s.evict(S):r&&(E instanceof q?r.markSessionDead(S):r.evict(S))),E}finally{s&&s.owns(S)?s.release(S):r?.end(S)}})()}catch(y){throw s&&s.owns(p)?s.release(p):r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,g)=>t.supportsImages(p,g),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,g)=>{let{app:y,entry:S}=await t.sessionFor(p);return await b(y,S,v(S,_,g))},openAudioOn:async(p,g,y,S)=>{let x=h(p);if(x){let k=x.entry.session;return xu(k)}let{app:E,entry:I}=await t.sessionForHandle(p);if(S&&I.session.phase?.name!=="live"){let k=I.session.phase?.name;S({status:k==="queued"||k==="waiting_for_capacity"?k:"pending",reason:`the dial's session is ${k??"not yet admitted"} \u2014 the connection waits for admission`})}return await b(E,I,v(I,R,g))},openTurnsOn:async function*(p,g){if(g?.aborted)throw Jr(g);let y=await m(p);yield*Ui(y.session,g)},openVideoOn:async p=>{let g=h(p);if(g)return Iu(g.entry.session);let{entry:y}=await t.sessionForHandle(p),S=a.get(y);return S||(S=to(y.session),a.set(y,S)),S},openVideo:async p=>{let{entry:g}=await t.sessionFor(p),y=a.get(g);return y||(y=to(g.session),a.set(g,y)),y},openVideoOut:async p=>{let{entry:g}=await t.sessionFor(p),y=l.get(g);return y||(y=ti(g.session),l.set(g,y)),y},sessionHandle:async p=>{if(s){let g=await t.resolveTargetFor(p);if(g.sharedApp){let y=await s.sessionFor(p,g),S=c(y.entry);if(S===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return dn(f,S)}}return(await t.handleFor(p)).handle},dedicatedSessionHandle:async p=>{if(!(await t.resolveTargetFor(p)).sharedApp)return(await t.handleFor(p)).handle;let{app:y,entry:S}=await t.dedicatedSessionFor(p);return dn(y,Pu(S))},releaseSessionHandle:p=>{let g=cn(p);if(!g)return;if(g.app.startsWith(St)){(async()=>{let S=null;try{S=(await t.sessionForHandle(p)).entry}catch{return}await Os(S.session).catch(()=>{}),await t.evict(g.app,S)})();return}if(!s||g.app!==f)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:g,entry:y}=await t.sessionForHandle(p);await t.evict(g,y)},createResponseOn:async(p,g,y)=>{let S=await m(p);await Vr(S.session);let x=y!==void 0&&h(p)?new ft({...S.session,consumerId:y},{sessionTag:y}):S.responses;return os(await x.responses.create(g),S.gone)},onSessionEnd:async(p,g)=>{let y=h(p);if(y)return y.entry.gone.onGone(I=>g({timeLeftMs:null,reason:I.message}));let{entry:S}=await t.sessionForHandle(p),x=S.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 E=!1;return x.onPhase(I=>{if(E||!Im.has(I.name))return;E=!0;let k=x.endsAt??null;g({timeLeftMs:k?Math.max(0,k.getTime()-Date.now()):null,reason:I.reason??`session ${I.name}`})})}}}var $u=require("http");var Tm="/pooler/v1/inference",zt=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},Pm=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Cm=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},Mu=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Lm=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Mu(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new zt(t.status,e,n,t.retryAfterSeconds)};async function $m(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Tm}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Pm(e),firstMessage:Cm(e)}});return new Promise((a,l)=>{let u=(0,$u.request)({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let c=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(c)?c:void 0,body:d})});u.on("error",d=>l(new zt(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var Lu=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Mm(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
|
|
88
|
-
|
|
89
|
-
`);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=Lu(s);i!==null&&(yield i)}let n=Lu(e);n!==null&&(yield n)}async function Nu(t,e,n,r){let o=Ir(e,n,r),s=o.model??"";if(s==="")throw new zt(400,"missing_model","the pooler submit requires a model");let i=await $m(t,o,n,s,e.stream===!0);if(i.status>=400)throw await Lm(i);let a=e.stream===!0?Tr(n,Mm(i)):await Nm(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Nm(t,e){let n=await Mu(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new zt(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Tr(e,(async function*(){yield o})())}var $s=8080,Nn="serve",Uu="0.0.0.0";function Um(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Du(t=process.env){let e=(t.PORT??"").trim(),n=e===""?$s:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=aa(tr(Um(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?tr(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=i?{catalogUrl:tr(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let c=u?{keyId:d,key:u}:void 0,f={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],m=h.filter((w,A)=>Object.values(f)[A]==="");if(m.length!==0&&m.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${m.join(", ")}, which would half-configure the lane plane`);let _=m.length===0?f:void 0,R={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},v=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],b=v.filter((w,A)=>Object.values(R)[A]==="");if(b.length!==0&&b.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${b.join(", ")}, which would half-configure the pooler cutover`);let p=b.length===0?R:void 0,g={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},y=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=y.filter((w,A)=>Object.values(g)[A]==="");if(S.length!==0&&S.length!==y.length)throw new Error(`${y.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let x=g.issuers.split(",").map(w=>w.trim()).filter(w=>w!=="");if(x.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let E=Number(g.tokenTtlS);if(S.length===0&&(!Number.isFinite(E)||E<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(g.tokenTtlS)}`);let I=S.length===0?{jwksBaseUrl:g.jwksBaseUrl,issuers:x,tokenTtlS:E}:void 0,k=(t.URUN_WORKOS_ISSUERS??"").trim(),O=k.split(",").map(w=>w.trim()).filter(w=>w!=="");if(k!==""&&O.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let w of O){let A;try{A=new URL(w)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(w)}`)}if(A.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${w}) \u2014 the issuer is the user rung's trust root`)}return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:_,pooler:p,machine:I,...O.length>0?{userIssuers:O}:{}}}var Ms=512;function Yt(t){return`urun-inference-proxy-${(0,Un.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Xt=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let u=`px_${(0,Un.randomUUID)()}`;return Nu(s,a,u,u)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Nn,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:Ou(process.env,process.env.HOSTNAME)??void 0},r=Cs(n),o=n.decisionPool?Cu(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Ls(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Ms;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Kr=512,Ns=1024,Qt=class extends Error{constructor(){super(`conversation capacity reached (${Kr} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Dm(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(bt))return{concurrencyKey:e};if(n.startsWith(bt)||n.startsWith(St))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(bt)||n.startsWith(St)||t.set(n,r)}}}function Fm(t,e,n,r,o){let s=Cs({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Nn,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Dm(r,o)});return{clients:Ls(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var Zt=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${Yt(e.apiKey)}:live`:`${Yt(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):Fm(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Kr;){let e=this.byCaller.keys().next();if(e.done)throw new Qt;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new Qt;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,Un.randomUUID)(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,l,u)=>s().backhaul.clients.createResponseOn(a,l,u),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let u=s().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(a)},i.openAudioOn=async(a,l,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return d(a,l,u)},i.openVideoOn=async(a,l)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,l)},i.openTurnsOn=(a,l)=>{let u=s().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Ns;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),u=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||u===void 0?void 0:u.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new q("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};var zr="/inference-usage",Fu=25e3;var Bm=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Bu(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Bm.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var Yr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${zr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Fu)})}catch(i){throw new oe(`the uRun usage surface (POST ${zr}) could not be reached within ${Fu}ms: ${Bu(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new J("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new oe(`the uRun usage surface (POST ${zr}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new oe(`the uRun usage surface (POST ${zr}) answered HTTP ${o.status} with a body that is not JSON: ${Bu(i)}`)}return ul(s,this.opts.onRejectedRow)}};var js="/inference-ledger",qs=1e4,en=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Fs=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},ae=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Bs=class extends J{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Hs=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Hm=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",Us],["output_minutes",Us],["cost_nano_usd",Us],["price_version",t=>t===null||typeof t=="string"]];function jm(t){for(let[e,n]of Hm){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function qm(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:jm(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Us(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Ds(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Gm(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Hu(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Wm(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Hu(t.started_at,n.started_at)&&Hu(t.completed_at,n.completed_at)&&Ds(t.prompt_tokens,n.prompt_tokens)&&Ds(t.completion_tokens,n.completion_tokens)&&Ds(t.output_units,n.output_units)&&Gm(t.output_minutes,n.output_minutes)}function Jm(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
|
|
90
|
-
`)}async function Vm(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(Jm(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Gs(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ae(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new ae(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new ae(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new ae(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new ae(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new ae(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new ae(`${e} answered a BLANK ${u} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),l=o!=null;if(l&&(i===null||a!==null))throw new ae(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!l&&(i!==null||a===null))throw new ae(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var tn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${js}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Vm(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new ae(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(qs)})}catch(u){throw new ae(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=qm(u);throw d.status==="found"&&Wm(n,d.row)?new Fs(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new en(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new en(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new Bs("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let f=c.error;f!==null&&typeof f=="object"&&"code"in f&&(d=f.code)}}catch{}throw d==="ledger_signature_invalid"?new Hs(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+u.slice(0,400)):new ae(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new ae(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new ae(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Gs(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new ae(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var Ws=5e3,Km=1e3,zm=1500,Js=3e3,Ym="/api/client-tokens";function Xr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function ju(t,e,n,r){Xr(t,e,{error:{message:n,type:r}})}async function Xm(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Ym}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Js)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Ju(t){let e=t.resolver??new ht({gatewayUrl:t.baseUrl}),n=t.machine?new qr({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new Gr({issuers:t.userIssuers,gatewayUrl:t.baseUrl}):null,o=new Jt(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),s=null,i=null,a=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let w=new Wu.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),A=mu({redis:w});return{registry:ru({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:Dl({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(T,L)=>s?.onHostedChange(T,L)??(()=>()=>{}),roomDoc:(T,L)=>{if(!s)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return s.roomDoc(T,L)},metrics:o,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(T,L)=>A.rows().then(N=>{let V=mo(N,L);return V?.warm_wait_s!==void 0?V.warm_wait_s*1e3:void 0}),currentReleaseOf:ou(w),closeLane:T=>s?.closeLane(T)}),catalog:A,redis:w}})(),l=t.registry??new Xt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>Xm(t.baseUrl)),d=async()=>{let w=null;for(let T of l.decisionPools()){w=T;break}if(!w)return null;let A=w.stats();if(A.some(T=>T.draining))return{ok:!1,detail:"decision pool draining"};if(A.every(T=>T.attached===0&&T.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let P=await w.pingReady(zm);return{ok:P,detail:P?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new Yr({apiUrl:t.apiUrl}),f=t.ledgerClient??new tn({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),h=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();h&&m&&(async()=>{try{await l.decisionWarmerFor({orgId:h,apiKey:m})?.warmFor(xr)}catch(w){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(w instanceof Error?w.message:w)}
|
|
91
|
-
`)}})();let _=async w=>Es(Kt(w.headers.authorization),e,n,r),R=async w=>{let A=await _(w);if(A.billingAudience==="platform"&&A.creditsAdmissionOk===!1){let P=A.creditsRefusalReason;throw new Vt(P==="spend_cap_reached"||P==="insufficient_credits"?P:void 0)}return A},v=w=>w instanceof J?{status:w.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:w instanceof Vt?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...w.code!==void 0?{code:w.code}:{}}:w instanceof Le?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:w.detail}:null,b={write:(w,A)=>f.write(Kt(w.headers.authorization),A),observe:w=>o.observeLedger(w),...t.ledgerLog?{report:t.ledgerLog}:{}},p=Al({clients:async w=>l.clientsFor(await R(w)),usage:{authorize:w=>Kt(w.headers.authorization),lookup:(w,A)=>c.lookup(w,A)},statusOf:v,...t.requestLog?{requestLog:t.requestLog}:{},observe:w=>o.observe(w),ledger:b}),g=va({authorize:async w=>{await R(w)},...t.lane?{secret:t.lane.tokenSecret}:{}}),y=null,S=null,x=(0,qu.createServer)((w,A)=>{let P=new URL(w.url??"/","http://localhost");(async()=>{if(w.method==="GET"&&P.pathname==="/healthz"){Xr(A,200,{ok:!0});return}if(w.method==="GET"&&P.pathname==="/readyz"){let N=Date.now();if((!y||N-y.at>=Ws)&&(y={at:N,...await u()}),!S||N-S.at>=Km){let Y=await d();S=Y===null?{at:N,ok:!0,detail:null}:{at:N,ok:Y.ok,detail:Y.detail}}let V=(y?.ready??!1)&&S.ok,H=S.detail===null?y?.detail??"control plane not yet probed":`${y?.detail??"control plane not yet probed"}; ${S.detail}`;Xr(A,V?200:503,{ok:V,control_plane:H});return}if(w.method==="GET"&&P.pathname==="/lanez"){Xr(A,200,{pools:a?await a.registry.status():null});return}let T=P.pathname==="/v1"||P.pathname.startsWith("/v1/"),L=P.pathname.startsWith("/partners/");if(!T&&!L){ju(A,404,`no route for ${w.method} ${P.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}await g(w,A)||p(w,A)})().catch(T=>{if(!A.headersSent){ju(A,500,String(T instanceof Error?T.message:T),"proxy_error");return}A.end()})}),E=t.conversations??new Zt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),I=new WeakMap,k=[yo(x,{authenticate:async w=>{let A=await Es(w,e,n,r),P=E.connectionFor(A);return{clients:P.clients,scope:Yt(A.apiKey),onBindResumeHandle:P.bindResumeHandle,clientsForResume:P.clientsForResume,release:P.release}}}),Io(x,{clients:async w=>l.clientsFor(await R(w)),statusOf:v}).close,lr(x,{resolver:{resolve:async(w,A,P)=>{let T=await R(w),L=E.connectionFor(T,Cl(w)),N;try{N=await Ll(Xo(L.clients,t.realtimeCompanions),Tl(w),A,Pl(w),P)}catch(Y){throw L.release().catch(()=>{}),Y}let V=N.release,H={...N,release:async()=>{await V?.(),await L.release()}};return I.set(H,T.orgId),H}},onSessionEnded:w=>{vr({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:rt(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:w.binding.model??null,stream:null,org:I.get(w.binding)??null,duration_ms:w.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:w.connected_ms/1e3,session_id:w.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:w.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:b,req:w.req})}})];if(t.lane&&a){let w=t.lane,A=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;s=fu(x,{verifyToken:(T,L)=>rs(T,L,w.tokenSecret,void 0,A),selfAddress:w.selfAddress,laneTenantOf:T=>a.redis.get(`lane_tenant:${T}`),onLaneTenantMissing:()=>o.observeLaneDocTenantMissing(),previousTokenSecret:A,hostRegistry:{setHost:(T,L)=>a.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${T}`,L,String(pu)),delHost:T=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${T}`,w.selfAddress)}}),i=Xl(x,{verifyToken:(T,L)=>rs(T,L,w.tokenSecret,void 0,A),selfAddress:w.selfAddress,hostOf:async T=>{let L=await a.redis.get(`lane_hosts:${T}`);return L&&L.trim()!==""?L.trim():null},podToPodDial:(T,L,N)=>new Promise((V,H)=>{(async()=>{let Y=await a.redis.get(`lane_tenant:${T}`),D=Cn(T,w.tokenSecret,void 0,void 0,Y||void 0),j=`ws://${N}/stream/${encodeURIComponent(T)}/${encodeURIComponent(L)}?token=${encodeURIComponent(D)}`,K=new Gu.default(j,$r(L));K.once("open",()=>V(K)),K.once("error",H)})().catch(H)})});let P=a;k.push(async()=>{await s.close(),await i.close(),await P.registry.close(),P.redis.quit().catch(()=>{})})}x.on("upgrade",(w,A)=>{let P=new URL(w.url??"/","http://localhost");P.pathname===Gn||P.pathname===xo||P.pathname===bn||s!==null&&P.pathname.startsWith("/doc/")||i!==null&&P.pathname.startsWith("/stream/")||A.destroyed||(A.write(`HTTP/1.1 404 Not Found\r
|
|
89
|
+
`);return}n.end()})})}var Ju=fe(require("ioredis"),1);var hs=require("crypto"),bu=require("http"),Su=9465,ys="x-urun-key-id",ws="x-urun-key-fingerprint",_s="urun-ratelimit-bucket:",vs="urun-ratelimit-tier:",Hr="anonymous",Sm=/^urun_sk_[A-Za-z0-9_-]{43}$/;function bs(t){return(0,hs.createHash)("sha256").update(`${_s}${t}`).digest("hex")}function Ss(t){return(0,hs.createHash)("sha256").update(`${vs}${t}`).digest("hex")}function ks(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Sm.test(n)?n:null}function jr(){return(0,bu.createServer)((t,e)=>{let n=ks(t.headers.authorization);e.setHeader(ys,n===null?Hr:bs(n)),e.setHeader(ws,n===null?Hr:Ss(n)),e.writeHead(200),e.end()})}var Mn=require("@urun-sh/core"),Jr=require("crypto"),ku="urun-session-gateway",km="machine",Rm=3e5;function Eu(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var J=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},Yt=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},$e=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function Xt(t){let e=(t??"").trim();if(e==="")throw new J("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new J("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Em=60,Es=6e4,xs=4096;function xm(t){return t===401||t===403}var _t=class{constructor(e){this.opts=e;this.mint=e.mint??Mn.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new J("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<Es)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Em});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Mn.ClientTokenError&&i.status===402?(this.cache.delete(e),new Yt(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof Mn.ClientTokenError&&xm(i.status)?(this.cache.delete(e),new J(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new $e(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new $e(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=xs){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function $n(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function Ru(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var qr=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof $e?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<Rm)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&Ru(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&Ru(s))),o}};function xu(t,e,n){try{let r=(0,Jr.createPublicKey)({key:n,format:"jwk"});return(0,Jr.verify)("RSA-SHA256",t,r,e)}catch{return!1}}var Gr=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new qr(e.fetchImpl??fetch,e.now??Date.now,n=>new $e("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new J("malformed machine token");let s,i;try{s=$n(n),i=$n(r)}catch{throw new J("malformed machine token")}if(s.alg!=="RS256")throw new J(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new J(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==ku)throw new J(`machine token audience must be ${ku} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==km)throw new J(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new J("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new J("machine token is expired \u2014 re-mint and retry");let c=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(c===void 0)throw new J(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!xu(f,h,c))throw new J("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new J("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:u,credential:"machine"}}},Am="https://api.workos.com/sso/jwks/";function Im(t){return`${Am}${t.slice(t.lastIndexOf("/")+1)}`}var Rs=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new qr(e.fetchImpl??fetch,this.now,n=>new $e("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Eu(e))return!1;try{let n=$n(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new J("malformed user token");let s,i;try{s=$n(n),i=$n(r)}catch{throw new J("malformed user token")}if(s.alg!=="RS256")throw new J(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new J(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new J("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new J("user token is expired \u2014 re-authenticate and retry");let c=await this.cache.keyFor(Im(l),a);if(c===void 0)throw new J(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),h=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!xu(f,h,c))throw new J("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new J("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:u,credential:"user"}}},Wr=class{verifier;bindings;constructor(e){this.verifier=new Rs({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new _t({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new J("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function As(t,e,n,r){if(Eu(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}var Dn=require("crypto");var le=require("@urun-sh/core");async function Au(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 Iu=require("@urun-sh/core"),Is=2;function Om(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function Tm(t){let e=t?.type;return e==="response.completed"||e==="error"}function Ou(t){return async function(n,r){let o=await t.sessionFor(n.model);return(async function*(){for(let i=1;i<=Is;i++){let{app:a,entry:l,identity:u}=i===1?o:await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(l)??null,identity:u});let d=!1,c=!1;try{let f=await t.createStream(l,n);for await(let h of f){if(Tm(h)&&(d=!0),Om(h)){if(i>1)continue}else c=!0;yield h}}catch(f){if(f instanceof Iu.SessionFailedError&&(f.kind==="never-live"||f.kind==="create-failed")){try{t.onAdmissionVerdict?.(a,l,f)}catch{}throw f}if(i<Is&&!c){await t.evict(a,l);continue}throw f}if(d)return;if(i<Is&&!c){await t.evict(a,l);continue}return}})()}}var Ps=require("crypto");var Os=require("@urun-sh/core"),Pm="audio";function Tu(t){let e=t.streamEndpoint(Pm);return{sessionId:t.id,appendInputAudio(n,r){let o=Buffer.from(n,"base64");if(o.byteLength!==0){if(r===void 0){e.send((0,Os.encodeStreamEnvelope)(new Uint8Array(o)));return}e.send((0,Os.encodeStreamEnvelope)({pcm16:n,capture_wall_ms:r}))}},onOutputAudio(){return()=>{}}}}var Pu=require("@urun-sh/core"),Cm="rt-video-in";function Cu(t){let e=t.streamEndpoint(Cm);return{sendInputFrame:async n=>{e.send((0,Pu.encodeStreamEnvelope)(n))}}}var $m=0,Mm=4,Nm=4;function $u(t,e){let n=(i,a)=>{let l=(t[i]??"").trim();if(!l)return a;let u=Number.parseInt(l,10);if(!Number.isInteger(u)||u<1)throw new Error(`${i} must be a positive integer (got ${JSON.stringify(t[i])})`);return u},r=(t.URUN_DECISION_POOL_MIN??"").trim();if(r==="0")return null;let o=r?Number.parseInt(r,10):$m;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,Mm));return{min:o,max:s,idleGraceMs:3e4,inFlightCap:n("URUN_DECISION_POOL_INFLIGHT_CAP",Nm),replicaId:(t.URUN_REPLICA_ID??"").trim()||e||"proxy"}}function Ts(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 Mu(t,e,n,r){let{baseUrl:o,orgId:s,auth:i}=t,a=e.fnName??t.fnName,l=t.sessionStartOptions?.(n),u=r||l||e.sharedApp?{...e.sharedApp?{sharedApp:!0}:{},...l,...r}:void 0,d=_=>({session:_,responses:new ht(_),gone:Nr(_,n)});if(i.lane==="jwt"){let _=(0,le.App)(e.appSlug,{baseUrl:o,orgId:s,jwt:i.jwt});return d(Ts(_,e.appSlug,a,u))}if(i.lane==="machine"||i.lane==="user"){let _=i.lane==="machine"?i.machineToken:i.userToken,{gatewayUrl:R}=i,v=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ps.randomUUID)(),b=(0,le.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,le.createClientToken)(_,{baseUrl:R,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:v,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Ts(b,e.appSlug,a,u))}let{apiKey:c,gatewayUrl:f}=i,h=(typeof t.subject=="function"?t.subject():t.subject)??(0,Ps.randomUUID)(),m=(0,le.App)(e.appSlug,{baseUrl:o,orgId:s,getAccessToken:async()=>(await(0,le.createClientToken)(c,{baseUrl:f,expiresIn:300,allowedFunctions:[`${e.appSlug}/${a}`],subject:h,...e.sharedApp?{sharedApp:!0}:{}})).token});return d(Ts(m,e.appSlug,a,u))}function Nu(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 Cs(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 Um=new Set(["error","paused"]);function Ls(t){let{auth:e,catalog:n}=t,r=null,o=(i,a)=>{let l=Mu(t,i,a);return t.onSessionOpen&&typeof l.session.id=="string"&&l.session.id!==""&&t.onSessionOpen(a,l.session.id),l.gone.onGone(()=>{r?.evict(a,l)}),l},s=new Yn({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"?()=>ji({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:t.catalogRows??(n?()=>Au(n):null),listPrices:n?()=>xi(n):null,shared:t.catalogRows?async()=>{let i=await t.catalogRows();return vi(i)}:e.lane==="api-key"?()=>bi({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:Nu});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp},Ge({appSlug:t.defaultApp}))),s}function Uu(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,a=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
90
|
+
`)},l=(d,c)=>{let f=o.get(c);if(f)return f;let h=new Xn({min:n.min,max:n.max,idleGraceMs:n.idleGraceMs,inFlightCap:n.inFlightCap,replicaId:r,openSlot:async m=>{let _=Mu(t,d,c,{concurrencyKey:m.concurrencyKey});return _.gone.onGone(()=>h.markSessionDead(_)),await Kr(_.session),a(`slot attached pool=${c} slot=${m.concurrencyKey} session=${_.session.id??"(no id)"}`),_},closeSlot:async m=>{m.gone.dispose(),m.audioDispose?.(),await m.session.end()},onDetach:(m,_)=>a(`slot detached pool=${c} slot=${m.concurrencyKey} reason=${_}`),terminalOpenFailure:m=>m instanceof le.SessionFailedError&&Cs(m)});return s.set(c,{target:d,env:n}),o.set(c,h),h},u=async(d,c)=>{let f=s.get(c);if(f)try{let h=await e.poolTuningFor(d);l(d,c).retune({min:h?.min??f.env.min,max:h?.max??f.env.max,inFlightCap:h?.in_flight_cap??f.env.inFlightCap,idleGraceMs:h?.idle_grace_s!==void 0?h.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:h?.warm_wait_s!==void 0?h.warm_wait_s*1e3:void 0})}catch(h){a(`pool tuning refresh failed pool=${c} reason=${h instanceof Error?h.message:String(h)}`)}};return{async boot(){if(t.defaultApp===null)return;let d={appSlug:t.defaultApp};await l(d,Ge(d)).boot()},async sessionFor(d){let c=await e.resolveTargetFor(d),f=Ge(c),h=l(c,f);await u(c,f);let m=await h.acquire({timeoutMs:h.requestWaitMs}),_=i.get(m.entry)??[];return _.push(m),i.set(m.entry,_),{app:f,entry:m.entry,identity:dn(c)}},async warmFor(d){let c=await e.resolveTargetFor(d);await l(c,Ge(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)u(c,d).then(()=>{let f=o.get(d);f&&f.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 Dm(t){return(0,le.isWakingPhase)(t?.name)?t?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?le.DEFAULT_WHEN_LIVE_TIMEOUT_MS:le.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:le.DEFAULT_WHEN_LIVE_TIMEOUT_MS}async function Kr(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:Dm(t.phase),signal:e})}async function Fm(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 Lu(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 Vr(t){return t.reason instanceof Error?t.reason:new Error("the client socket closed")}function $s(t,e=ei,n,r,o=Ro,s){let i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,c=p=>{let g=p.session.id;return typeof g=="string"&&g.length>0?g:null},f="lane",h=p=>{let g=Rt(p);if(!s||!g||g.app!==f)return null;let y=s.entryFor(g.key);if(!y)throw new q(`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}},m=async p=>h(p)?.entry??(await t.sessionForHandle(p)).entry,_=p=>{let g=i.get(p);if(!g){let y={waiting:0,gone:new AbortController};d.set(p,y),g=(async()=>{if(await Kr(p.session,y.gone.signal),y.gone.signal.aborted)throw Vr(y.gone.signal);d.get(p)===y&&d.delete(p);let S=await Zs(p.session,await e());return Object.assign(S,{sessionId:p.session.id})})(),i.set(p,g),g.then(S=>{i.get(p)===g&&(p.audioDispose=()=>S.dispose())},()=>{}),g.catch(()=>{i.get(p)===g&&i.delete(p)}),g.then(()=>{d.get(p)===y&&d.delete(p)},()=>{d.get(p)===y&&d.delete(p)})}return g},R=p=>{let g=u.get(p);return g||(g=(async()=>{let y=await _(p);return{appendInputAudio:(S,x)=>y.appendInputAudio(S,x),onOutputAudio:S=>y.onOutputAudio(S),sessionId:c(p)}})(),u.set(p,g),g.catch(()=>{u.get(p)===g&&u.delete(p)})),g},v=async(p,g,y,S=!1)=>{let x=()=>S?Lu(p.session):Fm(p.session);if(y?.aborted){let k=d.get(p);throw(i.get(p)===void 0||k!==void 0&&k.waiting===0)&&await x().catch(()=>{}),Vr(y)}let E=g(p),I=d.get(p);return I!==void 0&&I.waiting++,y===void 0?E:new Promise((k,O)=>{let w=()=>{I!==void 0&&--I.waiting===0&&d.get(p)===I&&(I.gone.abort(),d.delete(p),i.delete(p),u.delete(p),x().catch(()=>{})),O(Vr(y))};y.addEventListener("abort",w,{once:!0});let A=()=>y.removeEventListener("abort",w);E.then(T=>{A(),k(T)},T=>{A(),O(T)})})},b=async(p,g,y)=>{try{return await y}catch(S){throw(S instanceof q||S instanceof le.SessionFailedError&&Cs(S))&&(t.evict(p,g),S instanceof le.SessionFailedError&&n?.(p,S.kind==="never-live"?"never-live":"create-failed")),S}};return{createResponse:Ou({sessionFor:s?async p=>{let g=await t.resolveTargetFor(p);if(g.sharedApp)try{let y=await s.sessionFor(p,g);return{app:y.app,entry:y.entry,identity:y.identity}}catch(y){if(y instanceof ct)return r?r.sessionFor(p):t.sessionFor(p);if(y instanceof Le)return console.error(`[pooler-fallback] pooler channel failed for ${p} (${y.name} ${y.code}: ${y.message}) \u2014 serving via the per-request path`),r?r.sessionFor(p):t.sessionFor(p);throw y}return r?r.sessionFor(p):t.sessionFor(p)}:r?p=>r.sessionFor(p):p=>t.sessionFor(p),sessionIdOf:p=>c(p),evict:(p,g)=>{s&&s.owns(g)?s.evict(g):r?r.evict(g):t.evict(p,g)},onAdmissionVerdict:(p,g,y)=>{Cs(y)&&(s&&s.owns(g)?s.evict(g):r?r.markSessionDead(g):t.evict(p,g),n?.(p,y.kind==="never-live"?"never-live":"create-failed"))},createStream:async(p,g)=>{try{await Kr(p.session);let y=na(is(await p.responses.responses.create(g),p.gone),o);if(!r&&!s)return y;let S=p;return(async function*(){try{yield*y}catch(E){throw ra(E)&&(s&&s.owns(S)?s.evict(S):r&&(E instanceof q?r.markSessionDead(S):r.evict(S))),E}finally{s&&s.owns(S)?s.release(S):r?.end(S)}})()}catch(y){throw s&&s.owns(p)?s.release(p):r&&r.end(p),y}}}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(p,g)=>t.supportsImages(p,g),listImageModels:()=>t.imageModelList(),catalogIdentity:p=>t.catalogIdentityFor(p),servingAppSlug:async p=>await t.servingAppSlugFor(p),supportsAudio:p=>t.supportsAudio(p),supportsSpeech:p=>t.supportsSpeech(p),speechVoices:p=>t.speechVoices(p),supportsTranscription:p=>t.supportsTranscription(p),transcriptStreamFor:p=>t.transcriptStreamFor(p),listSpeechToTextModels:()=>t.speechToTextModelList(),openAudio:async(p,g)=>{let{app:y,entry:S}=await t.sessionFor(p);return await b(y,S,v(S,_,g))},openAudioOn:async(p,g,y,S)=>{let x=h(p);if(x){let O=x.entry.session;return Tu(O)}let{app:E,entry:I}=await t.sessionForHandle(p);if(S&&I.session.phase?.name!=="live"){let O=I.session.phase?.name;S({status:O==="queued"||O==="waiting_for_capacity"?O:"pending",reason:`the dial's session is ${O??"not yet admitted"} \u2014 the connection waits for admission`})}let k=Rt(p)?.app.startsWith(ot)??!1;return await b(E,I,v(I,R,g,k))},openTurnsOn:async function*(p,g){if(g?.aborted)throw Vr(g);let y=await m(p);yield*Di(y.session,g)},openVideoOn:async p=>{let g=h(p);if(g)return Cu(g.entry.session);let{entry:y}=await t.sessionForHandle(p),S=a.get(y);return S||(S=no(y.session),a.set(y,S)),S},openVideo:async p=>{let{entry:g}=await t.sessionFor(p),y=a.get(g);return y||(y=no(g.session),a.set(g,y)),y},openVideoOut:async p=>{let{entry:g}=await t.sessionFor(p),y=l.get(g);return y||(y=ni(g.session),l.set(g,y)),y},sessionHandle:async p=>{if(s){let g=await t.resolveTargetFor(p);if(g.sharedApp){let y=await s.sessionFor(p,g),S=c(y.entry);if(S===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return cn(f,S)}}return(await t.handleFor(p)).handle},dedicatedSessionHandle:async p=>{if(!(await t.resolveTargetFor(p)).sharedApp)return(await t.handleFor(p)).handle;let{app:y,entry:S}=await t.dedicatedSessionFor(p);return cn(y,Nu(S))},releaseSessionHandle:p=>{let g=Rt(p);if(!g)return;if(g.app.startsWith(ot)){(async()=>{let S=null;try{S=(await t.sessionForHandle(p)).entry}catch{return}await Lu(S.session).catch(()=>{}),await t.evict(g.app,S)})();return}if(!s||g.app!==f)return;let y=s.entryFor(g.key);y&&s.release(y)},speechSessionHandle:async p=>(await t.speechHandleFor(p)).handle,evictSpeechSession:async p=>{let{app:g,entry:y}=await t.sessionForHandle(p);await t.evict(g,y)},createResponseOn:async(p,g,y)=>{let S=await m(p);await Kr(S.session);let x=y!==void 0&&h(p)?new ht({...S.session,consumerId:y},{sessionTag:y}):S.responses;return is(await x.responses.create(g),S.gone)},onSessionEnd:async(p,g)=>{let y=h(p);if(y)return y.entry.gone.onGone(I=>g({timeLeftMs:null,reason:I.message}));let{entry:S}=await t.sessionForHandle(p),x=S.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 E=!1;return x.onPhase(I=>{if(E||!Um.has(I.name))return;E=!0;let k=x.endsAt??null;g({timeLeftMs:k?Math.max(0,k.getTime()-Date.now()):null,reason:I.reason??`session ${I.name}`})})}}}var Ms=8080,Nn="serve",Du="0.0.0.0";function Bm(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Fu(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Ms:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=la(nr(Bm(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?nr(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=i?{catalogUrl:nr(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let c=u?{keyId:d,key:u}:void 0,f={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},h=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],m=h.filter((w,A)=>Object.values(f)[A]==="");if(m.length!==0&&m.length!==h.length)throw new Error(`${h.join(", ")} must be set together (or all left unset) \u2014 missing: ${m.join(", ")}, which would half-configure the lane plane`);let _=m.length===0?f:void 0,R={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},v=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],b=v.filter((w,A)=>Object.values(R)[A]==="");if(b.length!==0&&b.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${b.join(", ")}, which would half-configure the pooler cutover`);let p=b.length===0?R:void 0,g={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},y=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=y.filter((w,A)=>Object.values(g)[A]==="");if(S.length!==0&&S.length!==y.length)throw new Error(`${y.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let x=g.issuers.split(",").map(w=>w.trim()).filter(w=>w!=="");if(x.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let E=Number(g.tokenTtlS);if(S.length===0&&(!Number.isFinite(E)||E<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(g.tokenTtlS)}`);let I=S.length===0?{jwksBaseUrl:g.jwksBaseUrl,issuers:x,tokenTtlS:E}:void 0,k=(t.URUN_WORKOS_ISSUERS??"").trim(),O=k.split(",").map(w=>w.trim()).filter(w=>w!=="");if(k!==""&&O.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let w of O){let A;try{A=new URL(w)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(w)}`)}if(A.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${w}) \u2014 the issuer is the user rung's trust root`)}return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:c,lane:_,pooler:p,machine:I,...O.length>0?{userIssuers:O}:{}}}var Ns=512;function Qt(t){return`urun-inference-proxy-${(0,Dn.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var Zt=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let u=`px_${(0,Dn.randomUUID)()}`;return Hl(s,a,u,u)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Nn,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:$u(process.env,process.env.HOSTNAME)??void 0},r=Ls(n),o=n.decisionPool?Uu(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label($s(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Ns;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},zr=512,Us=1024,Un=class extends Error{constructor(){super(`conversation capacity reached (${zr} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Hm(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(Et))return{concurrencyKey:e};if(n.startsWith(Et)||n.startsWith(ot))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(Et)||n.startsWith(ot)||t.set(n,r)}}}function jm(t,e,n,r,o){let s=Ls({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Nn,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...Hm(r,o)});return{clients:$s(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var en=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${Qt(e.apiKey)}:live`:`${Qt(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):jm(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=zr;){let e=!1;for(let[n,r]of this.byCaller){for(let[o,s]of r)if(!(s.attachments>0)){r.delete(o),this.dropHandleIndexFor(n,o),s.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new Un}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,(0,Dn.randomUUID)(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,l,u)=>s().backhaul.clients.createResponseOn(a,l,u),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let u=s().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(a)},i.openAudioOn=async(a,l,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return d(a,l,u)},i.openVideoOn=async(a,l)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,l)},i.openTurnsOn=(a,l)=>{let u=s().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Us;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),u=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||u===void 0?void 0:u.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new q("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};var Yr="/inference-usage",Bu=25e3;var qm=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Hu(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=qm.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var Xr=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Yr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Bu)})}catch(i){throw new oe(`the uRun usage surface (POST ${Yr}) could not be reached within ${Bu}ms: ${Hu(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new J("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new oe(`the uRun usage surface (POST ${Yr}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new oe(`the uRun usage surface (POST ${Yr}) answered HTTP ${o.status} with a body that is not JSON: ${Hu(i)}`)}return dl(s,this.opts.onRejectedRow)}};var qs="/inference-ledger",Gs=1e4,tn=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Bs=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},ae=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Hs=class extends J{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},js=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Gm=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",Ds],["output_minutes",Ds],["cost_nano_usd",Ds],["price_version",t=>t===null||typeof t=="string"]];function Wm(t){for(let[e,n]of Gm){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Jm(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Wm(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ds(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Fs(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Vm(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function ju(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Km(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&ju(t.started_at,n.started_at)&&ju(t.completed_at,n.completed_at)&&Fs(t.prompt_tokens,n.prompt_tokens)&&Fs(t.completion_tokens,n.completion_tokens)&&Fs(t.output_units,n.output_units)&&Vm(t.output_minutes,n.output_minutes)}function zm(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
|
|
91
|
+
`)}async function Ym(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(zm(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Ws(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new ae(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new ae(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new ae(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new ae(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new ae(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new ae(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new ae(`${e} answered a BLANK ${u} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),l=o!=null;if(l&&(i===null||a!==null))throw new ae(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!l&&(i!==null||a===null))throw new ae(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var nn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${qs}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Ym(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new ae(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Gs)})}catch(u){throw new ae(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=Jm(u);throw d.status==="found"&&Km(n,d.row)?new Bs(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new tn(`inference_id ${n.inference_id} is ALREADY TAKEN by a ledger row this org cannot read. The id space is a global primary key, so this is not a retry and cannot be this proxy's own write \u2014 either two orgs collided on a uuid, or a row was written for this id by somebody else.`,"duplicate_foreign"):new tn(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new Hs("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let u=await s.text().catch(c=>`<body unreadable: ${c instanceof Error?c.message:String(c)}>`),d;try{let c=JSON.parse(u);if(c!==null&&typeof c=="object"&&"error"in c){let f=c.error;f!==null&&typeof f=="object"&&"code"in f&&(d=f.code)}}catch{}throw d==="ledger_signature_invalid"?new js(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+u.slice(0,400)):new ae(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new ae(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new ae(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Ws(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new ae(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};var Js=5e3,Xm=1e3,Qm=1500,Vs=3e3,Zm="/api/client-tokens";function Qr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function qu(t,e,n,r){Qr(t,e,{error:{message:n,type:r}})}async function eg(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Zm}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Vs)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Vu(t){let e=t.resolver??new _t({gatewayUrl:t.baseUrl}),n=t.machine?new Gr({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new Wr({issuers:t.userIssuers,gatewayUrl:t.baseUrl}):null,o=new zt(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),s=null,i=null,a=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let w=new Ju.default(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),A=wu({redis:w});return{registry:au({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:Jl({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(P,L)=>s?.onHostedChange(P,L)??(()=>()=>{}),roomDoc:(P,L)=>{if(!s)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return s.roomDoc(P,L)},metrics:o,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(P,L)=>A.rows().then(N=>{let V=go(N,L);return V?.warm_wait_s!==void 0?V.warm_wait_s*1e3:void 0}),currentReleaseOf:lu(w),closeLane:P=>s?.closeLane(P)}),catalog:A,redis:w}})(),l=t.registry??new Zt({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>eg(t.baseUrl)),d=async()=>{let w=null;for(let P of l.decisionPools()){w=P;break}if(!w)return null;let A=w.stats();if(A.some(P=>P.draining))return{ok:!1,detail:"decision pool draining"};if(A.every(P=>P.attached===0&&P.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let T=await w.pingReady(Qm);return{ok:T,detail:T?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new Xr({apiUrl:t.apiUrl}),f=t.ledgerClient??new nn({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),h=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();h&&m&&(async()=>{try{await l.decisionWarmerFor({orgId:h,apiKey:m})?.warmFor(Ar)}catch(w){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(w instanceof Error?w.message:w)}
|
|
92
|
+
`)}})();let _=async w=>As(Xt(w.headers.authorization),e,n,r),R=async w=>{let A=await _(w);if(A.billingAudience==="platform"&&A.creditsAdmissionOk===!1){let T=A.creditsRefusalReason;throw new Yt(T==="spend_cap_reached"||T==="insufficient_credits"?T:void 0)}return A},v=w=>w instanceof J?{status:w.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:w instanceof Yt?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...w.code!==void 0?{code:w.code}:{}}:w instanceof $e?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:w.detail}:null,b={write:(w,A)=>f.write(Xt(w.headers.authorization),A),observe:w=>o.observeLedger(w),...t.ledgerLog?{report:t.ledgerLog}:{}},p=Il({clients:async w=>l.clientsFor(await R(w)),usage:{authorize:w=>Xt(w.headers.authorization),lookup:(w,A)=>c.lookup(w,A)},statusOf:v,...t.requestLog?{requestLog:t.requestLog}:{},observe:w=>o.observe(w),ledger:b}),g=ba({authorize:async w=>{await R(w)},...t.lane?{secret:t.lane.tokenSecret}:{}}),y=null,S=null,x=(0,Gu.createServer)((w,A)=>{let T=new URL(w.url??"/","http://localhost");(async()=>{if(w.method==="GET"&&T.pathname==="/healthz"){Qr(A,200,{ok:!0});return}if(w.method==="GET"&&T.pathname==="/readyz"){let N=Date.now();if((!y||N-y.at>=Js)&&(y={at:N,...await u()}),!S||N-S.at>=Xm){let Y=await d();S=Y===null?{at:N,ok:!0,detail:null}:{at:N,ok:Y.ok,detail:Y.detail}}let V=(y?.ready??!1)&&S.ok,H=S.detail===null?y?.detail??"control plane not yet probed":`${y?.detail??"control plane not yet probed"}; ${S.detail}`;Qr(A,V?200:503,{ok:V,control_plane:H});return}if(w.method==="GET"&&T.pathname==="/lanez"){Qr(A,200,{pools:a?await a.registry.status():null});return}let P=T.pathname==="/v1"||T.pathname.startsWith("/v1/"),L=T.pathname.startsWith("/partners/");if(!P&&!L){qu(A,404,`no route for ${w.method} ${T.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}await g(w,A)||p(w,A)})().catch(P=>{if(!A.headersSent){qu(A,500,String(P instanceof Error?P.message:P),"proxy_error");return}A.end()})}),E=t.conversations??new en({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),I=new WeakMap,k=[wo(x,{authenticate:async w=>{let A=await As(w,e,n,r),T=E.connectionFor(A);return{clients:T.clients,scope:Qt(A.apiKey),onBindResumeHandle:T.bindResumeHandle,clientsForResume:T.clientsForResume,release:T.release}}}),Oo(x,{clients:async w=>l.clientsFor(await R(w)),statusOf:v}).close,ur(x,{resolver:{resolve:async(w,A,T)=>{let P=await R(w),L=E.connectionFor(P,Ll(w)),N;try{N=await $l(Zo(L.clients,t.realtimeCompanions),Pl(w),A,Cl(w),T)}catch(Y){throw L.release().catch(()=>{}),Y}let V=N.release,H={...N,release:async()=>{await V?.(),await L.release()}};return I.set(H,P.orgId),H}},onSessionEnded:w=>{br({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:it(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:w.binding.model??null,stream:null,org:I.get(w.binding)??null,duration_ms:w.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:w.connected_ms/1e3,session_id:w.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:w.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:b,req:w.req})}})];if(t.lane&&a){let w=t.lane,A=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;s=yu(x,{verifyToken:(P,L)=>ss(P,L,w.tokenSecret,void 0,A),selfAddress:w.selfAddress,laneTenantOf:P=>a.redis.get(`lane_tenant:${P}`),onLaneTenantMissing:()=>o.observeLaneDocTenantMissing(),previousTokenSecret:A,hostRegistry:{setHost:(P,L)=>a.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${P}`,L,String(hu)),delHost:P=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${P}`,w.selfAddress)}}),i=tu(x,{verifyToken:(P,L)=>ss(P,L,w.tokenSecret,void 0,A),selfAddress:w.selfAddress,hostOf:async P=>{let L=await a.redis.get(`lane_hosts:${P}`);return L&&L.trim()!==""?L.trim():null},podToPodDial:(P,L,N)=>new Promise((V,H)=>{(async()=>{let Y=await a.redis.get(`lane_tenant:${P}`),D=Cn(P,w.tokenSecret,void 0,void 0,Y||void 0),j=`ws://${N}/stream/${encodeURIComponent(P)}/${encodeURIComponent(L)}?token=${encodeURIComponent(D)}`,K=new Wu.default(j,Mr(L));K.once("open",()=>V(K)),K.once("error",H)})().catch(H)})});let T=a;k.push(async()=>{await s.close(),await i.close(),await T.registry.close(),T.redis.quit().catch(()=>{})})}x.on("upgrade",(w,A)=>{let T=new URL(w.url??"/","http://localhost");T.pathname===Wn||T.pathname===Ao||T.pathname===bn||s!==null&&T.pathname.startsWith("/doc/")||i!==null&&T.pathname.startsWith("/stream/")||A.destroyed||(A.write(`HTTP/1.1 404 Not Found\r
|
|
92
93
|
Connection: close\r
|
|
93
94
|
\r
|
|
94
|
-
no WS route for ${
|
|
95
|
+
no WS route for ${T.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),A.destroy())});let O=async()=>{for(let w of k)await w();await E.detachAll()};return{server:x,metricsServer:Br(o),metrics:o,edgeIdentityServer:jr(),registry:l,closeAll:()=>l.closeAll(),closeWebSockets:O}}0&&(module.exports={ANONYMOUS_KEY_ID,BIND_HOST,BUCKET_DOMAIN,BoundedLabel,ControlPlaneUnavailableError,ConversationBackhauls,ConversationCapacityError,DEFAULT_PORT,EDGE_IDENTITY_PORT,EDGE_KEY_FINGERPRINT_HEADER,EDGE_KEY_ID_HEADER,InferenceMetrics,LEDGER_FUNCTION_PATH,LEDGER_WRITE_TIMEOUT_MS,LedgerClient,LedgerDuplicateError,LedgerSurfaceError,MAX_CACHED_KEYS,MAX_CONVERSATIONS,MAX_CONVERSATION_HANDLES,MAX_MODEL_LABELS,MAX_ORG_LABELS,MAX_TENANTS,METRICS_PATH,METRICS_PORT,NO_MODEL_LABEL,ORG_BINDING_TTL_MS,OTHER_LABEL,OrgResolver,ProxyAuthError,READINESS_TIMEOUT_MS,READINESS_TTL_MS,SERVE_FUNCTION,TIER_DOMAIN,TenantRegistry,bearerFrom,bearerTokenOf,createEdgeIdentityServer,createHostedProxy,createMetricsServer,edgeBucketId,edgeTierFingerprint,laneOf,parseLedgerRecorded,resolveHostedConfig,statusClassOf,tenantSubject});
|