@urun-sh/openai 0.5.4 → 0.5.6
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-BYx3YLGo.d.ts → ResponsesClient-BE3-hx3m.d.ts} +2 -0
- package/dist/{ResponsesClient-Dft3bg3b.d.cts → ResponsesClient-DjZWjlFH.d.cts} +2 -0
- package/dist/chunk-2T2YYBVX.js +1 -0
- package/dist/chunk-3WAJD62J.js +4 -0
- package/dist/{chunk-K23AZPI4.js → chunk-5HKWNK3O.js} +1 -1
- package/dist/chunk-7M6LY6DR.js +2 -0
- package/dist/chunk-BSHT6RZZ.js +1 -0
- package/dist/{chunk-GBBY3PCZ.js → chunk-FP4RSAIE.js} +1 -1
- package/dist/chunk-HR5H6S7L.js +1 -0
- package/dist/chunk-NY23USZF.js +57 -0
- package/dist/chunk-VLRMJRLS.js +6 -0
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +17 -2
- package/dist/gemini-live.d.ts +7 -2
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +65 -37
- package/dist/hosted/bin.js +3 -3
- package/dist/hosted/index.cjs +46 -19
- package/dist/hosted/index.d.cts +760 -272
- package/dist/hosted/index.d.ts +203 -107
- 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/{models-NYMZrklp.d.cts → models-DUdx_Y6X.d.cts} +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.d.cts +1 -1
- package/dist/pi-extension/index.d.ts +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +48 -48
- package/dist/proxy/cli.cjs +54 -40
- package/dist/proxy/cli.js +14 -14
- package/dist/proxy/index.cjs +33 -22
- package/dist/proxy/index.d.cts +546 -4
- package/dist/proxy/index.d.ts +185 -4
- package/dist/proxy/index.js +1 -1
- package/dist/responses-turn-Dr37N3kH.d.ts +486 -0
- package/dist/responses-turn-tNUHq5b0.d.cts +1807 -0
- package/dist/{translator-C9uPKypK.d.ts → translator-BCoRFaTs.d.ts} +1 -1
- package/dist/{translator-CcDBEfvm.d.cts → translator-Bh0Bp_Ie.d.cts} +3 -3
- package/dist/{video-out-D20UuJ8G.d.cts → video-out-CCksIcj8.d.cts} +5 -5
- package/package.json +12 -11
- package/dist/chunk-4MSBS7M6.js +0 -1
- package/dist/chunk-5NXM4IO3.js +0 -2
- package/dist/chunk-CWJRDBDC.js +0 -1
- package/dist/chunk-OI2OY32M.js +0 -1
- package/dist/chunk-RQBD4OAA.js +0 -6
- package/dist/chunk-STFRT5OY.js +0 -1
- package/dist/chunk-VNM4M4P3.js +0 -40
- package/dist/server-DuH_5OD9.d.ts +0 -84
- package/dist/server-wmUnMewW.d.cts +0 -206
- /package/dist/{chunk-YSFSRI3D.js → chunk-5CCJUNH7.js} +0 -0
- /package/dist/{models-NYMZrklp.d.ts → models-DUdx_Y6X.d.ts} +0 -0
- /package/dist/{video-out-CWesbk12.d.ts → video-out-IGQ4YQ-c.d.ts} +0 -0
package/dist/hosted/index.cjs
CHANGED
|
@@ -1,34 +1,61 @@
|
|
|
1
|
-
"use strict";var Pt=Object.create;var pe=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var Nt=Object.getOwnPropertyNames;var $t=Object.getPrototypeOf,Lt=Object.prototype.hasOwnProperty;var Mt=(t,n)=>{for(var e in n)pe(t,e,{get:n[e],enumerable:!0})},ze=(t,n,e,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Nt(n))!Lt.call(t,r)&&r!==e&&pe(t,r,{get:()=>n[r],enumerable:!(o=Ut(n,r))||o.enumerable});return t};var fe=(t,n,e)=>(e=t!=null?Pt($t(t)):{},ze(n||!t||!t.__esModule?pe(e,"default",{value:t,enumerable:!0}):e,t)),Dt=t=>ze(pe({},"__esModule",{value:!0}),t);var Bn={};Mt(Bn,{BIND_HOST:()=>At,ControlPlaneUnavailableError:()=>W,DEFAULT_PORT:()=>Fe,MAX_CACHED_KEYS:()=>Ve,MAX_TENANTS:()=>je,ORG_BINDING_TTL_MS:()=>De,OrgResolver:()=>te,ProxyAuthError:()=>F,READINESS_TIMEOUT_MS:()=>We,READINESS_TTL_MS:()=>Je,SERVE_FUNCTION:()=>Re,TenantRegistry:()=>ne,bearerFrom:()=>ke,createHostedProxy:()=>Ct,resolveHostedConfig:()=>Et,tenantSubject:()=>Ge});module.exports=Dt(Bn);var Tt=require("http");var tn=require("http");var Zt=require("crypto"),en=require("ws");function K(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Vt={chat:!0,code:!0,agent:!0,vl:!0},Ye={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ht(t){let n=t.toLowerCase();return Object.hasOwn(Ye,n)?Ye[n]:null}function Ee(t){let n=t.engine_args?.context_length;return typeof n=="number"&&Number.isFinite(n)&&n>0?n:null}function Qe(t,n){let e=n.filter(i=>K(`${i.model_id}-${i.variant}`)===t);if(e.length===1)return e[0];if(e.length>1)return Xe(e);let o=n.filter(i=>K(i.model_id)===t),r=new Set(o.map(i=>i.variant));return o.length>0&&r.size===1?Xe(o):null}function Xe(t){let n=t[0],e=s=>t.every(a=>(a[s]??void 0)===(n[s]??void 0))?n[s]:void 0,o=t.map(Ee),r=o[0],i=r!=null&&o.every(s=>s===r)?r:null;return{model_id:n.model_id,variant:n.variant,gpu_spec:e("gpu_spec"),engine:e("engine"),task:e("task"),description:e("description"),size_gb:e("size_gb"),hf_repo:e("hf_repo"),engine_args:i!==null?{context_length:i}:{},updated_at:e("updated_at")}}function Ze(t){let n=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(n)?Math.floor(n/1e3):0}function et(t,n){let e=Qe(t,n);if(!e)return{id:t,object:"model",created:0,owned_by:"urun"};let o=Ee(e);return{id:t,object:"model",created:Ze(e),owned_by:"urun",name:`${e.model_id}:${e.variant}`,...e.description?{description:e.description}:{},...e.task?{task:e.task}:{},...e.engine?{engine:e.engine}:{},...e.gpu_spec?{gpu_spec:e.gpu_spec}:{},...o!==null?{context_length:o}:{}}}function tt(t,n){let e=[];for(let o of t){let r=Qe(o,n);if(!r||!r.task||Vt[r.task]!==!0)continue;let i=Ee(r),s={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};i!==null&&(s.max_tokens={type:"integer",min:1,max:i,unit:"token"}),e.push({schema_version:"2.4",id:o,name:`${r.model_id}:${r.variant}`,created:Ze(r),quantization:Ht(r.variant),description:r.description??"",hugging_face_id:r.hf_repo?r.hf_repo.split("@")[0]??r.hf_repo:"",input_modalities:[{type:"text",...i!==null?{supported_inputs:{max_context_length:{value:i,unit:"token"}}}:{}},...r.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:s}]})}return{data:e}}var U=class extends Error{},H=class extends Error{},Oe="urs1.";function Bt(t,n){return Oe+Buffer.from(JSON.stringify([t,n]),"utf8").toString("base64url")}function Ft(t){if(!t.startsWith(Oe))return null;try{let n=JSON.parse(Buffer.from(t.slice(Oe.length),"base64url").toString("utf8"));if(Array.isArray(n)&&typeof n[0]=="string"&&typeof n[1]=="string")return{app:n[0],key:n[1]}}catch{}return null}async function ot(t){let n=t.fetchImpl??fetch,e=`${t.apiUrl.replace(/\/+$/,"")}/apps`,o=await n(e,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${e} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${e})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${e} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}var nt=6e4,me=class{constructor(n){this.opts=n}opts;pool=new Map;appsCache=null;rowsCache=null;seed(n,e){this.pool.set(n,Promise.resolve(e))}async deployedApps(){if(!this.opts.listApps)return[];let n=this.opts.appsTtlMs??nt;if(this.appsCache&&Date.now()-this.appsCache.at<n)return this.appsCache.apps;let e=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:e},e}async catalogRows(){if(!this.opts.listCatalog)return[];let n=this.opts.appsTtlMs??nt;if(this.rowsCache&&Date.now()-this.rowsCache.at<n)return this.rowsCache.rows;let e=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:e},e}servable(n){return n.filter(e=>e.function_name===this.opts.fnName&&e.deployment_status==="active").map(e=>e.app_slug)}async availableIds(){let n=this.opts.defaultApp,e=new Set(n===null?[]:[n]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))e.add(r);for(let r of this.pool.keys())e.add(r);let o=[...e].filter(r=>r!==n).sort();return n===null?o:[n,...o]}async noDefaultApp(n){let e=await this.availableIds(),o=e.length>0?e.join(", "):"(none deployed)";throw new U(n===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed "${this.opts.fnName}" apps; available models: ${o}`:`model "${n}" does not name a deployed "${this.opts.fnName}" app in your org, and this endpoint has no default model to fall back to; available models: ${o}`)}async resolveApp(n){let e=(n??"").trim(),o=this.opts.defaultApp;if(!e||e==="urun")return o===null?this.noDefaultApp(e):o;let r=K(e);if(r===o)return o;if(this.pool.has(r))return r;if(this.opts.listApps){let i=await this.deployedApps(),s=this.servable(i);if(s.includes(r))return r;let a=s.filter(c=>c.startsWith(`${r}-`));if(a.length===1)return a[0];if(a.length>1)throw new U(`model "${e}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=i.find(c=>c.app_slug===r||c.app_slug.startsWith(`${r}-`));if(u)throw new U(`model "${e}" maps to app "${u.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${e}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let s=(await this.opts.listCatalog()).find(a=>e===a.model_id||e===`${a.model_id}:${a.variant}`||r===K(a.model_id)||r===K(`${a.model_id}-${a.variant}`));if(s)throw new U(`model "${e}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${s.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(e):o}async sessionFor(n){let e=await this.resolveApp(n),o=this.pool.get(e);return o||(o=Promise.resolve(this.opts.openSession(e)),this.pool.set(e,o),o.catch(()=>this.pool.delete(e))),{app:e,entry:await o}}keyOf(n){let e=this.opts.sessionKey;if(!e)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=e(n);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(n){let{app:e,entry:o}=await this.sessionFor(n);return{app:e,handle:Bt(e,this.keyOf(o))}}async sessionForHandle(n){let e=Ft(n);if(!e)throw new H(`malformed session handle ${JSON.stringify(n)} \u2014 not issued by this proxy`);let{app:o,key:r}=e,i=this.pool.get(o),s=i?await i.then(a=>a,()=>null):null;if(s===null)throw new H(`the session behind this handle (app "${o}") 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(s)!==r)throw new H(`the session behind this handle (app "${o}") 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:o,entry:s}}async evict(n,e){let o=this.pool.get(n);!o||await o.then(i=>i,()=>null)!==e||this.pool.get(n)!==o||(this.pool.delete(n),await this.opts.closeSession(e).catch(()=>{}))}async modelList(){let n=await this.availableIds(),e=await this.catalogRows().catch(()=>[]);return{object:"list",data:n.map(o=>et(o,e))}}async openRouterModels(){let n=await this.availableIds(),e=await this.catalogRows();return tt(n,e)}async closeAll(){let n=[...this.pool.values()];this.pool.clear();let e=[];if(await Promise.all(n.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){e.push(String(r instanceof Error?r.message:r))}})),e.length>0)throw new Error(`failed to close ${e.length} pooled session(s): ${e.join("; ")}`)}};var Ie=class{constructor(n,e){this.backend=n;this.opts=e}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(n){if(!this.source)throw new Error("startOutbound() not called");let e=Buffer.from(n,"base64"),o=Math.floor(e.byteLength/2),r=new Int16Array(o);for(let i=0;i<o;i++)r[i]=e.readInt16LE(i*2);this.source.onData(r)}async startInbound(n){if(n==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("rt-audio-out").track is null)');this.sink=this.backend.createSink(n),this.sink.onframe=e=>{let o=Buffer.from(e.samples.buffer,e.samples.byteOffset,e.samples.byteLength).toString("base64");for(let r of this.outHandlers)r(o)}}onOutputAudio(n){return this.outHandlers.add(n),()=>this.outHandlers.delete(n)}};async function it(t,n,e=1e4){let o=new Ie(n,{sampleRate:24e3}),r=await o.startOutbound();await t.stream("rt-audio-in").attach(r);let i=await jt(t,e);return await o.startInbound(i),o}function jt(t,n){let e=t.stream("rt-audio-out");return e.track!=null?Promise.resolve(e.track):new Promise((o,r)=>{let i,s=setTimeout(()=>{i?.(),r(new Error(`enableSessionAudio: no downstream audio track within ${n}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},n),a=u=>{u!=null&&(clearTimeout(s),i?.(),o(u))};i=e.on?.("track",a),e.track!=null&&a(e.track)})}var rt="rt-video-in",st=256e3;function at(t){let n=t.stream(rt),e=n.emit;if(typeof e!="function")throw new Error(`enableSessionVideo: session.stream('${rt}') 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 o=>{if(o.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(o.byteLength>st)throw new Error(`enableSessionVideo: frame is ${o.byteLength} bytes \u2014 over the ${st}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await e.call(n,o)}}}var Gt=24e3,ie=480,qt=111;async function Jt(){let t=await import("opusscript"),n=t.default??t;return new n(Gt,1,2048)}async function ut(){let t=await import("werift"),n=await Jt();return{createSource:()=>{let e=new t.MediaStreamTrack({kind:"audio"}),o=Math.random()*4294967295>>>0,r=Math.random()*65535&65535,i=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:e,onData:a=>{let u=new Int16Array(s.length+a.length);u.set(s,0),u.set(a,s.length);let c=0;for(;u.length-c>=ie;){let p=u.subarray(c,c+ie);c+=ie;let f=Buffer.from(p.buffer,p.byteOffset,p.byteLength),m=n.encode(f,ie);r=r+1&65535,i=i+ie>>>0;let w=new t.RtpHeader({version:2,payloadType:qt,sequenceNumber:r,timestamp:i,ssrc:o,marker:!1}),h=new t.RtpPacket(w,m);e.writeRtp(h)}s=u.slice(c)}}},createSink:e=>{let o={onframe:null};return e.onReceiveRtp.subscribe(i=>{let s;try{s=n.decode(i.payload)}catch{return}let a=new Int16Array(s.length/2);for(let u=0;u<a.length;u++)a[u]=s.readInt16LE(u*2);o.onframe?.({samples:a})}),o}}}var ge=require("@urun-sh/core"),Te="rt-video-out";var Wt="h264";function Kt(t,n){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${n}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${n}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${n}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${n}: header key must be a boolean`)}function zt(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let n=t[0]|t[1]<<8;if(t.byteLength<2+n)throw new Error(`decodeVideoOutRecord: truncated record (header says ${n} bytes, ${t.byteLength-2} present)`);let e;try{e=JSON.parse(new TextDecoder().decode(t.subarray(2,2+n)))}catch(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}let o=e;if(o===null||typeof o!="object"||o.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(o?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let r=o;Kt(r,"decodeVideoOutRecord");let i=t.subarray(2+n);if(i.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:r,au:i.slice()}}function ct(t){let n=t.stream(Te);if(typeof n.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${Te}') 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 e=new Set,o=new Set,r=new Set,i=u=>{for(let c of o)c(u)},s=!1,a=async()=>{for await(let u of n.messages()){if(!(u instanceof Uint8Array)){i(new Error(`openSessionVideoOutLane: "${Te}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let c;try{c=zt(u)}catch(p){i(p instanceof Error?p:new Error(String(p)));continue}for(let p of e)p(c)}for(let u of r)u()};return{codec:Wt,onOutputFrame:u=>(e.add(u),s||(s=!0,a().catch(c=>i(c instanceof Error?c:new Error(String(c))))),()=>e.delete(u)),onLaneError:u=>(o.add(u),()=>o.delete(u)),onEnd:u=>(r.add(u),()=>r.delete(u))}}var Xt=24e3,so=`audio/pcm;rate=${Xt}`,Qt=Buffer.alloc(960).toString("base64");var Ue=class t{startedAt=Date.now();requests={};models={};ttftMs=[];tokRates=[];tokensOut=0;charsOut=0;localInBytes=0;naiveInBytes=0;request(n,e,o){this.requests[n]=(this.requests[n]??0)+1,this.localInBytes+=e,this.naiveInBytes+=o}modelEntry(n){let e=this.models[n];if(e)return e;let o=Object.keys(this.models).length>=nn?"(other)":n;return this.models[o]??={requests:0,tokens_out:0}}model(n){this.modelEntry(n).requests+=1}track(n,e){let o=this,r=performance.now(),i=null,s=0;return(async function*(){for await(let u of n)u.type==="response.output_text.delta"&&typeof u.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-r),o.ttftMs.length>512&&o.ttftMs.shift()),s+=1,o.tokensOut+=1,o.charsOut+=u.delta.length,e!==void 0&&(o.modelEntry(e).tokens_out+=1)),yield u;let a=(performance.now()-(i??r))/1e3;s>0&&a>0&&(o.tokRates.push(s/a),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(n){if(!n.length)return null;let e=[...n].sort((o,r)=>o-r);return e[Math.floor(e.length/2)]}snapshot(){let n=Object.values(this.requests).reduce((e,o)=>e+o,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:n},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}}}};function $e(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function M(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function q(t,n,e,o="invalid_request_error"){M(t,n,{error:{message:e,type:o}})}function B(t,n,e,o){M(t,n,{type:"error",error:{type:e,message:o}})}function Le(t,n,e){if(n==="anthropic"){M(t,404,{type:"error",error:{type:"not_found_error",message:e.message}});return}M(t,404,{error:{message:e.message,type:"invalid_request_error",code:"model_not_found"}})}var nn=256,on=128;function Me(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,on)}var lt=64*1024*1024,he=class extends Error{};async function rn(t){let n=[],e=0;for await(let r of t){if(e+=r.length,e>lt)throw new he(`request body exceeds ${lt} bytes`);n.push(r)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Q(t,n,e,o){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:n,choices:[{index:0,delta:e,finish_reason:o}]}}var sn=256;function an(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 Ne=class{conversations=new Map;thread(n,e){let o=an(e);if(n==null)return o;let r=this.conversations.get(String(n));if(!r)throw new Error(`unknown previous_response_id ${String(n)} (proxy restarts drop stored responses)`);return[...r,...o]}remember(n,e,o){this.conversations.set(n,[...e,{role:"assistant",content:o}]);for(let r of this.conversations.keys()){if(this.conversations.size<=sn)break;this.conversations.delete(r)}}};function ae(t){let n=t?.output;return Array.isArray(n)?n.filter(e=>e.type==="function_call"):[]}function z(t){return t.find(n=>n.type==="response.completed")?.response??null}function ye(t){let n=t?.usage;if(!n||typeof n!="object")return null;let e=s=>typeof s=="number"&&Number.isFinite(s)&&s>=0?s:0,o=e(n.input_tokens),r=e(n.output_tokens);if(o===0&&r===0)return null;let i=e(n.total_tokens)||o+r;return{input_tokens:o,output_tokens:r,total_tokens:i}}function dt(t){let n=ye(t);return n?{prompt_tokens:n.input_tokens,completion_tokens:n.output_tokens,total_tokens:n.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function ft(t){let n=t?.output;if(!Array.isArray(n))return"";let e="";for(let o of n)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let r of o.content)r.type==="reasoning_text"&&(e+=String(r.text??""));return e}function ue(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 Y=class{calls=new Map;add(n){let e=this.calls.get(n.tool_index),o=!e;return e||(e={args:""},this.calls.set(n.tool_index,e)),n.call_id&&(e.id=n.call_id),n.name&&(e.name=n.name),e.args+=n.delta,{call:e,isNew:o}}get size(){return this.calls.size}items(){return[...this.calls.entries()].map(([n,e])=>({type:"function_call",call_id:e.id??`call_${n}`,name:e.name??"",arguments:e.args}))}},un=["<tool_call>","<function="];function cn(t){return un.find(n=>t.includes(n))}function Z(t,n){return`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function ee(t,n,e){if(!(!t||n>0))return cn(e)}function ln(t){if(Array.isArray(t))return t.map(n=>{let e=n.function;return!e||typeof e!="object"?n:{type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:e.strict}})}var we=class extends Error{};function dn(t,n){return Array.isArray(n)?n.map(e=>{let o=e;if(o.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:o.text};if(o.type==="image_url"){let r=o.image_url??{};return{type:"input_image",image_url:r.url,detail:r.detail}}throw new we(`unsupported chat content part type "${String(o.type)}" \u2014 the proxy translates text and image_url parts`)}):n}function pn(t){let n=[];for(let e of t){if(e.role==="tool"){n.push({type:"function_call_output",call_id:e.tool_call_id,output:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")});continue}if(e.role==="assistant"&&Array.isArray(e.tool_calls)){typeof e.content=="string"&&e.content&&n.push({role:"assistant",content:e.content});for(let o of e.tool_calls){let r=o.function??{};n.push({type:"function_call",call_id:o.id,name:r.name,arguments:r.arguments})}continue}n.push({...e,content:dn(e.role,e.content)})}return n}function Ce(t){return ae(t).map((n,e)=>({index:e,id:n.call_id??n.id??`call_${e}`,type:"function",function:{name:n.name??"",arguments:n.arguments??"{}"}}))}function pt(t,n){let e=n?.output_text;return typeof e=="string"?e:t.filter(o=>o.type==="response.output_text.delta"&&typeof o.delta=="string").map(o=>o.delta).join("")}async function fn(t,n,e,o,r){let i=t.stream===!0,s;try{s=e.thread(t.previous_response_id,t.input)}catch(l){q(o,400,String(l instanceof Error?l.message:l));return}t.previous_response_id!=null&&(r.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(t.input)));let a=`resp_${Math.random().toString(36).slice(2,14)}`,u=t.store!==!1,c=Me(t);r.model(c);let p=Array.isArray(t.tools)&&t.tools.length>0,f;try{f=await n.createResponse({model:t.model,input:s,stream:i,tools:t.tools,tool_choice:t.tool_choice,temperature:t.temperature,top_p:t.top_p,stop:t.stop,max_output_tokens:t.max_output_tokens,...t.reasoning_effort!==void 0?{reasoning_effort:t.reasoning_effort}:{},...t.chat_template_kwargs!==void 0?{chat_template_kwargs:t.chat_template_kwargs}:{}})}catch(l){if(l instanceof U){Le(o,"openai",l);return}throw l}let m=[];if(i){$e(o);let l=g=>{o.write(`event: ${String(g.type??"message")}
|
|
2
|
-
data: ${JSON.stringify(g)}
|
|
1
|
+
"use strict";var Us=Object.create;var ht=Object.defineProperty;var Ms=Object.getOwnPropertyDescriptor;var Ds=Object.getOwnPropertyNames;var Bs=Object.getPrototypeOf,Fs=Object.prototype.hasOwnProperty;var js=(t,e)=>{for(var n in e)ht(t,n,{get:e[n],enumerable:!0})},yr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ds(e))!Fs.call(t,o)&&o!==n&&ht(t,o,{get:()=>e[o],enumerable:!(r=Ms(e,o))||r.enumerable});return t};var yt=(t,e,n)=>(n=t!=null?Us(Bs(t)):{},yr(e||!t||!t.__esModule?ht(n,"default",{value:t,enumerable:!0}):n,t)),qs=t=>yr(ht({},"__esModule",{value:!0}),t);var Eu={};js(Eu,{ANONYMOUS_KEY_ID:()=>zt,BIND_HOST:()=>As,BUCKET_DOMAIN:()=>Vn,BoundedLabel:()=>De,ControlPlaneUnavailableError:()=>ge,ConversationBackhauls:()=>He,ConversationCapacityError:()=>qe,DEFAULT_PORT:()=>or,EDGE_IDENTITY_PORT:()=>ys,EDGE_KEY_FINGERPRINT_HEADER:()=>Gn,EDGE_KEY_ID_HEADER:()=>Hn,InferenceMetrics:()=>Be,LEDGER_FUNCTION_PATH:()=>lr,LEDGER_WRITE_TIMEOUT_MS:()=>cr,LedgerClient:()=>We,LedgerDuplicateError:()=>Ve,LedgerSurfaceError:()=>q,MAX_CACHED_KEYS:()=>Xn,MAX_CONVERSATIONS:()=>tn,MAX_CONVERSATION_HANDLES:()=>ir,MAX_MODEL_LABELS:()=>Dn,MAX_ORG_LABELS:()=>Bn,MAX_TENANTS:()=>sr,METRICS_PATH:()=>Jt,METRICS_PORT:()=>gs,NO_MODEL_LABEL:()=>Mn,ORG_BINDING_TTL_MS:()=>Yn,OTHER_LABEL:()=>Me,OrgResolver:()=>Fe,ProxyAuthError:()=>z,READINESS_TIMEOUT_MS:()=>gr,READINESS_TTL_MS:()=>mr,SERVE_FUNCTION:()=>gt,TIER_DOMAIN:()=>Wn,TenantRegistry:()=>je,bearerFrom:()=>Se,bearerTokenOf:()=>zn,createEdgeIdentityServer:()=>Yt,createHostedProxy:()=>Ns,createMetricsServer:()=>Kt,edgeBucketId:()=>Jn,edgeTierFingerprint:()=>Kn,laneOf:()=>Fn,parseLedgerRecorded:()=>pr,resolveHostedConfig:()=>Is,statusClassOf:()=>jn,tenantSubject:()=>Ge});module.exports=qs(Eu);var Ls=require("http");var vr="audio",on=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e){if(!this.source)throw new Error("startOutbound() not called");let n=Buffer.from(e,"base64"),r=Math.floor(n.byteLength/2),o=new Int16Array(r);for(let s=0;s<r;s++)o[s]=n.readInt16LE(s*2);this.source.onData(o)}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let o of this.outHandlers)o(r)}}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function br(t,e,n=1e4){let r=new on(e,{sampleRate:24e3}),o=await r.startOutbound();await t.stream(vr).attach(o);let s=await Hs(t,n);return await r.startInbound(s),r}function Hs(t,e){let n=t.stream(vr);return n.track!=null?Promise.resolve(n.track):new Promise((r,o)=>{let s,i=setTimeout(()=>{s?.(),o(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),a=u=>{u!=null&&(clearTimeout(i),s?.(),r(u))};s=n.on?.("track",a),n.track!=null&&a(n.track)})}var _r="rt-video-in",wr=256e3;function kr(t){let e=t.stream(_r),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${_r}') 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>wr)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${wr}-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 Gs=24e3,Ke=480,Vs=111;async function Ws(){let t=await import("opusscript"),e=t.default??t;return new e(Gs,1,2048)}async function xr(){let t=await import("werift"),e=await Ws();return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,o=Math.random()*65535&65535,s=Math.random()*4294967295>>>0,i=new Int16Array(0);return{track:n,onData:a=>{let u=new Int16Array(i.length+a.length);u.set(i,0),u.set(a,i.length);let d=0;for(;u.length-d>=Ke;){let l=u.subarray(d,d+Ke);d+=Ke;let c=Buffer.from(l.buffer,l.byteOffset,l.byteLength),m=e.encode(c,Ke);o=o+1&65535,s=s+Ke>>>0;let p=new t.RtpHeader({version:2,payloadType:Vs,sequenceNumber:o,timestamp:s,ssrc:r,marker:!1}),v=new t.RtpPacket(p,m);n.writeRtp(v)}i=u.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(s=>{let i;try{i=e.decode(s.payload)}catch{return}let a=new Int16Array(i.length/2);for(let u=0;u<a.length;u++)a[u]=i.readInt16LE(u*2);r.onframe?.({samples:a})}),r}}}var _t=require("@urun-sh/core"),sn="rt-video-out";var Js="h264";function Ks(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function zs(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(i){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(i)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let o=r;Ks(o,"decodeVideoOutRecord");let s=t.subarray(2+e);if(s.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:o,au:s.slice()}}var Rr="urun.videoOut.v2-ws";function Sr(t){let e=t.stream(sn);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${sn}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,o=new Set,s=u=>{for(let d of r)d(u)},i=!1,a=async()=>{for await(let u of e.messages()){if(!(u instanceof Uint8Array)){s(new Error(`openSessionVideoOutLane: "${sn}" delivered a non-BINARY \xA75 payload (${typeof u}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=zs(u)}catch(l){s(l instanceof Error?l:new Error(String(l)));continue}for(let l of n)l(d)}for(let u of o)u()};return{codec:Js,onOutputFrame:u=>(n.add(u),i||(i=!0,a().catch(d=>s(d instanceof Error?d:new Error(String(d))))),()=>n.delete(u)),onLaneError:u=>(r.add(u),()=>r.delete(u)),onEnd:u=>(o.add(u),()=>o.delete(u))}}var bt="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Xs=1007,Ar=1008,oe=1011,kt=1008,y=class extends Error{constructor(n,r=Xs){super(n);this.closeCode=r}closeCode},M=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null,wt=["setup","clientContent","realtimeInput","toolResponse"];function Ir(t){let e;try{e=JSON.parse(t)}catch{throw new y("client message is not valid JSON")}let n=M(e);if(!n)throw new y("client message must be a JSON object");let r=wt.filter(a=>n[a]!==void 0),o=Object.keys(n).filter(a=>!wt.includes(a));if(o.length>0)throw new y(`unknown client message field(s) ${JSON.stringify(o)} \u2014 expected exactly one of ${wt.join(", ")}`);if(r.length!==1)throw new y(`client message must contain exactly one of ${wt.join(", ")} (got ${r.length})`);let s=r[0],i=M(n[s]);if(!i)throw new y(`"${s}" must be a JSON object`);return{kind:s,[s]:i}}function Or(t,e){if(typeof t=="string")return t;let n=M(t),r=n?n.parts:void 0;if(!Array.isArray(r))throw new y(`${e}: expected a Content with a parts array`);let o=[];for(let s of r){let i=M(s);if(i&&typeof i.text=="string"){o.push(i.text);continue}throw i&&(i.inlineData!==void 0||i.fileData!==void 0)?new y(`${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 y(`${e}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new y(`${e}: unsupported part ${JSON.stringify(s)}`)}return o.join(`
|
|
2
|
+
`)}var Qs={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},_e="urun.videoOut";function Tr(t){return{framing:Rr,codec:t}}function Cr(t){let{seq:e,ptsUs:n,codec:r,key:o}=t.header;return{[_e]:{v:1,seq:e,ptsUs:n,codec:r,key:o,data:Buffer.from(t.au).toString("base64")}}}var Zs={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},ei=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",_e],Er=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function ti(t){let e=M(t);if(!e)throw new y("setup.realtimeInputConfig must be an object");for(let o of Object.keys(e))if(!(o==="automaticActivityDetection"||o==="activityHandling"))throw new y(o==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${o}"`);let n=M(e.automaticActivityDetection);if(e.automaticActivityDetection!==void 0&&!n)throw new y("realtimeInputConfig.automaticActivityDetection must be an object");for(let o of Object.keys(n??{}))if(o!=="disabled")throw new y(`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 y("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(!Er.includes(e.activityHandling))throw new y(`unsupported activityHandling ${JSON.stringify(e.activityHandling)} \u2014 expected one of ${Er.join(", ")}`);r=e.activityHandling}return{manualActivity:!0,activityHandling:r}}var ni=["temperature","maxOutputTokens","responseModalities"];function Pr(t){for(let[c,m]of Object.entries(Zs))if(t[c]!==void 0)throw new y(m);for(let c of Object.keys(t))if(!ei.includes(c))throw new y(`unsupported setup field "${c}"`);if(typeof t.model!="string"||t.model.length===0)throw new y('setup.model is required (format "models/{model}")');let e=t.model.replace(/^models\//,""),n,r,o=!1,s=M(t.generationConfig);if(t.generationConfig!==void 0&&!s)throw new y("setup.generationConfig must be an object");if(s){for(let c of Object.keys(s))if(!ni.includes(c))throw new y(`unsupported generationConfig field "${c}"`);if(s.temperature!==void 0){if(typeof s.temperature!="number")throw new y("generationConfig.temperature must be a number");n=s.temperature}if(s.maxOutputTokens!==void 0){if(typeof s.maxOutputTokens!="number")throw new y("generationConfig.maxOutputTokens must be a number");r=s.maxOutputTokens}if(s.responseModalities!==void 0){let c=Array.isArray(s.responseModalities)?s.responseModalities:[s.responseModalities];for(let m of c){let p=String(m).toUpperCase();if(p==="AUDIO"){o=!0;continue}if(p!=="TEXT")throw new y(`responseModalities ${JSON.stringify(m)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let i=[];t.systemInstruction!==void 0&&i.push({role:"system",content:Or(t.systemInstruction,"setup.systemInstruction")});let a;if(t.tools!==void 0){if(!Array.isArray(t.tools))throw new y("setup.tools must be an array");a=[];for(let c of t.tools){let m=M(c);if(!m)throw new y("setup.tools entries must be objects");for(let p of Object.keys(m))if(p!=="functionDeclarations")throw new y(`unsupported tool "${p}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(m.functionDeclarations))throw new y("tool.functionDeclarations must be an array");for(let p of m.functionDeclarations){let v=M(p);if(!v||typeof v.name!="string")throw new y("functionDeclarations entries require a string name");a.push({type:"function",name:v.name,description:v.description,parameters:v.parameters})}}a.length===0&&(a=void 0)}let u={enabled:!1,handle:null};if(t.sessionResumption!==void 0){let c=M(t.sessionResumption);if(!c)throw new y("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let m of Object.keys(c))if(m!=="handle")throw new y(`unsupported sessionResumption field "${m}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(c.handle!==void 0&&(typeof c.handle!="string"||c.handle.length===0))throw new y("sessionResumption.handle must be a non-empty string when present");u={enabled:!0,handle:typeof c.handle=="string"?c.handle:null}}let d=t.realtimeInputConfig===void 0?Qs:ti(t.realtimeInputConfig),l=!1;if(t[_e]!==void 0){if(!M(t[_e]))throw new y(`setup["${_e}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:e,systemItems:i,tools:a,temperature:n,maxOutputTokens:r,audioModality:o,activity:d,sessionResumption:u,videoOut:l}}function $r(t){return{sessionResumptionUpdate:{newHandle:t,resumable:!0}}}function Lr(t){let e=Math.max(0,t??0)/1e3;return{goAway:{timeLeft:`${Math.round(e*1e3)/1e3}s`}}}function Nr(t){for(let r of Object.keys(t))if(r!=="turns"&&r!=="turnComplete")throw new y(`unsupported clientContent field "${r}"`);let e=t.turns===void 0?[]:t.turns;if(!Array.isArray(e))throw new y("clientContent.turns must be an array");let n=[];for(let r of e){let o=M(r);if(!o)throw new y("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 y(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(o.role)})`);n.push({role:s==="model"?"assistant":"user",content:Or(o,"clientContent.turns")})}return{items:n,turnComplete:t.turnComplete===!0}}var vt=16e3,Ur=24e3,ri=`audio/pcm;rate=${Ur}`,Mr=Buffer.alloc(960).toString("base64");function oi(t,e,n){if(e===n)return t;let r=Math.floor(t.length*n/e),o=new Int16Array(r),s=e/n,i=t.length-1;for(let a=0;a<r;a++){let u=a*s,d=Math.floor(u);if(d>=i){o[a]=t[i];continue}let l=u-d;o[a]=Math.round(t[d]+(t[d+1]-t[d])*l)}return o}function si(t){let e=M(t);if(!e)throw new y("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(e.mimeType))throw new y(`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 y("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 y("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(n)}function ii(t){let e=M(t);if(!e)throw new y("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof e.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(e.mimeType))throw new y(`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])!==vt)throw new y(`realtimeInput.audio.mimeType declares rate=${n[1]} \u2014 the Live spec input format is ${vt} Hz (audio/pcm;rate=${vt})`);if(typeof e.data!="string"||e.data.length===0)throw new y("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 y(`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=oi(o,vt,Ur);return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}function Dr(t){if(t.mediaChunks!==void 0)throw new y('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 y("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let o=t.activityStart!==void 0?"activityStart":"activityEnd",s=M(t[o]);if(!s||Object.keys(s).length!==0)throw new y(`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 y(`unsupported realtimeInput field "${r}"`);let n=e.filter(r=>t[r]!==void 0);if(n.length!==1)throw new y(`realtimeInput must carry exactly one of ${e.join(", ")} (got ${n.length})`);if(t.audio!==void 0)return{kind:"audio",base64Pcm24k:ii(t.audio)};if(t.video!==void 0)return{kind:"video",jpegFrame:si(t.video)};if(t.audioStreamEnd!==void 0){if(t.audioStreamEnd!==!0)throw new y("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof t.text!="string"||t.text.length===0)throw new y("realtimeInput.text must be a non-empty string");return{kind:"text",text:t.text}}function Br(t){for(let e of Object.keys(t))if(e!=="functionResponses")throw new y(`unsupported toolResponse field "${e}"`);if(!Array.isArray(t.functionResponses)||t.functionResponses.length===0)throw new y("toolResponse.functionResponses must be a non-empty array");return t.functionResponses.map(e=>{let n=M(e);if(!n||typeof n.id!="string"||n.id.length===0)throw new y("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 Fr(t){return t.type!=="response.output_text.delta"||typeof t.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:t.delta}]}}}}function jr(t){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:ri,data:t}}]}}}}function qr(t){let e=M(t)??{},n=Array.isArray(e.output)?e.output:[],r=[],o=[],s=typeof e.output_text=="string"?e.output_text:"";if(!s)for(let d of n){let l=M(d);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let c of l.content){let m=M(c);m?.type==="output_text"&&typeof m.text=="string"&&(s+=m.text)}}s&&o.push({role:"assistant",content:s});for(let d of n){let l=M(d);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new y(`upstream function_call item is missing call_id/name: ${JSON.stringify(d)}`,oe);let c=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",m;try{m=JSON.parse(c)}catch{throw new y(`upstream function_call arguments are not valid JSON: ${c}`,oe)}r.push({id:l.call_id,name:l.name,args:m}),o.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:c})}let i=[];r.length>0&&i.push({toolCall:{functionCalls:r}}),i.push({serverContent:{generationComplete:!0}});let a=M(e.usage),u={serverContent:{turnComplete:!0}};if(a){let d={};typeof a.input_tokens=="number"&&(d.promptTokenCount=a.input_tokens),typeof a.output_tokens=="number"&&(d.responseTokenCount=a.output_tokens),typeof a.total_tokens=="number"&&(d.totalTokenCount=a.total_tokens),Object.keys(d).length>0&&(u.usageMetadata=d)}return i.push(u),{messages:i,assistantItems:o}}var lo=require("crypto"),co=require("ws");var W=class extends Error{};function ai(t){if(t===null||typeof t!="object")return null;let e=t.shared;if(e==null)return null;if(typeof e!="object")throw new W(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:n,endpoints:r}=e;if(typeof n!="string"||n==="")throw new W(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(r))throw new W(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let o=r.map((s,i)=>{if(s===null||typeof s!="object")throw new W(`catalog shared endpoints[${i}] is not an object: ${JSON.stringify(s)}`);let a=s;for(let u of["model_id","variant","app_slug","function"])if(typeof a[u]!="string"||a[u].length===0)throw new W(`catalog shared endpoints[${i}] (${JSON.stringify(a)}) has no valid "${u}"`);return a});return o.length===0?null:{shared_org_id:n,endpoints:o}}function xt(t){return[...t.endpoints].sort((e,n)=>e.model_id.localeCompare(n.model_id)||e.variant.localeCompare(n.variant))}function Hr(t,e,n){let r=(e??"").trim();if(r==="")return null;let o=r,s=n,i=r.lastIndexOf(":");i>0&&(o=r.slice(0,i),s=r.slice(i+1));let a=t.endpoints.filter(d=>d.model_id===o);if(a.length===0)return null;if(s!==void 0){let d=a.find(l=>l.variant===s);return d?{shared_org_id:t.shared_org_id,endpoint:d}:null}if(a.length===1)return{shared_org_id:t.shared_org_id,endpoint:a[0]};let u=a.filter(d=>d.compat_default===!0);if(u.length!==1)throw new W(`shared model "${o}" has ${u.length} compat_default rows (exactly one required) among variants ${a.map(d=>d.variant).join(", ")}`);return{shared_org_id:t.shared_org_id,endpoint:u[0]}}async function Gr(t){let e=t.fetchImpl??fetch,n=`${t.apiUrl.replace(/\/+$/,"")}/catalog`,r=await e(n,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!r.ok)throw new W(`catalog read failed: GET ${n} \u2192 ${r.status}`);return ai(await r.json())}function se(t){return t.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}var Z=class extends Error{name="ModelPriceError"},an="per_million_input_tokens",un="per_million_output_tokens",Wr="model_id,variant,unit,price_usd,effective_at,expires_at",Vr={per_request:!0,per_minute:!0,per_output_unit:!0},ui=5e3;function di(t,e){let n=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;if(!Number.isFinite(n)||n<0)throw new Z(`${e}: price_usd is not a non-negative number (${JSON.stringify(t)})`);return n}function Jr(t,e,n){let r=typeof t=="string"?Date.parse(t):NaN;if(!Number.isFinite(r))throw new Z(`${e}: ${n} is not a parseable timestamp (${JSON.stringify(t)})`);return r}function li(t,e,n){return t===null?null:Jr(t,e,n)}function ci(t,e){if(t===an)return"input";if(t===un)return"output";if(typeof t=="string"&&Object.hasOwn(Vr,t))return null;throw new Z(`${e}: unit ${JSON.stringify(t)} is neither a per-token rate (${an} | ${un}) nor a known GPU-time unit (${Object.keys(Vr).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 pi(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 fi(t){if(!Array.isArray(t))throw new Z(`model_prices read is not an array: ${JSON.stringify(t)}`);let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=`model_prices[${n}]`;if(r===null||typeof r!="object"||Array.isArray(r))throw new Z(`${o} is not an object: ${JSON.stringify(r)}`);let s=r;for(let d of Wr.split(","))if(!Object.hasOwn(s,d))throw new Z(`${o} has no "${d}" column: ${JSON.stringify(s)}`);let i=ci(s.unit,o);if(i===null)continue;let a=s.model_id;if(typeof a!="string"||a==="")throw new Z(`${o} has no model_id (${JSON.stringify(s)})`);let u=s.variant;if(!(u===null||typeof u=="string"&&u!==""))throw new Z(`${o} has a non-string variant (${JSON.stringify(u)})`);e.push({model_id:a,variant:u,side:i,usd:di(s.price_usd,o),effective_at:Jr(s.effective_at,o,"effective_at"),expires_at:li(s.expires_at,o,"expires_at")})}return e}function Kr(t,e=Date.now()){let n=new Map,r=new Map;for(let a of t){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let u=n.get(a.model_id);u||(u=new Map,n.set(a.model_id,u),r.set(a.model_id,new Map));let d=a.variant??"",l=u.get(d);l||(l={input:[],output:[]},u.set(d,l),r.get(a.model_id).set(d,a.variant)),l[a.side].push({effective_at:a.effective_at,usd:a.usd})}let o=[],s=[];for(let[a,u]of n){let d=u.get(""),l=(c,m)=>{let p=c&&c.length>0?c:d?.[m];if(!p||p.length===0)return null;let v=pi(p,m);return"reason"in v?v:v.rate.usd===0?{reason:`the ${m} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:v.rate};for(let[c,m]of r.get(a)){let p=u.get(c),v=l(p?.input,"input"),h=l(p?.output,"output");if(v!==null&&"reason"in v){s.push({model_id:a,variant:m,reason:v.reason});continue}if(h!==null&&"reason"in h){s.push({model_id:a,variant:m,reason:h.reason});continue}v===null||h===null||o.push({model_id:a,variant:m,pricing:{input:v.usd,output:h.usd}})}}let i=(a,u)=>a.model_id.localeCompare(u.model_id)||(a.variant===null?1:0)-(u.variant===null?1:0)||(a.variant??"").localeCompare(u.variant??"");return{prices:o.sort(i),refusals:s.sort(i)}}function ze(t,e,n){if(n.refusals.some(s=>s.model_id===t&&s.variant===e))return null;let r=n.prices.find(s=>s.model_id===t&&s.variant===e);if(r)return r.pricing;if(n.refusals.some(s=>s.model_id===t&&s.variant===null))return null;let o=n.prices.find(s=>s.model_id===t&&s.variant===null);return o?o.pricing:null}var Rt={prices:[],refusals:[]};async function zr(t){let e=t.fetchImpl??fetch,n=`${an},${un}`,r=await e(`${t.catalogUrl}/model_prices?select=${Wr}&unit=in.(${n})`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`},signal:AbortSignal.timeout(ui)});if(!r.ok)throw new Error(`model_prices fetch failed: ${r.status}`);return fi(await r.json())}var mi={chat:!0,code:!0,agent:!0,vl:!0},Yr={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function gi(t){let e=t.toLowerCase();return Object.hasOwn(Yr,e)?Yr[e]:null}var hi=["context_length","max_model_len"];function yi(t){let e=hi.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 St(t){let e=t.map(yi),n=e[0];return n==null?null:e.every(r=>r===n)?n:null}function _i(t,e){let n=e.filter(o=>se(`${o.model_id}-${o.variant}`)===t);if(n.length>0)return dn(n);let r=e.filter(o=>se(o.model_id)===t);return r.length>0?dn(r):null}function dn(t){let e=t[0];return t.every(r=>r.model_id===e.model_id&&r.variant===e.variant)?{row:t.length===1?e:wi(t),matches:t}:null}function wi(t){let e=t[0],n=r=>t.every(o=>(o[r]??void 0)===(e[r]??void 0))?e[r]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:n("gpu_spec"),engine:n("engine"),task:n("task"),description:n("description"),size_gb:n("size_gb"),hf_repo:n("hf_repo"),updated_at:n("updated_at")}}function Zr(t){let e=t.updated_at?Date.parse(t.updated_at):NaN;return Number.isFinite(e)?Math.floor(e/1e3):0}function ln(t,e,n){let r=_i(t,e);if(!r)return{id:t,object:"model",created:0,owned_by:"urun"};let{row:o,matches:s}=r,i=St(s),a=ze(o.model_id,o.variant,n);return{id:t,object:"model",created:Zr(o),owned_by:"urun",name:`${o.model_id}:${o.variant}`,...o.description?{description:o.description}:{},...o.task?{task:o.task}:{},...o.engine?{engine:o.engine}:{},...o.gpu_spec?{gpu_spec:o.gpu_spec}:{},...i!==null?{context_length:i}:{},...a!==null?{pricing:a}:{}}}function Xr(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 Qr(t){return{input:[{type:"prompt",unit:"token",cost_usd:Xr(t.input)}],output:[{type:"completion",unit:"token",cost_usd:Xr(t.output)}]}}function vi(t,e){if(t.length===0)return null;let n=dn(t);if(!n)return null;let{row:r,matches:o}=n;if(!r.task||mi[r.task]!==!0)return null;let s=St(o),i=ze(r.model_id,r.variant,e),a={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return s!==null&&(a.max_tokens={type:"integer",min:1,max:s,unit:"token"}),{schema_version:"2.4",id:`${r.model_id}:${r.variant}`,name:`${r.model_id}:${r.variant}`,created:Zr(r),quantization:gi(r.variant),description:r.description??"",hugging_face_id:r.hf_repo?r.hf_repo.split("@")[0]??r.hf_repo:"",input_modalities:[{type:"text",...s!==null?{supported_inputs:{max_context_length:{value:s,unit:"token"}}}:{},...i?{pricing:Qr(i).input}:{}},...r.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:a,...i?{pricing:Qr(i).output}:{}}]}}function eo(t,e,n){let r=[],o=new Set;for(let s of t){let i=`${s.model_id}:${s.variant}`;if(o.has(i))continue;o.add(i);let a=vi(e.filter(u=>u.model_id===s.model_id&&u.variant===s.variant),n);a&&r.push(a)}return{data:r}}var B=class extends Error{},V=class extends Error{},pn="urs1.";function bi(t,e){return pn+Buffer.from(JSON.stringify([t,e]),"utf8").toString("base64url")}function ki(t){if(!t.startsWith(pn))return null;try{let e=JSON.parse(Buffer.from(t.slice(pn.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 ao(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 to(t){if(t.length===0)return[];if(!t.every(n=>(n.task??void 0)==="image"))return[];let e=Ri(t);return e===null?[]:[e]}function no(t,e,n,r,o){if(!o)throw new W(`shared model "${t}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||n===void 0)throw new W(`shared model "${t}" resolved without a catalog id + variant to join on`);let s=r.filter(i=>i.model_id===e&&i.variant===n);if(s.length===0)throw new W(`shared model "${t}" names endpoint ${e}:${n} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return s}function ro(t,e){if(!e.every(o=>(o.task??void 0)==="image"))return[];let n=e.map(o=>o.engine_args?.expects_image),r=n[0];if(typeof r!="boolean"||!n.every(o=>o===r))throw new W(`shared image model "${t}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(n)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[r===!1?"generation":"edit"]}var uo="shared:";function Ye(t){return t.sharedApp?uo+t.appSlug:t.appSlug}function oo(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 cn(t,e){let n=e.filter(s=>se(`${s.model_id}-${s.variant}`)===t);if(n.length>0)return n;let r=e.filter(s=>se(s.model_id)===t);return new Set(r.map(s=>s.variant)).size===1?r:[]}function xi(t){let e=t.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Ri(t){let e=t.map(xi),n=e[0];return n!=null&&e.every(r=>r===n)?n:null}var so={stt:"stt",tts:"tts"};function io(t){if(t.length===0)return null;let e=t[0].task??void 0;return e===void 0||so[e]===void 0?null:t.every(n=>(n.task??void 0)===e)?so[e]:null}var Et=6e4,At=class{constructor(e){this.opts=e}opts;pool=new Map;appsCache=null;rowsCache=null;seed(e,n){this.pool.set(e,Promise.resolve(n))}async deployedApps(){if(!this.opts.listApps)return[];let e=this.opts.appsTtlMs??Et;if(this.appsCache&&Date.now()-this.appsCache.at<e)return this.appsCache.apps;let n=await this.opts.listApps();return this.appsCache={at:Date.now(),apps:n},n}async sharedBlock(){if(!this.opts.shared)return null;let e=this.opts.appsTtlMs??Et;if(this.sharedCache&&Date.now()-this.sharedCache.at<e)return this.sharedCache.block;let n=await this.opts.shared();return this.sharedCache={at:Date.now(),block:n},n}sharedCache=null;async catalogRows(){if(!this.opts.listCatalog)return[];let e=this.opts.appsTtlMs??Et;if(this.rowsCache&&Date.now()-this.rowsCache.at<e)return this.rowsCache.rows;let n=await this.opts.listCatalog();return this.rowsCache={at:Date.now(),rows:n},n}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??Et;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(){let e;try{e=await this.priceRows()}catch(r){if(r instanceof Z)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
3
|
+
`),Rt}let n=Kr(e,Date.now());for(let r of n.refusals)this.warn(`urun /v1/models: refusing to price ${r.model_id}:${r.variant??"*"} \u2014 ${r.reason}
|
|
4
|
+
`);return n}warn(e){(this.opts.warn??(r=>console.warn(r.trimEnd())))(e)}servable(e){return e.filter(n=>n.function_name===this.opts.fnName&&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(uo)||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 B(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed "${this.opts.fnName}" apps; available models: ${r}`:`model "${e}" does not name a deployed "${this.opts.fnName}" app in your org, and this endpoint has no default model to fall back to; available models: ${r}`)}async resolveTarget(e){let n=(e??"").trim(),r=this.opts.defaultApp;if(!n||n==="urun")return r===null?this.noDefaultApp(n):{appSlug:r};let o=se(n);if(o===r)return{appSlug:r};if(this.pool.has(o))return{appSlug:o};if(this.opts.listApps){let s=await this.deployedApps(),i=this.servable(s);if(i.includes(o))return{appSlug:o};let a=i.filter(d=>d.startsWith(`${o}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new B(`model "${n}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let u=s.find(d=>d.app_slug===o||d.app_slug.startsWith(`${o}-`));if(u)throw new B(`model "${n}" maps to app "${u.app_slug}", which is not an active "${this.opts.fnName}" app \u2014 deploy it with \`urun serve ${n}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.shared){let s=await this.sharedBlock();if(s){let i=Hr(s,n);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant}}}if(this.opts.listCatalog){let i=(await this.opts.listCatalog()).find(a=>n===a.model_id||n===`${a.model_id}:${a.variant}`||o===se(a.model_id)||o===se(`${a.model_id}-${a.variant}`));if(i)throw new B(`model "${n}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${i.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return r===null?this.noDefaultApp(n):{appSlug:r}}async catalogIdentityFor(e){let n=oo(await this.resolveTarget(e));return n.kind==="catalog"?{model_id:n.model_id,variant:n.variant}:null}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return Ye(await this.resolveTarget(e))}async sessionFor(e){let n=await this.resolveTarget(e),r=Ye(n),o=this.pool.get(r);return o||(o=Promise.resolve(this.opts.openSession(n)),this.pool.set(r,o),o.catch(()=>this.pool.delete(r))),{app:r,entry:await o,identity:oo(n)}}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:bi(n,this.keyOf(r))}}async sessionForHandle(e){let n=ki(e);if(!n)throw new V(`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 V(`the session behind this handle (app "${r}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(i)!==o)throw new V(`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=await this.availableIds(),[n,r]=await Promise.all([this.catalogRows().then(d=>({ok:!0,rows:d}),()=>({ok:!1,rows:[]})),this.pricesForListing()]),o=n.rows,s=n.ok?r:Rt;n.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
|
|
5
|
+
`);let i=await this.sharedBlock(),u=(i?xt(i):[]).map(d=>{let l={id:`${d.model_id}:${d.variant}`,object:"model",created:0,owned_by:"urun",name:`${d.model_id}:${d.variant}`};d.gpu_spec&&(l.gpu_spec=d.gpu_spec),typeof d.warm=="number"&&(l.warm=d.warm);let c=o.filter(v=>v.model_id===d.model_id&&v.variant===d.variant),m=St(c);m!==null&&(l.context_length=m);let p=ze(d.model_id,d.variant,s);return p!==null&&(l.pricing=p),l});return{object:"list",data:[...e.map(d=>ln(d,o,s)),...u]}}async openRouterModels(){let[e,n]=await Promise.all([this.catalogRows(),this.pricesForListing()]),r=await this.sharedBlock();return eo(r?xt(r):[],e,n)}async supportsImages(e,n){let r=await this.resolveTarget(e),o=await this.catalogRows();if(r.sharedApp){let s=no(String(e),r.modelId,r.variant,o,this.opts.listCatalog!==null);return ro(`${r.modelId}:${r.variant}`,s).includes(n)}return to(cn(r.appSlug,o)).includes(n)}async supportsAudio(e){let n=await this.resolveTarget(e),r=await this.catalogRows();return n.sharedApp?io(r.filter(o=>o.model_id===n.modelId&&o.variant===n.variant))!==null:io(cn(n.appSlug,r))!==null}async imageModelList(){let e=await this.catalogRows(),n=Rt,r=[];for(let s of await this.availableIds()){let i=to(cn(s,e));i.length!==0&&r.push({...ln(s,e,n),image_modes:i})}let o=await this.sharedBlock();if(o)for(let s of xt(o)){let i=no(`${s.model_id}:${s.variant}`,s.model_id,s.variant,e,this.opts.listCatalog!==null),a=ro(`${s.model_id}:${s.variant}`,i);if(a.length===0)continue;let u={id:`${s.model_id}:${s.variant}`,object:"model",created:0,owned_by:"urun",name:`${s.model_id}:${s.variant}`,image_modes:a};s.gpu_spec&&(u.gpu_spec=s.gpu_spec),typeof s.warm=="number"&&(u.warm=s.warm),r.push(u)}return{object:"list",data:r}}async closeAll(){let e=[...this.pool.values()],n=[];if(await Promise.all(e.map(async r=>{try{await this.opts.closeSession(await r)}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} pooled session(s): ${n.join("; ")}`)}};var Si=256,fn=class{snapshots=new Map;store(e,n,r){for(this.snapshots.set(`${e}\0${n}`,r);this.snapshots.size>Si;){let o=this.snapshots.keys().next().value;this.snapshots.delete(o)}}get(e,n){return this.snapshots.get(`${e}\0${n}`)}},Ei="local",Xe=t=>t.slice(0,120),mn=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 B){this.ws.close(Ar,Xe(e.message));return}if(e instanceof V){this.ws.close(kt,Xe(e.message));return}if(e instanceof y){this.ws.close(e.closeCode,Xe(e.message));return}this.ws.close(oe,Xe(String(e instanceof Error?e.message:e)))}onMessage(e){try{let n=Ir(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 y(`"${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}=Nr(n.clientContent);this.transcript.push(...o),s&&this.enqueue(()=>this.runTurn());return}if(n.kind==="realtimeInput"){let o=Dr(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:Mr);return}this.transcript.push(...Br(n.toolResponse)),this.enqueue(()=>this.runTurn())}catch(n){this.fail(n)}}async handleSetup(e){if(this.config)throw new y("setup may only be sent once, as the first client message");let n=Pr(e),r=n.sessionResumption.handle;if(r!==null){let s=this.registry.get(this.scope,r);if(!s)throw new y("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",kt);if(s.model!==n.model)throw new y(`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 y("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 y(`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`,kt);this.unsubscribeEnd=await this.clients.onSessionEnd(s.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...s.transcript]}else this.proxyHandle=await this.clients.sessionHandle(n.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.transcript.push(...n.systemItems);this.config=n;let o={};if(n.videoOut){let s=this.clients.openVideoOut;if(s){let i=await s.call(this.clients,n.model),a=i.onOutputFrame(d=>this.send(Cr(d))),u=i.onLaneError(d=>this.fail(d));this.detachVideoOut=()=>{a(),u()},o[_e]=Tr(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 y("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openAudio;if(!n)throw new y("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",oe);return this.audio=(async()=>{let r=await n.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(o=>this.send(jr(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 y("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let n=this.clients.openVideo;if(!n)throw new y("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",oe);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 y(`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 y("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 y("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(n=>this.fail(n))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let n=await this.clients.sessionHandle(e.model);this.proxyHandle=n;let r=(0,lo.randomUUID)();this.registry.store(this.scope,r,{model:e.model,proxyHandle:n,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send($r(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(Lr(e.timeLeftMs)),this.ws.close(oe,Xe(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let n={interrupted:!1};this.activeTurn=n;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),o,s=!1;for await(let u of r){if(n.interrupted)break;let d=u;if(d.type==="error")throw new y(`upstream error: ${JSON.stringify(d)}`,oe);if(d.type==="response.completed"){o=d.response,s=!0;continue}let l=Fr(d);l&&this.send(l)}if(n.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!s)throw new y("upstream produced no response.completed event",oe);let{messages:i,assistantItems:a}=qr(o);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},we=class extends Error{constructor(n,r){super(r);this.status=n;this.name="UpgradeAuthError"}status};function Ai(t,e,n){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let d of u)d!==""&&r.add(d)})(t.headers["x-goog-api-key"]);let s=t.headers.authorization;typeof s=="string"&&s.startsWith("Bearer ")&&s.length>7&&r.add(s.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new we(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(n&&i!==void 0&&i!=="")throw new we(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&n)throw new we(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function gn(t,e){let n=e.authenticate!==void 0;if(n&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!n&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new co.WebSocketServer({noServer:!0}),o=new fn;t.on("upgrade",(i,a,u)=>{let d=new URL(i.url??"/","http://localhost");d.pathname===bt&&(a.on("error",()=>{}),(async()=>{let l=Ai(i,d,n),c;if(e.authenticate)c=await e.authenticate(l,i);else{if(e.apiKey!==void 0&&l!==e.apiKey)throw new we(401,"invalid local proxy api key");c={clients:e.clients,scope:Ei}}r.handleUpgrade(i,a,u,m=>{new mn(m,c,o)})})().catch(l=>{let c=502;(l instanceof we||typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number")&&(c=l.status);let m=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",p=l instanceof Error?l.message:String(l);a.destroyed||(a.write(`HTTP/1.1 ${c} ${m}\r
|
|
6
|
+
Connection: close\r
|
|
7
|
+
\r
|
|
8
|
+
${p}\r
|
|
9
|
+
`),a.destroy())}))});let s=null;return()=>(s??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),s)}var fe=require("ws");var po=require("crypto"),fo="Inference-Id";function Qe(){return(0,po.randomUUID)()}function hn(t){return t==="/v1"||t.startsWith("/v1/")}function mo(t,e){if(!hn(t)||e===null)throw new Error(`no inference turn for ${t}: an inference lane was reached off the /v1 surface, so its response would carry no Inference-Id and could never be billed`);return e}function Ze(t){return`resp_${t}`}function go(t){return`chatcmpl-${t}`}function ho(t){return`msg_${t}`}function ie(t){return e=>{t.sessionId=e.sessionId,t.catalog=e.identity}}function yo(t){let e=t.now??(()=>performance.now());return{event:"inference_request",ts:new Date().toISOString(),inference_id:t.turn.id,method:t.method,path:t.path,status:t.res.headersSent?t.res.statusCode:null,delivered:t.res.writableFinished,stream_error:t.turn.streamError,model:t.turn.model,stream:t.turn.stream,org:t.turn.org,duration_ms:e()-t.turn.startedAt,ttft_ms:t.turn.stream===!0?t.turn.ttftMs:null,prompt_tokens:t.turn.promptTokens,completion_tokens:t.turn.completionTokens,output_units:t.turn.outputUnits,session_id:t.turn.sessionId,queue_ms:t.turn.timing?.queue_ms??null,prefill_ms:t.turn.timing?.prefill_ms??null,decode_ms:t.turn.timing?.decode_ms??null,total_ms:t.turn.timing?.total_ms??null,catalog:t.turn.catalog}}function _o(t){return`${JSON.stringify(t)}
|
|
10
|
+
`}var Ii=256,Oi=128;function ae(t){return typeof t.model!="string"||!t.model.trim()?"(default)":t.model.trim().slice(0,Oi)}var ve=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>=Ii?"(other)":e;return this.models[r]??={requests:0,tokens_out:0}}model(e){this.modelEntry(e).requests+=1}track(e,n,r){let o=this,s=performance.now(),i=null,a=0;return(async function*(){for await(let d of e)d.type==="response.output_text.delta"&&typeof d.delta=="string"&&(i===null&&(i=performance.now(),o.ttftMs.push(i-s),o.ttftMs.length>512&&o.ttftMs.shift(),r!==void 0&&(r.ttftMs=i-r.startedAt)),a+=1,o.tokensOut+=1,o.charsOut+=d.delta.length,n!==void 0&&(o.modelEntry(n).tokens_out+=1)),yield d;let u=(performance.now()-(i??s))/1e3;a>0&&u>0&&(o.tokRates.push(a/u),o.tokRates.length>512&&o.tokRates.shift())})()}static p50(e){if(!e.length)return null;let n=[...e].sort((r,o)=>r-o);return n[Math.floor(n.length/2)]}snapshot(){let e=Object.values(this.requests).reduce((n,r)=>n+r,0);return{uptime_s:Math.round((Date.now()-this.startedAt)/1e3),requests:this.requests,models:this.models,tokens_out:this.tokensOut,chars_out:this.charsOut,ttft_ms:{p50:t.p50(this.ttftMs),last:this.ttftMs.at(-1)??null},tok_per_s:{p50:t.p50(this.tokRates),last:this.tokRates.at(-1)??null},traffic:{local_request_bytes:this.localInBytes,naive_baseline:{request_bytes:this.naiveInBytes,connections:e},persistent_connections:1,history_bytes_saved:Math.max(0,this.naiveInBytes-this.localInBytes),history_bytes_saved_pct:this.naiveInBytes>0?Math.round((1-this.localInBytes/this.naiveInBytes)*1e3)/10:null}}}},Ti=256;function Ci(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 be=class extends Error{},Ae=class{conversations=new Map;thread(e,n){let r=Ci(n);if(e==null)return r;let o=this.conversations.get(String(e));if(!o)throw new be(`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<=Ti)break;this.conversations.delete(s)}}forget(e){this.conversations.delete(e)}},wo=new WeakMap;function et(t){let e=wo.get(t);return e||(e=new Ae,wo.set(t,e)),e}function Ie(t){let e=t?.output;return Array.isArray(e)?e.filter(n=>n.type==="function_call"):[]}function ue(t){return t.find(e=>e.type==="response.completed")?.response??null}function Oe(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 pe=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}))}},Pi=["<tool_call>","<function="];function $i(t){return Pi.find(e=>t.includes(e))}function ke(t,e){return`serving row emitted a prose tool call (literal ${JSON.stringify(e)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${t}" (see catalog parser_defaults)`}function xe(t,e,n){if(!(!t||e>0))return $i(n)}function yn(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 Li(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 _n(t,e){let n=Li(t);return n.length>0?n:e?[{role:"assistant",content:e}]:[]}var ee=class extends Error{constructor(n,r,o=400,s){super(n);this.code=r;this.status=o;this.param=s}code;status;param};function Te(t,e){try{return t.thread(e.previous_response_id,e.input)}catch(n){throw n instanceof be?new ee(n.message,"previous_response_not_found",400,"previous_response_id"):new ee(String(n instanceof Error?n.message:n),"invalid_input")}}function vo(t){let e=t.text;if(e!==null&&typeof e=="object"){let n=e.format;if(n!==void 0)return n}}async function wn(t,e,n,r,o){if(e.instructions!==void 0&&typeof e.instructions!="string")throw new ee("instructions must be a string","invalid_instructions");let s=typeof e.instructions=="string"?e.instructions:void 0;return t.createResponse({model:e.model,input:n,stream:r,tools:e.tools,tool_choice:e.tool_choice,temperature:e.temperature,top_p:e.top_p,stop:e.stop,...s!==void 0?{instructions:s}:{},max_output_tokens:e.max_output_tokens,...e.reasoning_effort!==void 0?{reasoning_effort:e.reasoning_effort}:{},...e.chat_template_kwargs!==void 0?{chat_template_kwargs:e.chat_template_kwargs}:{},...vo(e)!==void 0?{response_format:vo(e)}:{}},o)}async function tt(t){let{body:e,clients:n,store:r,stats:o}=t,s=Te(r,e);e.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(s))-Buffer.byteLength(JSON.stringify(e.input)));let i=t.responseId,a=t.remember??e.store!==!1,u=e.store!==!1,d=ae(e);o.model(d);let l=Array.isArray(e.tools)&&e.tools.length>0,c=t.turn,m=await wn(n,e,s,!0,c?ie(c):void 0);return{responseId:i,events:Ni({events:m,conversation:s,responseId:i,modelKey:d,requestHadTools:l,remember:a,persist:u,store:r,stats:o,turn:t.turn})}}async function*Ni(t){let{events:e,conversation:n,responseId:r,modelKey:o,requestHadTools:s,remember:i,persist:a,store:u,stats:d}=t,l=[],c=I=>I.response&&typeof I.response=="object"?{...I,response:{...I.response,id:r}}:I,m=`item_${r.slice(5)}`,p=`rs_${r.slice(5)}`,v=!1,h=!1,f=0;function*g(){v||(v=!0,yield{type:"response.created",response:{id:r,object:"response",status:"in_progress"}})}let w=!1,b=0,A="";function*R(){w&&(w=!1,yield{type:"response.reasoning_text.done",item_id:p,output_index:b,content_index:0,text:A},yield{type:"response.output_item.done",output_index:b,item:{id:p,type:"reasoning",summary:[],content:[{type:"reasoning_text",text:A}],status:"completed"}})}let k=!1,_=0,C="";function*P(I){k&&(k=!1,yield{type:"response.output_text.done",item_id:m,output_index:_,content_index:0,text:C},yield{type:"response.content_part.done",item_id:m,output_index:_,content_index:0,part:{type:"output_text",text:C}},yield{type:"response.output_item.done",output_index:_,item:{id:m,type:"message",role:"assistant",status:I,content:[{type:"output_text",text:C}]}})}let N=new pe,O=null,te=-1;function*X(I){if(!O)return;let L=O;O=null,yield{type:"response.function_call_arguments.done",item_id:L.fcId,output_index:L.outputIndex,arguments:L.args},yield{type:"response.output_item.done",output_index:L.outputIndex,item:{id:L.fcId,type:"function_call",call_id:L.callId??L.fcId,name:L.name??"",arguments:L.args,status:I}}}let H=!1;for await(let I of d.track(e,o,t.turn)){l.push(I);let L=String(I.type??"");if(L==="response.created"||L==="response.in_progress"){v=!0,yield c(I);continue}if(L==="response.output_item.added"){h=!0,yield c(I);continue}if(L==="response.reasoning_text.delta"&&!h){yield*g(),w||(w=!0,b=f++,yield{type:"response.output_item.added",output_index:b,item:{id:p,type:"reasoning",summary:[],content:[],status:"in_progress"}}),A+=String(I.delta??""),yield{type:"response.reasoning_text.delta",item_id:p,output_index:b,content_index:0,delta:I.delta};continue}if(L==="response.output_text.delta"&&!h){yield*g(),yield*R(),k||(k=!0,_=f++,yield{type:"response.output_item.added",output_index:_,item:{id:m,type:"message",role:"assistant",status:"in_progress",content:[]}},yield{type:"response.content_part.added",item_id:m,output_index:_,content_index:0,part:{type:"output_text",text:""}}),C+=String(I.delta??""),yield{type:L,item_id:m,output_index:_,content_index:0,delta:I.delta};continue}let j=h?null:Oe(I);if(j){if(yield*g(),yield*R(),yield*P("completed"),N.add(j),j.tool_index!==te){yield*X("completed"),te=j.tool_index;let Q=f++;O={fcId:`fc_${r.slice(5)}_${j.tool_index}`,outputIndex:Q,callId:j.call_id,name:j.name,args:""},yield{type:"response.output_item.added",output_index:Q,item:{id:O.fcId,type:"function_call",call_id:O.callId??O.fcId,name:O.name??"",arguments:"",status:"in_progress"}}}O&&(j.call_id&&(O.callId=j.call_id),j.name&&(O.name=j.name),O.args+=j.delta,yield{type:"response.function_call_arguments.delta",item_id:O.fcId,output_index:O.outputIndex,delta:j.delta});continue}if(L==="response.completed"&&!h){let Q=Ie(I.response),he=xe(s,N.size+Q.length,C);if(he){H=!0,yield{type:"error",error:{type:"urun_error",code:"tool_call_parser_missing",message:ke(o,he)}};break}if(yield*R(),yield*P("completed"),yield*X("completed"),N.size===0)for(let ye of Q){let ce=f++,re=ye.id??ye.call_id??`fc_${ce}`,Je=ye.arguments??"",Ee={id:re,type:"function_call",call_id:ye.call_id??re,name:ye.name??""};yield{type:"response.output_item.added",output_index:ce,item:{...Ee,arguments:"",status:"in_progress"}},yield{type:"response.function_call_arguments.delta",item_id:re,output_index:ce,delta:Je},yield{type:"response.function_call_arguments.done",item_id:re,output_index:ce,arguments:Je},yield{type:"response.output_item.done",output_index:ce,item:{...Ee,arguments:Je,status:"completed"}}}yield c(I);continue}yield c(I)}if(yield*R(),yield*P("incomplete"),yield*X("incomplete"),i&&!H){let I=ue(l);u.remember(r,n,_n(I,yn(l,I)),a)}}var kn="/v1/responses",Ui=64*1024*1024,Mi=8*1024*1024,Di=16,bo=32,ko=3600*1e3,Bi=/^[A-Za-z0-9._-]{1,256}$/;function J(t,e,n){return{type:"error",status:t,...n!==void 0?{stream_id:n}:{},error:{...e,...e.code!==void 0?{code:e.code}:{}}}}var Fi=J(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 xn(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function ji(t){for(;t.bufferedAmount>Mi&&t.readyState===fe.WebSocket.OPEN;){let{promise:e,resolve:n}=xn();setTimeout(n,5),await e}}var vn=class extends Ae{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 be))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)}},bn=class{constructor(e,n,r,o){this.ws=e;this.clients=n;this.stats=r;this.statusOf=o;this.store=new vn(et(n)),e.on("message",(i,a)=>this.onMessage(i,a)),e.on("close",()=>this.dispose()),e.on("error",()=>this.dispose()),setTimeout(()=>{this.closed||(this.sendFrame(J(400,{type:"invalid_request_error",code:"websocket_connection_limit_reached",message:`Responses websocket connection limit reached (${ko/6e4} minutes). Create a new websocket connection to continue.`})),this.ws.close(1001,"connection time limit reached"))},ko).unref?.()}ws;clients;stats;statusOf;store;lanes=new Map;laneOfResponse=new Map;activeTurns=new Set;active=0;waiters=[];closed=!1;onMessage(e,n){if(this.closed)return;if(n){this.sendFrame(J(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(J(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(J(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(J(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(J(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(J(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"||!Bi.test(o.stream_id)){this.sendFrame(Fi);return}if(s=o.stream_id,!this.lanes.has(s)&&this.namedLaneCount()>=bo){this.sendFrame(J(400,{type:"invalid_request_error",code:"websocket_stream_limit_reached",message:`This WebSocket connection has reached its maximum number of distinct stream IDs (${bo}). Reuse an existing stream_id or open a new WebSocket connection.`,param:"stream_id"},s));return}}let i=o.generate===!1?()=>this.runWarmup(o,s):()=>this.runTurn(o,s),a=s??"",u=this.lanes.get(a)??Promise.resolve();this.lanes.set(a,u.then(i).catch(()=>{}))}namedLaneCount(){return this.lanes.has("")?this.lanes.size-1:this.lanes.size}async runTurn(e,n){if(!this.closed){await this.acquire();try{let r=Buffer.byteLength(JSON.stringify(e));this.stats.request("responses_ws",r,r);let o;try{o=await tt({body:e,clients:this.clients,store:this.store,stats:this.stats,remember:!0,responseId:Ze(Qe())})}catch(i){this.failTurn(i,n,e);return}this.laneOfResponse.set(o.responseId,n??null);let s=o.events;this.activeTurns.add(s);try{for await(let i of s){if(this.closed||this.ws.readyState!==fe.WebSocket.OPEN)break;this.send(i,n),await ji(this.ws)}}finally{this.activeTurns.delete(s)}}catch(r){this.failTurn(r,n,e)}finally{this.release()}}}runWarmup(e,n){if(this.closed)return;let r=Ze(Qe());try{let o=Te(this.store,{...e,input:e.input??(e.previous_response_id!=null?[]:void 0)});this.store.remember(r,o,[],e.store!==!1),this.laneOfResponse.set(r,n??null),this.send({type:"response.created",response:{id:r,object:"response",status:"in_progress"}},n)}catch(o){this.failTurn(o,n,e)}}failTurn(e,n,r){this.sendFrame(this.errorFrameOf(e,n));let o=r.previous_response_id;typeof o=="string"&&this.laneOfResponse.get(o)===(n??null)&&(this.store.forget(o),this.laneOfResponse.delete(o))}errorFrameOf(e,n){let r=String(e instanceof Error?e.message:e);if(e instanceof ee)return J(e.status,{type:"invalid_request_error",code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{}},n);if(e instanceof B)return J(404,{type:"invalid_request_error",code:"model_not_found",message:r},n);if(e instanceof V)return J(503,{type:"upstream_error",code:"session_gone",message:r},n);let o=this.statusOf?.(e)??null;return o?J(o.status,{type:o.openaiType,message:r},n):J(500,{type:"upstream_error",message:r},n)}async acquire(){for(;this.active>=Di;){let{promise:e,resolve:n}=xn();this.waiters.push(n),await e}this.active++}release(){this.active--,this.waiters.shift()?.()}dispose(){if(!this.closed){this.closed=!0;for(let e of[...this.activeTurns])e.return(void 0);this.activeTurns.clear(),this.lanes.clear(),this.laneOfResponse.clear();for(let e of this.waiters.splice(0))e()}}send(e,n){if(this.closed||this.ws.readyState!==fe.WebSocket.OPEN)return;let r=n===void 0?e:{...e,stream_id:n};this.ws.send(JSON.stringify(r))}sendFrame(e){this.closed||this.ws.readyState!==fe.WebSocket.OPEN||this.ws.send(JSON.stringify(e))}};function It(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
11
|
+
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
12
|
+
Connection: close\r
|
|
13
|
+
Content-Type: text/plain; charset=utf-8\r
|
|
14
|
+
Content-Length: ${Buffer.byteLength(o)}\r
|
|
15
|
+
\r
|
|
16
|
+
${o}`)}function Rn(t,e){let n=new fe.WebSocketServer({noServer:!0,maxPayload:Ui}),r=new ve,o=new Set,s=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,c,m)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{It(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),p.pathname!==kn){i.add(c);return}s.add(c);let v=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){It(c,401,"invalid local proxy api key");return}let h;try{h=await a(l)}catch(f){let g=e.statusOf?.(f)??null;It(c,g?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(v=!0,n.handleUpgrade(l,c,m,f=>{s.delete(c),o.add(f),f.on("close",()=>o.delete(f));try{new bn(f,h,r,e.statusOf)}catch{o.delete(f),f.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!v&&!c.destroyed&&It(c,500,"responses websocket upgrade failed")}).finally(()=>s.delete(c))};return t.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=xn();if(u)return c(),l;u=!0,t.off("upgrade",d);for(let p of s)p.destroy();s.clear();for(let p of i)p.destroy();i.clear();for(let p of o)p.close(1001,"server shutting down");let m=setTimeout(()=>{for(let p of o)p.readyState!==fe.WebSocket.CLOSED&&p.terminate()},2e3);return m.unref?.(),n.close(()=>{clearTimeout(m),c()}),l}}}var Io=require("@urun-sh/core");var xo=require("@urun-sh/core"),qi={no_capacity:429,queue_timeout:429,cold_start_exceeded:429,queue_full:429,admission_busy:503,admission_unavailable:503,backend_error:502};function Ot(t){if(t==null)return null;let e=qi[t];return e===void 0?null:{status:e,code:t,retryable:e!==502,openaiType:e===429?"capacity_error":"upstream_error",anthropicType:e===429?"rate_limit_error":e===503?"overloaded_error":"api_error"}}function Tt(t){if(t.kind==="create-failed")return Ot(t.status.error?.code??null);if(t.kind!=="never-live")return null;let e=(t.status.elapsedMs??0)>=xo.COLD_BOOT_WHEN_LIVE_TIMEOUT_MS;return Ot(e?"cold_start_exceeded":"queue_timeout")}var Oo=require("ws");var So=require("crypto");function x(t){return`${t}_${(0,So.randomUUID)().replace(/-/g,"").slice(0,24)}`}var Ct=4*1024*1024,Sn=8*1024*1024,Pt=512,$t=20*1024*1024;function F(t,e,n){return{type:"invalid_request_error",code:t,message:e,param:n??null}}function rt(t,e){return{type:"server_error",code:t,message:e}}function $(t){return{type:"error",event_id:x("event"),error:t}}function En(){return{outputModalities:["text"],turnDetection:null,inputAudioTranscription:!1}}var S=class extends Error{constructor(n,r,o="invalid_value"){super(n);this.param=r;this.code=o;this.name="SessionUpdateError"}param;code},Hi={model:!0,instructions:!0,modalities:!0,voice:!0,input_audio_format:!0,output_audio_format:!0,temperature:!0,max_output_tokens:!0,max_response_output_tokens:!0,tool_choice:!0,tools:!0,metadata:!0,turn_detection:!0,input_audio_transcription:!0,input_audio_noise_reduction:!0,audio:!0},Gi={format:!0,transcription:!0,turn_detection:!0,noise_reduction:!0},Vi={format:!0,voice:!0,speed:!0};function Ro(t,e){let n=t;if(!n||typeof n!="object"||n.type!=="audio/pcm"||n.rate!==void 0&&n.rate!==24e3)throw new S(`${e} must be {"type":"audio/pcm","rate":24000} \u2014 the session audio lane is 24 kHz mono PCM16 only`,e)}function nt(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new S("session must be an object","session","invalid_request");let r=t,o=Object.keys(r).filter(i=>!(i in Hi));if(o.length>0)throw new S(`session field(s) not supported by this backend: ${o.join(", ")}`,o[0],"unsupported_field");let s={...e,outputModalities:[...e.outputModalities]};for(let[i,a]of Object.entries(r))switch(i){case"model":if(a!==null&&typeof a!="string")throw new S("model must be a string or null","model");s.model=a??void 0;break;case"instructions":if(a!==null&&typeof a!="string")throw new S("instructions must be a string or null","instructions");s.instructions=a??void 0;break;case"modalities":{if(!Array.isArray(a)||a.length===0)throw new S("modalities must be a non-empty array","modalities");let u=[];for(let d of a){if(d!=="text"&&d!=="audio")throw new S(`modality ${JSON.stringify(d)} is not "text" or "audio"`,"modalities");if(d==="audio"&&!n.voice)throw new S('modality "audio" refused: the resolver did not provide an authoritative voice binding for the resolved backend \u2014 this model cannot speak on this session',"modalities","audio_not_supported");u.includes(d)||u.push(d)}s.outputModalities=u;break}case"voice":if(a===null){delete s.voice;break}if(typeof a!="string")throw new S("voice must be a string or null","voice");if(!n.voice)throw new S("voice refused: no authoritative voice binding for the resolved backend","voice","audio_not_supported");s.voice=a;break;case"input_audio_format":case"output_audio_format":if(a!=="pcm16")throw new S(`${i} must be "pcm16" \u2014 the session audio lane is 24 kHz mono PCM16 only`,i);break;case"temperature":if(a!==null&&(typeof a!="number"||!Number.isFinite(a)))throw new S("temperature must be a finite number or null","temperature");s.temperature=a??void 0;break;case"max_output_tokens":case"max_response_output_tokens":if(a!==null&&a!=="inf"&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw new S(`${i} must be a positive integer, "inf" or null`,i);s.maxOutputTokens=a===null?void 0:a;break;case"tools":if(!Array.isArray(a))throw new S("tools must be an array","tools");s.tools=a;break;case"tool_choice":s.toolChoice=a;break;case"metadata":if(a!==null&&(!a||typeof a!="object"||Array.isArray(a)))throw new S("metadata must be an object or null","metadata");s.metadata=a??null;break;case"turn_detection":{if(a===null){s.turnDetection=null;break}if(!n.turns)throw new S("turn_detection is refused: the resolved backend does not wire its own turn boundary lane (stt stream with turn_start/turn_end) \u2014 there is no native VAD source to drive responses from. Drive turns manually: input_audio_buffer.commit + response.create.","turn_detection","unsupported_field");let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new S("turn_detection must be an object or null","turn_detection");let d=String(u.type??"");if(d!=="server_vad"&&d!=="semantic_vad")throw new S(`turn_detection.type ${JSON.stringify(u.type)} is not "server_vad"/"semantic_vad"`,"turn_detection.type");s.turnDetection={createResponse:u.create_response!==!1,interruptResponse:u.interrupt_response!==!1};break}case"input_audio_transcription":{if(a===null){s.inputAudioTranscription=!1;break}if(!n.turns)throw new S("input_audio_transcription is refused: the resolved backend does not wire a transcript lane \u2014 no native transcription source exists behind this session","input_audio_transcription","unsupported_field");if(!a||typeof a!="object"||Array.isArray(a))throw new S("input_audio_transcription must be an object or null","input_audio_transcription");for(let u of Object.keys(a))if(!["model","language","languages","prompt"].includes(u))throw new S(`input_audio_transcription field not honored by this backend: ${u} (transcription comes from the voice engine itself)`,`input_audio_transcription.${u}`,"unsupported_field");s.inputAudioTranscription=!0;break}case"input_audio_noise_reduction":if(a!==null)throw new S("input_audio_noise_reduction must be null on this backend: no noise-reduction primitive exists behind the session audio bridge","input_audio_noise_reduction","unsupported_field");break;case"audio":{if(a===null)break;let u=a;if(!u||typeof u!="object"||Array.isArray(u))throw new S("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 S("audio.input must be an object","audio.input");for(let l of Object.keys(d))if(!(l in Gi))throw new S(`audio.input field not supported by this backend: ${l}`,`audio.input.${l}`,"unsupported_field");if(d.format!==void 0&&Ro(d.format,"audio.input.format"),d.transcription!==null&&d.transcription!==void 0){let l=nt({input_audio_transcription:d.transcription},s,n);s.inputAudioTranscription=l.inputAudioTranscription}if(d.turn_detection!==null&&d.turn_detection!==void 0){let l=nt({turn_detection:d.turn_detection},s,n);s.turnDetection=l.turnDetection}if(d.noise_reduction!==null&&d.noise_reduction!==void 0)throw new S("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 S("audio.output must be an object","audio.output");for(let l of Object.keys(d))if(!(l in Vi))throw new S(`audio.output field not supported by this backend: ${l}`,`audio.output.${l}`,"unsupported_field");if(d.format!==void 0&&Ro(d.format,"audio.output.format"),d.speed!==void 0)throw new S("audio.output.speed is not supported on this backend: playback rate is fixed","audio.output.speed","unsupported_field");if(d.voice!==void 0)if(d.voice===null)delete s.voice;else{if(typeof d.voice!="string")throw new S("audio.output.voice must be a string or null","audio.output.voice");if(!n.voice)throw new S("audio.output.voice refused: no authoritative voice binding for the resolved backend","audio.output.voice","audio_not_supported");s.voice=d.voice}d.format!==void 0&&!s.outputModalities.includes("audio")&&(s.outputModalities=["text","audio"])}break}default:break}return s}function Lt(t,e){return{id:e,object:"realtime.session",model:t.model??null,instructions:t.instructions??"",modalities:[...t.outputModalities],voice:t.voice??null,input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:t.inputAudioTranscription?{}:null,input_audio_noise_reduction:null,turn_detection:t.turnDetection?{type:"server_vad",create_response:t.turnDetection.createResponse,interrupt_response:t.turnDetection.interruptResponse}:null,temperature:t.temperature??null,max_response_output_tokens:t.maxOutputTokens??"inf",tool_choice:t.toolChoice??"auto",tools:t.tools??[],metadata:t.metadata??null}}function An(t,e){let n=t;if(!n||typeof n!="object")throw new S("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 S("function_call_output item requires string call_id and output","item.call_id","invalid_request");return{id:typeof n.id=="string"?n.id:x("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 S('message item role must be "user", "assistant" or "system"',"item.role","invalid_request");if(!Array.isArray(n.content))throw new S("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 S("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 S(`${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 S("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 S("input_audio part requires base64 audio","item.content.audio","invalid_request");o.push({type:"input_audio",...typeof i.transcript=="string"?{transcript:i.transcript}:{}});continue}throw new S(`content part type ${String(i.type)} is not supported on message items here (input_text / output_text / input_audio)`,"item.content.type","invalid_request")}return{id:typeof n.id=="string"?n.id:x("item"),type:"message",role:r,content:o}}throw new S(`item type ${String(n.type)} is not supported \u2014 message and function_call_output items only`,"item.type","invalid_request")}function In(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 Wi=1001,Ji=1011,Eo=t=>t.slice(0,120),Ki=/^[A-Za-z0-9+/=]*$/,zi=2;function Yi(t){let e=Buffer.from(t,"base64");for(let n=0;n+1<e.byteLength;n+=2)if(Math.abs(e.readInt16LE(n))>zi)return!1;return!0}var ot=class{id=x("conn");ws;binding;onClosed;config=En();sessionId=x("sess");conversationId=x("conv");items=[];pendingAudioBytes=[];pendingAudioTotalBytes=0;frozenAudio=[];inFlight=null;activeResponseId=null;responseFlushed=!1;cancelled=!1;voiceClaimed=!1;audioLaneOwner=!1;audioUnsubscribe=null;outOfTurnAudioWarned=!1;audioOnlyTranscriptGapWarned=!1;closed=!1;turnLaneAbort=null;turnTranscript={open:!1,text:""};lastCommittedTranscript=null;constructor(e){this.ws=e.ws,this.binding=e.binding,this.onClosed=e.onClosed,this.binding.model&&(this.config.model=this.binding.model),this.ws.on("message",n=>{this.onMessage(n)}),this.ws.on("close",()=>this.teardown("client disconnected")),this.ws.on("error",()=>this.teardown("client socket error")),this.send({type:"session.created",event_id:x("event"),session:Lt(this.config,this.sessionId)}),this.send({type:"conversation.created",event_id:x("event"),conversation:{id:this.conversationId,object:"realtime.conversation"}}),this.binding.turns&&this.startTurnLane()}startTurnLane(){let e=new AbortController;this.turnLaneAbort=e;let n=this.binding.turns;(async()=>{try{for await(let r of n()){if(this.closed||e.signal.aborted)return;this.onTurnEvent(r)}}catch(r){!this.closed&&!e.signal.aborted&&this.send($(rt("turn_lane_fault",`the backend turn/transcript lane failed: ${r instanceof Error?r.message:String(r)}`)))}})()}onTurnEvent(e){switch(e.kind){case"delta":case"final":{let n=typeof e.text=="string"?e.text:"";if(n.length===0)return;this.turnTranscript.open=!0,this.turnTranscript.text+=n,this.config.inputAudioTranscription&&this.send({type:"conversation.item.input_audio_transcription.delta",event_id:x("event"),item_id:"input_audio_turn",content_index:0,delta:n});return}case"turn_start":{this.turnTranscript={open:!0,text:this.turnTranscript.text},this.send({type:"input_audio_buffer.speech_started",event_id:x("event"),item_id:"input_audio_turn",audio_start_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.turnDetection?.interruptResponse&&this.inFlight&&this.cancelResponse();return}case"turn_end":{let n=this.turnTranscript.text.trim(),r=n.length>0?n:null;this.turnTranscript={open:!1,text:""},this.lastCommittedTranscript=r,this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let o=x("item"),s=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:o,type:"message",role:"user",content:[{type:"input_audio",...r!==null?{transcript:r}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:x("event"),previous_item_id:s,item_id:o}),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:s,item:this.itemToProtocol(this.items[this.items.length-1])}),this.send({type:"input_audio_buffer.speech_stopped",event_id:x("event"),item_id:o,audio_end_ms:typeof e.startMs=="number"?e.startMs:0}),this.config.inputAudioTranscription&&r!==null&&this.send({type:"conversation.item.input_audio_transcription.completed",event_id:x("event"),item_id:o,content_index:0,transcript:r}),this.config.turnDetection?.createResponse&&!this.inFlight&&this.startResponse({});return}case"turn_eager_end":case"turn_resumed":return;default:return}}takeTurnTranscript(){let e=this.lastCommittedTranscript;return this.lastCommittedTranscript=null,e}async onMessage(e){if(this.closed)return;let n;try{n=e.toString()}catch{this.fail(F("decode_error","frame is not decodable text"),"invalid_frame");return}if(Buffer.byteLength(n,"utf8")>Ct){this.fail(F("frame_too_large",`frame exceeds the ${Ct}-byte limit`),"invalid_frame");return}let r;try{r=JSON.parse(n)}catch{this.fail(F("invalid_json","frame is not valid JSON"),"invalid_frame");return}if(typeof r.type!="string"||r.type.length===0){this.fail(F("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($({type:"invalid_request_error",code:s.code??"invalid_value",message:s.message,param:s.param??null}));return}this.fail(rt(null,o instanceof Error?o.message:String(o)),"handler_fault")}}async handle(e){switch(e.type){case"session.update":this.config=nt(e.session,this.config,{voice:this.binding.voice,turns:this.binding.turns!==void 0}),this.send({type:"session.updated",event_id:x("event"),session:Lt(this.config,this.sessionId)});return;case"conversation.item.create":{let n=An(e.item,this.binding.voice),r=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem(n),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:r,item:this.itemToProtocol(n)});return}case"conversation.item.delete":{let n=this.items.findIndex(r=>r.id===e.item_id);if(n<0){this.send($(F("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:x("event"),item_id:e.item_id});return}case"conversation.item.retrieve":{let n=this.items.find(r=>r.id===e.item_id);if(!n){this.send($(F("item_not_found",`no item with id ${JSON.stringify(e.item_id)}`,"item_id")));return}this.send({type:"conversation.item.retrieved",event_id:x("event"),item:this.itemToProtocol(n)});return}case"conversation.item.truncate":{let n=this.items.find(r=>r.id===e.item_id);if(!n||n.type!=="message"||n.role!=="assistant"){this.send($(F("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:x("event"),item_id:n.id,content_index:typeof e.content_index=="number"?e.content_index:0,audio_end_ms:typeof e.audio_end_ms=="number"?e.audio_end_ms:0});return}case"input_audio_buffer.append":{if(typeof e.audio!="string"||e.audio.length===0){this.send($(F("invalid_audio",'input_audio_buffer.append requires base64 "audio"',"audio")));return}if(!this.ensureVoice())return;if(!Ki.test(e.audio)){this.send($(F("invalid_audio","input_audio_buffer.append audio must be base64","audio")));return}let n=Buffer.byteLength(e.audio,"base64");if(this.pendingAudioBytes.length+n>$t){this.send($(F("buffer_full",`uncommitted input audio exceeds the ${$t}-byte bound \u2014 commit or clear first`,"audio")));return}if(this.inFlight){this.binding.audioSession.audio.appendInputAudio(e.audio);return}this.pendingAudioBytes.push(e.audio),this.pendingAudioTotalBytes+=n;return}case"input_audio_buffer.clear":{if(!this.ensureVoice())return;this.pendingAudioBytes.length=0,this.pendingAudioTotalBytes=0,this.send({type:"input_audio_buffer.cleared",event_id:x("event")});return}case"input_audio_buffer.commit":{if(!this.ensureVoice())return;if(this.pendingAudioTotalBytes===0&&this.takeTurnTranscript()===null){this.send($(F("empty_buffer","input_audio_buffer.commit with no buffered audio","audio")));return}this.frozenAudio=this.pendingAudioBytes.splice(0),this.pendingAudioTotalBytes=0;let n=this.takeTurnTranscript();n===null&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let r=x("item"),o=this.items.length>0?this.items[this.items.length-1].id:null;this.pushItem({id:r,type:"message",role:"user",content:[{type:"input_audio",...n!==null?{transcript:n}:{}}]}),this.send({type:"input_audio_buffer.committed",event_id:x("event"),previous_item_id:o,item_id:r}),this.send({type:"conversation.item.created",event_id:x("event"),previous_item_id:o,item:this.itemToProtocol(this.items[this.items.length-1])});return}case"output_audio_buffer.clear":{this.send($(F("output_clear_unavailable","output_audio_buffer.clear has no server-side playback queue to flush on this adapter: output audio is delivered as response.output_audio.delta events and interrupted turns are stopped with response.cancel")));return}case"response.create":this.startResponse(e.response??{});return;case"response.cancel":this.cancelResponse();return;default:this.send($(F("unknown_event",`event type ${e.type} is not supported by this adapter`)))}}ensureVoice(){return!this.binding.voice||!this.binding.audioSession?(this.send($(F("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($({type:"invalid_request_error",code:"audio_input_transcript_unavailable",message:"committed input audio is forwarded to the runtime audio lane but is NOT model-visible in the text turn lane: the resolved backend wires no turn/transcript lane (the voice engine's own stt stream with turn_start/turn_end + transcripts). Wire the transcribe/turn-detection leg upstream (the resolver supplies binding.turns) and committed audio gains its REAL transcript as the model-visible turn.",param:"input_audio_buffer.commit"})))}async upstreamStream(e,n){let r=this.binding.session;if(r&&typeof r.sendResponseCreate=="function")return r.sendResponseCreate(e,e.input??[],n);let o=this.binding.clients;if(o&&typeof o.createResponse=="function")return await o.createResponse(e);throw new Error("realtime binding provides neither session.sendResponseCreate nor clients.createResponse \u2014 no upstream turn seam")}startResponse(e){if(this.inFlight){this.send($(F("response_in_progress","a response is already in progress \u2014 cancel it with response.cancel first","response.create")));return}let n=e??{};if(n.modalities!==void 0){if(!Array.isArray(n.modalities)||n.modalities.some(h=>h!=="text"&&h!=="audio")){this.send($(F("invalid_modalities",'response.modalities must be "text"/"audio"',"response.modalities")));return}if(n.modalities.includes("audio")&&!this.ensureVoice())return}if(n.input!==void 0){this.send($(F("response_input_unsupported","response.input is not supported by this adapter: build the context with conversation.item.create, then response.create","response.input")));return}this.cancelled=!1,this.responseFlushed=!1,this.messageItemAdded=!1;let r=x("req"),o=`resp_${r}`;this.activeResponseId=o;let s=this.items.length,{input:i,sawAudioOnlyItem:a}=In(this.items),u=typeof n.instructions=="string"?n.instructions:this.config.instructions,d=typeof n.temperature=="number"?n.temperature:this.config.temperature,l=n.max_output_tokens??this.config.maxOutputTokens,c=l==="inf"||l===void 0?void 0:l,m=n.tools!==void 0?n.tools:this.config.tools,p=n.tool_choice!==void 0?n.tool_choice:this.config.toolChoice,v={input:i,stream:!0,...this.config.model?{model:this.config.model}:{},...u!==void 0?{instructions:u}:{},...d!==void 0?{temperature:d}:{},...c!==void 0?{max_output_tokens:c}:{},...m!==void 0?{tools:m}:{},...p!==void 0?{tool_choice:p}:{}};for(let h of this.frozenAudio.splice(0))this.binding.audioSession?.audio.appendInputAudio(h);this.inFlight=(async()=>{let h=[],f=A=>{this.responseFlushed?this.send(A):h.push(A)},g=()=>{if(!this.responseFlushed){this.send({type:"response.created",event_id:x("event"),response:this.responseObject(o,"in_progress")}),this.send({type:"response.in_progress",event_id:x("event"),response:this.responseObject(o,"in_progress")});for(let A of h)this.send(A);h.length=0,this.responseFlushed=!0}},w={messageOpen:!1,messageText:"",tools:new Map,nextOutputIndex:0},b=null;try{a&&this.binding.turns===void 0&&this.warnAudioOnlyTranscriptGap();let A;try{A=await this.upstreamStream(v,r)}catch(R){this.emitUpstreamFault(R,o);return}try{for await(let R of A){if(this.cancelled)break;let k=R;if(k.type==="error"){let _=this.upstreamErrorBody(k);this.responseFlushed?this.send($(_)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(o,_)});return}if(k.type==="response.output_text.delta"&&typeof k.delta=="string"){g(),w.messageOpen||(this.beginMessageItem(o,w.nextOutputIndex++),w.messageOpen=!0),f({type:"response.output_text.delta",event_id:x("event"),item_id:`${o}_msg_0`,response_id:o,output_index:0,content_index:0,delta:k.delta}),w.messageText+=k.delta;continue}if(k.type==="response.function_call_arguments.delta"){g();let _=typeof k.delta=="string"?k.delta:"",C=typeof k.call_id=="string"&&k.call_id.length>0?k.call_id:`${o}_fc_${w.nextOutputIndex}`,P=w.tools.get(C);if(!P){let N=typeof k.name=="string"&&k.name.length>0?k.name:void 0;P={outputIndex:w.nextOutputIndex++,name:N,args:""},w.tools.set(C,P),f({type:"response.output_item.added",event_id:x("event"),response_id:o,output_index:P.outputIndex,item:{id:C,object:"realtime.item",type:"function_call",call_id:C,name:N??"",arguments:"",status:"in_progress"}})}typeof k.name=="string"&&k.name.length>0&&(P.name=k.name),P.args+=_,f({type:"response.function_call_arguments.delta",event_id:x("event"),item_id:C,response_id:o,output_index:P.outputIndex,call_id:C,name:P.name??"",delta:_});continue}if(k.type==="response.completed"){b=k.response??null;continue}}}catch(R){this.emitUpstreamFault(R,o);return}if(this.cancelled)return;this.closeOpenItems(o,w,s),g(),this.send({type:"response.done",event_id:x("event"),response:this.doneResponse(o,s,b)})}finally{this.inFlight=null,this.activeResponseId=null}})()}onOutputAudioFrame(e,n){if(this.cancelled)return;if(this.activeResponseId!==e){if(Yi(n))return;!this.outOfTurnAudioWarned&&!this.closed&&(this.outOfTurnAudioWarned=!0,this.send($({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:x("event"),response:this.responseObject(e,"in_progress")}),this.send({type:"response.in_progress",event_id:x("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:x("event"),item_id:r,response_id:e,output_index:0,content_index:0,delta:n})}messageItemAdded=!1;messageItemOpenForAudio=!1;beginMessageItem(e,n){let r=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:n,item:{id:r,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:x("event"),item_id:r,response_id:e,output_index:n,content_index:0,part:{type:"output_text",text:""}})}beginAudioMessageItem(e){let n=`${e}_msg_0`;this.messageItemAdded||(this.messageItemAdded=!0,this.send({type:"response.output_item.added",event_id:x("event"),response_id:e,output_index:0,item:{id:n,object:"realtime.item",type:"message",role:"assistant",status:"in_progress",content:[]}})),this.send({type:"response.content_part.added",event_id:x("event"),item_id:n,response_id:e,output_index:0,content_index:0,part:{type:"output_audio",transcript:""}})}closeOpenItems(e,n,r){if(n.messageOpen||this.messageItemOpenForAudio){let o=`${e}_msg_0`,s=this.messageItemOpenForAudio;s&&this.send({type:"response.output_audio.done",event_id:x("event"),item_id:o,response_id:e,output_index:0,content_index:0}),n.messageText.length>0&&this.send({type:"response.output_text.done",event_id:x("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:x("event"),item_id:o,response_id:e,output_index:0,content_index:0,part:s?{type:"output_audio",transcript:""}:{type:"output_text",text:n.messageText}});let i=[];s&&i.push({type:"output_audio"}),n.messageText.length>0&&i.push({type:"output_text",text:n.messageText});let a={id:o,type:"message",role:"assistant",content:i};this.pushItem(a),this.send({type:"response.output_item.done",event_id:x("event"),response_id:e,output_index:0,item:this.itemToProtocol(a)})}for(let[o,s]of n.tools){let i=s.args.length>0?s.args:"{}";this.send({type:"response.function_call_arguments.done",event_id:x("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:x("event"),response_id:e,output_index:s.outputIndex,item:this.itemToProtocol(a)})}this.messageItemOpenForAudio=!1,this.messageItemAdded=!1}responseObject(e,n,r){return{id:e,object:"realtime.response",status:n,conversation_id:this.conversationId,usage:null,...r??{}}}failedResponse(e,n){return this.responseObject(e,"failed",{status_details:{error:{code:n.code,message:n.message}}})}doneResponse(e,n,r){let o=r&&typeof r.usage=="object"&&r.usage!==null?r.usage:null,s=[];for(let i=n;i<this.items.length;i++)s.push(this.itemToProtocol(this.items[i]));return this.responseObject(e,"completed",{output:s,usage:o?{input_tokens:typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0,output_tokens:typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0,total_tokens:typeof o.total_tokens=="number"&&Number.isFinite(o.total_tokens)?o.total_tokens:(typeof o.input_tokens=="number"&&Number.isFinite(o.input_tokens)?o.input_tokens:0)+(typeof o.output_tokens=="number"&&Number.isFinite(o.output_tokens)?o.output_tokens:0),input_token_details:{cached_tokens:0,audio_tokens:0,text_tokens:0},output_token_details:{audio_tokens:0,text_tokens:0}}:null})}upstreamErrorBody(e){let n=e.error,r=n&&typeof n.message=="string"?n.message:JSON.stringify(e);return{type:"server_error",code:n&&typeof n.code=="string"?n.code:null,message:r}}emitUpstreamFault(e,n){if(this.cancelled)return;let r=rt(null,e instanceof Error?e.message:String(e));this.responseFlushed?this.send($(r)):this.send({type:"response.failed",event_id:x("event"),response:this.failedResponse(n,r)})}cancelResponse(){let e=this.inFlight;if(!e){this.send($(F("no_response_to_cancel","no response is in progress","response.cancel")));return}this.cancelled=!0;let n=this.activeResponseId??"resp_";e.finally(()=>{this.send({type:"response.cancelled",event_id:x("event"),response:this.responseObject(n,"cancelled")})})}pushItem(e){this.items.push(e),this.items.length>Pt&&(this.items.shift(),this.send($({type:"invalid_request_error",code:"transcript_evicted",message:`the conversation transcript exceeded ${Pt} items \u2014 the oldest item was evicted to keep the per-connection bound`})))}itemToProtocol(e){let n={id:e.id,object:"realtime.item"};if(e.type==="function_call")return{...n,type:"function_call",call_id:e.callId,name:e.name,arguments:e.arguments??"{}",status:"completed"};if(e.type==="function_call_output")return{...n,type:"function_call_output",call_id:e.callId,output:e.output};let r=(e.content??[]).map(o=>o.type==="input_text"||o.type==="output_text"?{type:o.type,text:o.text}:o.type==="input_audio"?{type:"input_audio",...o.transcript?{transcript:o.transcript}:{}}:{type:"output_audio",transcript:o.transcript??""});return{...n,type:"message",role:e.role,status:e.truncated?"incomplete":"completed",content:r}}send(e){if(!(this.closed||this.ws.readyState!==this.ws.OPEN)){if(this.ws.bufferedAmount>Sn){this.ws.close(Wi,Eo("outbound buffer exceeded")),this.teardown("outbound buffer exceeded");return}this.ws.send(JSON.stringify(e))}}fail(e,n){this.send($(e)),this.ws.close(Ji,Eo(n)),this.teardown(n)}teardown(e){if(!this.closed){this.closed=!0,this.turnLaneAbort?.abort(),this.turnLaneAbort=null,this.releaseVoiceBinding(),this.audioUnsubscribe?.(),this.audioUnsubscribe=null,this.binding.release&&Promise.resolve().then(()=>this.binding.release?.()).catch(n=>Ao(this.id,`binding release failed: ${n instanceof Error?n.message:String(n)}`));try{this.ws.removeAllListeners("message")}catch{}this.onClosed?.(this),Ao(this.id,e)}}},On=[];function Ao(t,e){On.push({id:t,reason:e}),On.length>256&&On.shift()}var st="/v1/realtime",Xi=t=>t.slice(0,120);function Qi(t,e,n){let r=e===401||e===403?"Unauthorized":e===502?"Upstream Fault":"Upgrade Refused";t.write(`HTTP/1.1 ${e} ${r}\r
|
|
17
|
+
Connection: close\r
|
|
18
|
+
Content-Type: text/plain\r
|
|
19
|
+
\r
|
|
20
|
+
${Xi(n)}\r
|
|
21
|
+
`),t.destroy()}function Nt(t,e){let n=new Oo.WebSocketServer({noServer:!0}),r=new Set;return t.on("upgrade",(o,s,i)=>{if(new URL(o.url??"/","http://localhost").pathname!==st)return;r.add(s),s.on("close",()=>{r.delete(s)});let u=l=>{let c=l,m=c.session!=null&&typeof c.session.sendResponseCreate=="function",p=c.clients!=null&&typeof c.clients.createResponse=="function";if(!m&&!p)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((v,h)=>{n.handleUpgrade(o,s,i,f=>{try{new ot({ws:f,binding:l}),v()}catch(g){h(g)}})})};(typeof e.resolver=="function"?e.resolver:e.resolver.resolve.bind(e.resolver))(o).then(u).catch(l=>{let c=l instanceof Io.SessionFailedError?Tt(l):null,m=null;if(l!==null&&typeof l=="object"&&"status"in l){let h=l.status;typeof h=="number"&&(m=h)}let p=m??c?.status??502,v=l instanceof Error?l.message:String(l);s.destroyed||Qi(s,p,v)}).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 Da=require("http");var Zi=yt(require("os"),1),ea=yt(require("path"),1),ta=require("url"),na=require("util");function To(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 Ut(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 ra=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function oa(t){let e=t?.code;return typeof e=="string"&&ra.has(e)}function Ce(t,e){try{return t.write(e),!0}catch(n){if(oa(n))return!1;throw n}}var Co="/v1/images/generations",Mt="/v1/images/edits";function Po(t){return t===Co||t===Mt}var $o="/v1/images/models";async function Lo(t,e,n){if(t){if(t.model=ae({model:n}),t.stream=!1,typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var T=class extends Error{status;param;constructor(e,n,r){super(n),this.status=e,this.param=r}},sa=16*1024*1024,No=64*1024*1024;function Uo(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 it(t,e){t.statusCode=e.status,t.setHeader("content-type","application/json"),t.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var de=class extends Error{};async function ia(t,e){let n=Number(t.headers["content-length"]??"0");if(Number.isFinite(n)&&n>e)throw new de(`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 de(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function Mo(t,e,n,r){let o=await t.createResponse({model:e,input:[{role:"user",content:n}],stream:!1},r),s=null;for await(let c of o){if(c.type==="error"){let m=c.error??{};throw new T(502,`image upstream error: ${String(m.message??"upstream reported an error")}`)}if(c.type==="response.completed"){s=c.response??null;break}}if(s===null)throw new T(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=s.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new T(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(Uo(d)===null)throw new T(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function Do(t){return t instanceof T?t:t instanceof B?new T(404,t.message):new T(502,`image upstream failed: ${String(t instanceof Error?t.message:t)}`)}async function Bo(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 it(r,new T(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 Fo(t,e){t&&(t.outputUnits=e.images.length)}function jo(t,e){t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(n=>({b64_json:n}))}))}var aa={model:!0,prompt:!0,response_format:!0,n:!0};async function qo(t,e,n){let r=n.maxBodyBytes??No;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Co}`);let o;try{o=JSON.parse((await ia(t,r)).toString("utf8")||"{}")}catch(c){throw c instanceof de?new T(413,c.message):new T(400,"request body is not valid JSON")}if(o===null||typeof o!="object"||Array.isArray(o))throw new T(400,"request body must be a JSON object");let s=o;for(let c of Object.keys(s))if(!aa[c])throw new T(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let i=s.prompt;if(typeof i!="string"||i.trim().length===0)throw new T(400,"prompt is required and must be a non-empty string","prompt");let a=s.model===void 0?void 0:s.model;if(a!==void 0&&typeof a!="string")throw new T(400,"model must be a string","model");await Lo(n.turn,n.clients,a);let u=s.n??1;if(u!==1)throw new T(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=s.response_format??"b64_json";if(d!=="b64_json")throw new T(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(n.stats?.request("images_generations",i.length,i.length),!await Bo(n.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await Mo(n.clients,a,l,n.turn?ie(n.turn):void 0);Fo(n.turn,c),jo(e,c)}catch(c){throw Do(c)}}catch(o){if(o instanceof de){it(e,new T(413,o.message));return}if(o instanceof T){it(e,o);return}throw o}}var ua={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function Ho(t,e,n){let r=n.maxBodyBytes??No,o=n.maxImagePartBytes??sa;try{if(t.method!=="POST")throw new T(405,`${String(t.method)} is not supported on ${Mt}`);let s=String(t.headers["content-type"]??"");if(!s.toLowerCase().startsWith("multipart/form-data"))throw new T(400,`the edit endpoint consumes multipart/form-data, got ${s||"none"}`);let i=t[Symbol.asyncIterator](),a=0,u=new ReadableStream({async pull(f){try{let g=await i.next();if(g.done){f.close();return}if(a+=g.value.length,a>r){f.error(new de(`request body exceeds the ${r}-byte limit`));return}f.enqueue(g.value)}catch(g){f.error(g)}},cancel(){i.return?.()}}),d;try{let f=new Headers;for(let[b,A]of Object.entries(t.headers))if(typeof A=="string")f.set(b,A);else if(Array.isArray(A))for(let R of A)f.append(b,R);let g={method:"POST",headers:f,body:u,duplex:"half"};d=await new Request(`https://proxy.internal${t.url??"/"}`,g).formData()}catch(f){throw f instanceof de?new T(413,f.message):new T(400,`malformed multipart body: ${String(f instanceof Error?f.message:f)}`)}let l=d.get("prompt");if(typeof l!="string"||l.trim().length===0)throw new T(400,"prompt is required and must be a non-empty string field","prompt");let c=d.get("model");if(c!==null&&typeof c!="string")throw new T(400,"model must be a string field","model");let m=c===null?void 0:c;await Lo(n.turn,n.clients,m);let p=d.get("response_format")??"b64_json";if(p!=="b64_json")throw new T(400,`response_format ${JSON.stringify(p)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let f of d.keys())if(!ua[f])throw new T(400,`form field "${f}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,f);let v=[];for(let f of["image","image[]"])for(let g of d.getAll(f)){if(!(g instanceof File))throw new T(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",f);if(g.size>o)throw new T(413,`image part exceeds the ${o}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,f);let w=new Uint8Array(await g.arrayBuffer()),b=Uo(w);if(b===null)throw new T(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",f);v.push({bytes:w,mime:b})}if(v.length===0)throw new T(400,"the edit endpoint requires at least one `image` file part","image");if(n.stats?.request("images_edits",l.length,l.length),!await Bo(n.imageModels,m,"edit",e))return;let h=[{type:"input_text",text:l}];for(let{bytes:f,mime:g}of v)h.push({type:"input_image",image_url:`data:${g};base64,${Buffer.from(f).toString("base64")}`});try{let f=await Mo(n.clients,m,h,n.turn?ie(n.turn):void 0);Fo(n.turn,f),jo(e,f)}catch(f){throw Do(f)}}catch(s){if(s instanceof de){it(e,new T(413,s.message));return}if(s instanceof T){it(e,s);return}throw s}}var Bt="/v1/usage/requests",Go=1e4,da=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,me=class extends Error{constructor(n,r=400){super(n);this.status=r;this.name="UsageRequestError"}status},U=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Dt=class extends U{constructor(e){super(e),this.name="UsageWithholdingError"}},Ko=1024*1024;function Pn(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new me(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let n=t[e];if(!Array.isArray(n))throw new me(`"${e}" must be an array of uuid strings`);if(n.length>Go)throw new me(`"${e}" carries ${n.length} ids; at most ${Go} 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"||!da.test(s))throw new me(`"${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 zo(t){return Pn(t,"inference_ids")}var la=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","cost_nano_usd","price_version","priced_at"];function Pe(t,e,n){let r=t[e];if(typeof r!="string"||r==="")throw new U(`${n}: ${e} is not a non-empty string (got ${$e(r)})`);return r}function Tn(t,e,n){let r=t[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new U(`${n}: ${e} is neither null nor a non-empty string (got ${$e(r)})`);return r}function at(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 U(`${n}: ${e} is not a number (got ${$e(o)})`);if(r&&!Number.isSafeInteger(s))throw new U(`${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 U(`${n}: ${e} is negative`);return Object.is(s,-0)?0:s}var ca=40,Vo=64,Wo=600;function Yo(t){let e=Object.keys(t).sort(),r=e.slice(0,ca).map(o=>o.length>Vo?`${o.slice(0,Vo)}\u2026`:o).join(", ");return r.length>Wo&&(r=`${r.slice(0,Wo)}\u2026`),`${e.length} keys present: [${r}]`}function $e(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?"an array":typeof t=="object"?"an object":`a ${typeof t}`}function Cn(t){Ce(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:t.where,reason:t.reason})}
|
|
22
|
+
`)}function pa(t,e){let n;try{n=t(e)}catch{Jo(t,e);return}fa(n)&&Promise.resolve(n).catch(()=>{Jo(t,e)})}function fa(t){return typeof t?.then=="function"}function Jo(t,e){if(t!==Cn)try{Cn(e)}catch{}}function Xo(t,e=Cn){let n=t?.requests;if(!Array.isArray(n)){let o=t!==null&&typeof t=="object"&&!Array.isArray(t)?Yo(t):$e(t);throw new U(`the usage surface answered without a "requests" array: got ${$e(n)} (${o})`)}let r=[];for(let o=0;o<n.length;o++){let s=`usage.requests[${o}]`;try{r.push(ma(n[o],s))}catch(i){if(i instanceof Dt||!(i instanceof U))throw i;pa(e,{where:s,reason:i.message})}}if(n.length>0&&r.length===0)throw new U(`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 ma(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new U(`${e} is not an object: got ${$e(t)}`);let n=t;if(Object.hasOwn(n,"gpu_seconds"))throw new Dt(`${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 la)if(!Object.hasOwn(n,o))throw new U(`${e} has no "${o}" column (${Yo(n)})`);let r=at(n,"http_status",e,!0);if(r===null)throw new U(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:Pe(n,"inference_id",e),model_id:Pe(n,"model_id",e),identity_kind:Pe(n,"identity_kind",e),variant:Tn(n,"variant",e),task:Pe(n,"task",e),http_status:r,started_at:Pe(n,"started_at",e),completed_at:Pe(n,"completed_at",e),prompt_tokens:at(n,"prompt_tokens",e,!0),completion_tokens:at(n,"completion_tokens",e,!0),output_units:at(n,"output_units",e,!1),cost_nano_usd:at(n,"cost_nano_usd",e,!0),price_version:Tn(n,"price_version",e),priced_at:Tn(n,"priced_at",e)}}function Ft(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 U(`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 U(`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 Vt=require("@urun-sh/core");var ut="/partners/huggingface/v1/billing/requests";function ga(t){return Pn(t,"requestIds")}function ha(t){return t>=200&&t<=399}function ya(t){let e=[];for(let n of t)n.cost_nano_usd!==null&&ha(n.http_status)&&e.push({requestId:n.inference_id,costNanoUsd:n.cost_nano_usd});return{requests:e.length>0?e:null}}async function Qo(t,e){let n=ga(t),r=await e(n);return Ft(r,n),ya(r)}var _a=new Map([["/v1/chat/completions","conversational"],["/v1/responses","conversational"],["/v1/messages","conversational"],["/v1/images/generations","text-to-image"],["/v1/images/edits","image-to-image"]]);function wa(t){return _a.get(t)??null}var va=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function ba(t){let e=t?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function ka(t){return t==="surface"}function xa(t){let e=t?.ledgerFailureReason;return va.includes(e)?e:"unknown"}function Ra(t){return t.status===null?!1:t.status>=200&&t.status<400&&!t.stream_error}function Sa(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 Ea=256,Zo=4096,lt=12e4,Aa=250,Ia=8e3,Re=[],es=new Set,ct=0,dt=!1;function ts(){return Re.length}function ns(t=Date.now()){let e=Re[0];return e===void 0?0:Math.max(0,t-e.queuedAt)}var Oa=new Set;function Ta(){return ct===0&&Re.length===0}function Ca(){if(Ta()){dt=!1;for(let t of[...Oa])t()}}function rs(t,e){return`${JSON.stringify({event:t,ts:new Date().toISOString(),...e})}
|
|
23
|
+
`}function Pa(t){Ce(process.stdout,t)}function os(t,e){try{t(e)}catch{}}function ss(t){let{record:e,ledger:n}=t;if(n===null)return;let r=n.report??Pa,o=wa(e.path);if(o===null)return;let s=l=>{try{n.observe(l)}catch{}},i=(l,c)=>{s({outcome:"skipped",reason:l}),os(r,rs("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:o,http_status:e.status,started_at:Sa(e),completed_at:e.ts,billable_outcome:Ra(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms};if(Re.length>=Zo){i("queue_full",`${Re.length} ledger writes are already waiting (capacity ${Zo}, ${ct} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}Re.push({entry:d,req:t.req,record:e,ledger:n,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),ct<Ea&&(ct+=1,$a())}async function $a(){try{for(;;){let t=La();if(t===void 0)return;es.add(t);try{await Na(t)}finally{es.delete(t)}}}finally{ct-=1,Ca()}}function La(){let t=Date.now();for(;;){let e=Re.shift();if(e===void 0)return;let n=t-e.queuedAt;if(n<lt)return e;Le(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 ${lt}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 Na(t){let{entry:e,record:n,ledger:r}=t;for(;;){t.attempts+=1;try{let o=await r.write(t.req,e);Le(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=ba(o);if(s!==null){Le(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=xa(o),a=Date.now()-t.queuedAt;if(dt){Le(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(ka(i)&&a<lt){if(await Ma(Ua(t.attempts)),dt||Date.now()-t.queuedAt>=lt){let u=Date.now()-t.queuedAt;Le(t,{outcome:"failed",reason:dt?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:dt?"dropped_on_exit":"dwell_expired",attempts:t.attempts,waited_ms:u,error:`this row's backoff outlived the ${lt}ms dwell bound (waited ${u}ms over ${t.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${o instanceof Error?o.message:String(o)}`});return}continue}Le(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 Ua(t){return Math.min(Ia,Aa*2**Math.max(0,t-1))}function Ma(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}function Le(t,e,n){if(t.settled)return;t.settled=!0;try{t.ledger.observe(e)}catch{}let{event:r,...o}=n;os(t.report,rs(r,{inference_id:t.entry.inference_id,path:t.record.path,org:t.record.org,...o}))}function Nn(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function K(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function le(t,e,n,r="invalid_request_error",o){K(t,e,{error:o?{message:n,type:r,code:o}:{message:n,type:r}})}function us(t,e){let n=e.error,r=n?.type??"upstream_error",o=n?.message??JSON.stringify(e);K(t,r==="invalid_request_error"?400:502,{error:{message:o,type:r,code:n?.code??null}})}function ne(t,e,n,r){K(t,e,{type:"error",error:{type:n,message:r}})}function jt(t,e,n){if(e==="anthropic"){K(t,404,{type:"error",error:{type:"not_found_error",message:n.message}});return}K(t,404,{error:{message:n.message,type:"invalid_request_error",code:"model_not_found"}})}var Ba=64*1024*1024,pt=class extends Error{};async function is(t,e=Ba){let n=[],r=0;for await(let s of t){if(r+=s.length,r>e)throw new pt(`request body exceeds ${e} bytes`);n.push(s)}let o=Buffer.concat(n).toString("utf8");return o?JSON.parse(o):{}}function Ne(t,e,n,r){return{id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:n,finish_reason:r}]}}function ds(t){let e=t?.usage;if(!e||typeof e!="object")return{kind:"absent"};let n=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,o=r(n.input_tokens),s=r(n.output_tokens),i=u=>u??0,a=r(n.total_tokens)??i(o)+i(s);if(i(o)>0||i(s)>0){let u={input_tokens:i(o),output_tokens:i(s),total_tokens:a};return o===null||s===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return o===null||s===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function qt(t){let e=ds(t);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function as(t){let e=qt(t);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function Fa(t,e){let n=ds(e);n.kind==="absent"||n.kind==="partial"||(t.promptTokens=n.usage.input_tokens,t.completionTokens=n.usage.output_tokens)}function ja(t){let e=t?.urun_timing;if(!e||typeof e!="object")return null;let n=e,r=u=>{let d=n[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},o=r("queue_ms"),s=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return o===null||s===null||i===null||a===null?null:{queue_ms:o,prefill_ms:s,decode_ms:i,total_ms:a}}function qa(t,e){let n=ja(e);n&&(t.timing=n)}function Ue(t,e){Fa(t,e),qa(t,e)}async function Un(t,e,n){if(typeof e.catalogIdentity!="function"){t.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(n);if(r!==null){t.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let o=typeof e.servingAppSlug=="function"?await e.servingAppSlug(n):null;t.catalog={kind:"not-a-catalog-model",model:o??n??null}}catch(r){t.catalog={kind:"unresolved",reason:`model ${JSON.stringify(n??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function ls(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 Ha(t){if(Array.isArray(t))return t.map(e=>{let n=e.function;return!n||typeof n!="object"?e:{type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:n.strict}})}var Ht=class extends Error{};function Ga(t,e){return Array.isArray(e)?e.map(n=>{let r=n;if(r.type==="text")return{type:t==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let o=r.image_url??{};return{type:"input_image",image_url:o.url,detail:o.detail}}throw new Ht(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function Va(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:Ga(n.role,n.content)})}return e}function $n(t){return Ie(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 Wa(t,e,n,r,o,s){let i=Ze(s.id),a=t.stream===!0;if(s.model=ae(t),s.stream=a,await Un(s,e,typeof t.model=="string"?t.model:void 0),a){let g;try{g=await tt({body:t,clients:e,store:n,stats:o,responseId:i,turn:s})}catch(w){if(w instanceof B){jt(r,"openai",w);return}if(w instanceof ee){le(r,w.status,w.message);return}throw w}Nn(r);for await(let w of g.events)w.type==="error"&&(s.streamError=!0),w.type==="response.completed"&&Ue(s,w.response),r.write(`event: ${String(w.type??"message")}
|
|
24
|
+
data: ${JSON.stringify(w)}
|
|
3
25
|
|
|
4
|
-
`)
|
|
26
|
+
`);r.write(`data: [DONE]
|
|
5
27
|
|
|
6
|
-
`),
|
|
28
|
+
`),r.end();return}let u;try{u=Te(n,t)}catch(g){if(g instanceof ee){le(r,g.status,g.message);return}throw g}t.previous_response_id!=null&&(o.naiveInBytes+=Buffer.byteLength(JSON.stringify(u))-Buffer.byteLength(JSON.stringify(t.input)));let d=t.store!==!1,l=ae(t);o.model(l);let c=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await wn(e,t,u,!1,ie(s))}catch(g){if(g instanceof B){jt(r,"openai",g);return}if(g instanceof ee){le(r,g.status,g.message);return}throw g}let p=[],v=null;for await(let g of o.track(m,l,s)){if(p.push(g),g.type==="error"){us(r,g);return}g.type==="response.completed"&&(v=g.response)}if(v==null){le(r,502,"upstream produced no response.completed event","upstream_error");return}Ue(s,v);let h=yn(p,v),f=xe(c,Ie(v).length,h);if(f){le(r,502,ke(l,f),"upstream_error");return}d&&n.remember(i,u,_n(v,h),d),K(r,200,{...v,id:i})}async function Ja(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){le(n,400,"chat/completions requires a messages array");return}let i=String(t.model??"urun"),a=go(o.id),u;try{u=Va(s)}catch(_){if(_ instanceof Ht){le(n,400,_.message);return}throw _}let d=ae(t);r.model(d),o.model=d,o.stream=t.stream===!0,await Un(o,e,typeof t.model=="string"?t.model:void 0);let l=Array.isArray(t.tools)&&t.tools.length>0,c;try{c=await e.createResponse({model:t.model,input:u,stream:!0,tools:Ha(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}:{}},ie(o))}catch(_){if(_ instanceof B){jt(n,"openai",_);return}throw _}if(t.stream===!0){Nn(n);let _=[],C=new pe,P="";n.write(`data: ${JSON.stringify(Ne(a,i,{role:"assistant"},null))}
|
|
7
29
|
|
|
8
|
-
`);for await(let
|
|
30
|
+
`);for await(let H of r.track(c,d,o)){_.push(H);let I=Oe(H);if(H.type==="response.output_text.delta"&&typeof H.delta=="string")P+=H.delta,n.write(`data: ${JSON.stringify(Ne(a,i,{content:H.delta},null))}
|
|
9
31
|
|
|
10
|
-
`);else if(
|
|
32
|
+
`);else if(H.type==="response.reasoning_text.delta"&&typeof H.delta=="string")n.write(`data: ${JSON.stringify(Ne(a,i,{reasoning_content:H.delta},null))}
|
|
11
33
|
|
|
12
|
-
`);else if(
|
|
34
|
+
`);else if(I){let{call:L,isNew:j}=C.add(I),Q=j?{index:I.tool_index,id:L.id??`call_${I.tool_index}`,type:"function",function:{name:L.name??"",arguments:I.delta}}:{index:I.tool_index,function:{arguments:I.delta}};n.write(`data: ${JSON.stringify(Ne(a,i,{tool_calls:[Q]},null))}
|
|
13
35
|
|
|
14
|
-
`)}else if(
|
|
36
|
+
`)}else if(H.type==="error"){o.streamError=!0,n.write(`data: ${JSON.stringify({error:H})}
|
|
15
37
|
|
|
16
|
-
`),
|
|
38
|
+
`),n.end();return}}let N=$n(ue(_)),O=xe(l,C.size+N.length,P);if(O){o.streamError=!0,n.write(`data: ${JSON.stringify({error:{type:"urun_error",code:"tool_call_parser_missing",message:ke(d,O)}})}
|
|
17
39
|
|
|
18
|
-
`),
|
|
40
|
+
`),n.end();return}C.size===0&&N.length>0&&n.write(`data: ${JSON.stringify(Ne(a,i,{tool_calls:N},null))}
|
|
19
41
|
|
|
20
|
-
`);let
|
|
42
|
+
`);let te=C.size>0||N.length>0;n.write(`data: ${JSON.stringify(Ne(a,i,{},te?"tool_calls":"stop"))}
|
|
21
43
|
|
|
22
|
-
`)
|
|
44
|
+
`);let X=qt(ue(_));Ue(o,ue(_)),X&&n.write(`data: ${JSON.stringify({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[],usage:as(ue(_))})}
|
|
23
45
|
|
|
24
|
-
`),
|
|
46
|
+
`),n.write(`data: [DONE]
|
|
25
47
|
|
|
26
|
-
`),
|
|
27
|
-
data: ${JSON.stringify({type:
|
|
48
|
+
`),n.end();return}let m="",p="",v=[],h=new pe;for await(let _ of r.track(c,d,o)){v.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(m+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(p+=_.delta);let C=Oe(_);if(C&&h.add(C),_.type==="error"){us(n,_);return}}let f=ue(v);Ue(o,f);let g=$n(f),w=g.length>0?g:$n({output:h.items()}),b=xe(l,w.length,m);if(b){le(n,502,ke(d,b),"upstream_error");return}let A=w.map(({index:_,...C})=>C),R={role:"assistant",content:m||null},k=p||ls(f);k&&(R.reasoning_content=k),A.length>0&&(R.tool_calls=A),K(n,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:R,finish_reason:A.length>0?"tool_calls":"stop"}],usage:as(f)})}function Ka(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>String(e.text??"")).join(""):""}var ft=class extends Error{};function Gt(t){return new ft(`unsupported anthropic content block type "${t}" \u2014 the proxy translates text, tool_use and tool_result blocks`)}function za(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 Ya(t){if(t==null)return;let e=t.type;if(e==="auto")return"auto";if(e==="none")return"none";if(e==="any")return"required";if(e==="tool")return{type:"function",name:t.name};throw new ft(`unsupported anthropic tool_choice type ${JSON.stringify(String(e))} \u2014 the proxy maps auto, none, any and tool`)}function Xa(t){if(typeof t=="string")return t;if(t==null)return"";if(!Array.isArray(t))throw Gt(typeof t);let e="";for(let n of t){let r=String(n.type??"");if(r!=="text")throw Gt(`tool_result > ${r}`);e+=String(n.text??"")}return e}function Qa(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 Gt(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:Xa(i.content)});else{if(a==="thinking"||a==="redacted_thinking")continue;throw Gt(a)}}return s(),r}function Ln(t){return Ie(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 Za(t,e,n,r,o){let s=t.messages;if(!Array.isArray(s)){ne(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){ne(n,400,"invalid_request_error","max_tokens is required and must be a positive integer");return}if(t.top_k!==void 0){ne(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(_=>typeof _!="string"))){ne(n,400,"invalid_request_error","stop_sequences must be an array of strings");return}let i=String(t.model??"urun"),a=ho(o.id),u=[],d;try{t.system&&u.push({role:"system",content:Ka(t.system)});for(let _ of s)u.push(...Qa(_));d=Ya(t.tool_choice)}catch(_){if(_ instanceof ft){ne(n,400,"invalid_request_error",_.message);return}throw _}let l=ae(t);r.model(l),o.model=l,o.stream=t.stream===!0,await Un(o,e,typeof t.model=="string"?t.model:void 0);let c=Array.isArray(t.tools)&&t.tools.length>0,m;try{m=await e.createResponse({model:t.model,input:u,stream:!0,tools:za(t.tools),tool_choice:d,temperature:t.temperature,max_output_tokens:t.max_tokens,top_p:t.top_p,stop:t.stop_sequences},ie(o))}catch(_){if(_ instanceof B){jt(n,"anthropic",_);return}throw _}let p=(_,C)=>{n.destroyed||n.write(`event: ${_}
|
|
49
|
+
data: ${JSON.stringify({type:_,...C})}
|
|
28
50
|
|
|
29
|
-
`)};if(t.stream===!0){let
|
|
30
|
-
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:
|
|
51
|
+
`)};if(t.stream===!0){let _=r.track(m,l,o);Nn(n),p("message_start",{message:{id:a,type:"message",role:"assistant",content:[],model:i,stop_reason:null,usage:{input_tokens:0,output_tokens:0}}});let C=0,P="",N=0,O="none",te=()=>O,X=-1,H=-1,I=new pe,L=[],j=()=>{O!=="none"&&(O="none",p("content_block_stop",{index:X}))},Q=(D,Y)=>{j(),O=D,X=N++,p("content_block_start",{index:X,content_block:Y})};for await(let D of _){if(n.destroyed)break;L.push(D);let Y=Oe(D);if(D.type==="response.reasoning_text.delta"&&typeof D.delta=="string")te()!=="thinking"&&Q("thinking",{type:"thinking",thinking:""}),p("content_block_delta",{index:X,delta:{type:"thinking_delta",thinking:D.delta}});else if(D.type==="response.output_text.delta"&&typeof D.delta=="string")te()!=="text"&&Q("text",{type:"text",text:""}),C+=1,P+=D.delta,p("content_block_delta",{index:X,delta:{type:"text_delta",text:D.delta}});else if(Y){let{call:hr}=I.add(Y);(te()!=="tool"||Y.tool_index!==H)&&(H=Y.tool_index,Q("tool",{type:"tool_use",id:hr.id??`call_${Y.tool_index}`,name:hr.name??"",input:{}})),Y.delta&&p("content_block_delta",{index:X,delta:{type:"input_json_delta",partial_json:Y.delta}})}else if(D.type==="error"){o.streamError=!0,p("error",{error:{type:"api_error",message:JSON.stringify(D)}}),n.end();return}}if(n.destroyed)return;let he=ue(L),ye=Ie(he),ce=xe(c,I.size+ye.length,P);if(ce){o.streamError=!0,p("error",{error:{type:"api_error",message:ke(l,ce)}}),n.end();return}j();let re=[];if(I.size===0)try{re=Ln(he)}catch(D){o.streamError=!0,p("error",{error:{type:"api_error",message:String(D instanceof Error?D.message:D)}}),n.end();return}N===0&&re.length===0&&(Q("text",{type:"text",text:""}),j()),re.forEach(D=>{let Y=N++;p("content_block_start",{index:Y,content_block:{...D,input:{}}}),p("content_block_delta",{index:Y,delta:{type:"input_json_delta",partial_json:JSON.stringify(D.input??{})}}),p("content_block_stop",{index:Y})});let Je=I.size>0||re.length>0,Ee=qt(he);Ue(o,he),p("message_delta",{delta:{stop_reason:Je?"tool_use":"end_turn"},usage:Ee?{input_tokens:Ee.input_tokens,output_tokens:Ee.output_tokens}:{output_tokens:C}}),p("message_stop",{}),n.end();return}let v="",h="",f=[],g=new pe;for await(let _ of r.track(m,l,o)){f.push(_),_.type==="response.output_text.delta"&&typeof _.delta=="string"&&(v+=_.delta),_.type==="response.reasoning_text.delta"&&typeof _.delta=="string"&&(h+=_.delta);let C=Oe(_);if(C&&g.add(C),_.type==="error"){let P=_.error,N=P?.type==="invalid_request_error";ne(n,N?400:502,N?"invalid_request_error":"api_error",P?.message??JSON.stringify(_));return}if(n.destroyed)break}if(n.destroyed)return;let w=ue(f);Ue(o,w);let b;try{b=Ln(w),b.length===0&&g.size>0&&(b=Ln({output:g.items()}))}catch(_){ne(n,502,"api_error",String(_ instanceof Error?_.message:_));return}let A=xe(c,b.length,v);if(A){ne(n,502,"api_error",ke(l,A));return}let R=[],k=h||ls(w);k&&R.push({type:"thinking",thinking:k}),(v||b.length===0)&&R.push({type:"text",text:v}),R.push(...b),K(n,200,{id:a,type:"message",role:"assistant",content:R,model:i,stop_reason:b.length>0?"tool_use":"end_turn",usage:qt(w)??{input_tokens:0,output_tokens:0}})}function eu(t){Ce(process.stdout,t)}function cs(t){let{clients:e,apiKey:n,identity:r,statusOf:o}=t,s=typeof e=="function"?e:()=>e,i=t.requestLog??eu,a=t.observe,u=new ve;return(d,l)=>{let c=new URL(d.url??"/","http://localhost"),m=c.pathname==="/v1/messages"||c.pathname.startsWith("/v1/messages/"),p=(w,b,A,R,k)=>m?ne(l,w,R,b):le(l,w,b,A,k),v=hn(c.pathname),h=c.pathname.startsWith("/partners/"),f=v||h?{id:Qe(),startedAt:performance.now(),streamError:!1,model:null,stream:null,org:null,ttftMs:null,catalog:{kind:"unresolved",reason:"no lane resolved a model for this request"},promptTokens:null,completionTokens:null,outputUnits:null,sessionId:null,timing:null}:null;f&&(l.setHeader(fo,f.id),l.once("close",()=>{let w=yo({turn:f,method:d.method??"",path:c.pathname,res:l});i(_o(w)),a?.(w),ss({record:w,ledger:t.ledger??null,req:d})}));let g=()=>mo(c.pathname,f);(async()=>{if(d.method==="GET"&&c.pathname==="/healthz"){K(l,200,{ok:!0});return}if(d.method==="GET"&&c.pathname==="/stats"){K(l,200,r?{identity:r,...u.snapshot()}:u.snapshot());return}if(n&&(d.headers.authorization??"")!==`Bearer ${n}`){p(401,"invalid local proxy api key","authentication_error","authentication_error");return}let w=c.pathname===Bt?"canonical":c.pathname===ut?"huggingface":null;if(w){if(d.method!=="POST"){p(405,`${c.pathname} is a POST batch lookup`,"invalid_request_error","invalid_request_error");return}let k=t.usage;if(!k){p(501,`${c.pathname} needs a usage seam (ProxyHandlerOptions.usage) to read the per-request inference ledger; this proxy has none, and answering an empty result would be indistinguishable from "nothing is priced yet"`,"not_implemented","not_implemented_error");return}let _=k.authorize(d),C;try{C=await is(d,Ko)}catch(O){if(O instanceof pt){p(413,O.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let P=O=>k.lookup(_,O),N;try{if(w==="canonical"){let O=zo(C),te=await P(O);Ft(te,O),N={requests:te}}else N=await Qo(C,P)}catch(O){if(O instanceof me){p(O.status,O.message,"invalid_request_error","invalid_request_error");return}throw O}K(l,200,N);return}if(c.pathname.startsWith("/partners/")){p(404,`no partner adapter for ${d.method} ${c.pathname} \u2014 the partner surface currently carries ${ut}`,"invalid_request_error","not_found_error");return}let b=await s(d);if(f&&(f.org=b.tenant??null),d.method==="GET"&&c.pathname==="/v1/models"){if(c.searchParams.get("format")==="openrouter"){if(!b.openRouterModels){p(501,"format=openrouter needs a router-backed client (openRouterModels)","not_implemented","not_implemented_error");return}K(l,200,await b.openRouterModels());return}K(l,200,await b.listModels());return}if(d.method==="GET"&&c.pathname===$o){if(!b.listImageModels){p(501,"GET /v1/images/models needs a router-backed client (listImageModels)","not_implemented","not_implemented_error");return}K(l,200,await b.listImageModels());return}if(Po(c.pathname)){if(!b.supportsImages){p(501,`the image lanes need a router-backed client (supportsImages) to gate model capability for ${c.pathname}`,"not_implemented","not_implemented_error");return}let k={clients:b,imageModels:b.supportsImages,stats:u,turn:g()};c.pathname===Mt?await Ho(d,l,k):await qo(d,l,k);return}if(d.method!=="POST"){p(404,`no route for ${d.method} ${c.pathname}`,"invalid_request_error","not_found_error");return}let A;try{A=await is(d)}catch(k){if(k instanceof pt){p(413,k.message,"request_too_large","request_too_large");return}p(400,"request body is not valid JSON","invalid_request_error","invalid_request_error");return}let R=Buffer.byteLength(JSON.stringify(A));if(c.pathname==="/v1/responses"){u.request("responses",R,R),await Wa(A,b,et(b),l,u,g());return}if(c.pathname==="/v1/chat/completions"){u.request("chat_completions",R,R),await Ja(A,b,l,u,g());return}if(c.pathname==="/v1/messages"){u.request("messages",R,R),await Za(A,b,l,u,g());return}if(c.pathname==="/v1/messages/count_tokens"){u.request("count_tokens",R,R),ne(l,404,"not_found_error","count_tokens is not implemented by the uRun proxy: the serve transport exposes no token-count lane, and the proxy will not fabricate counts");return}p(404,`no route for POST ${c.pathname}`,"invalid_request_error","not_found_error")})().catch(w=>{let b=String(w instanceof Error?w.message:w);if(!l.headersSent){let A=o?.(w)??null;if(A){p(A.status,b,A.openaiType,A.anthropicType);return}if(w instanceof Vt.SessionAllocationError){let R=Ot(w.code);if(R){let k=w.retryAfterSeconds??(R.status===429?30:void 0);k!==void 0&&l.setHeader("Retry-After",String(k)),p(R.status,b,R.openaiType,R.anthropicType,R.code);return}}if(w instanceof Vt.SessionFailedError){let R=Tt(w);if(R){let k=R.status===429?30:void 0;k!==void 0&&l.setHeader("Retry-After",String(k)),p(R.status,b,R.openaiType,R.anthropicType,R.code);return}}if(w instanceof U){p(502,b,"upstream_error","api_error");return}p(500,b,"proxy_error","api_error","proxy_error");return}f&&(f.streamError=!0),l.destroyed||(m?l.write(`event: error
|
|
52
|
+
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:b}})}
|
|
31
53
|
|
|
32
|
-
`):
|
|
54
|
+
`):l.write(`data: ${JSON.stringify({error:{message:b,type:"upstream_error"}})}
|
|
33
55
|
|
|
34
|
-
`)),p.end()})}}var ve=require("@urun-sh/core"),F=class extends Error{constructor(e,o=401){super(e);this.status=o;this.name="ProxyAuthError"}status},W=class extends Error{constructor(n){super(n),this.name="ControlPlaneUnavailableError"}};function ke(t){let n=(t??"").trim();if(n==="")throw new F("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let e=/^Bearer[ \t]+(\S.*)$/i.exec(n);if(!e)throw new F("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return e[1].trim()}var kn=60,De=6e4,Ve=4096;function xn(t){return t===401||t===403}var te=class{constructor(n){this.opts=n;this.mint=n.mint??ve.createClientToken,this.now=n.now??Date.now}opts;cache=new Map;mint;now;async resolve(n){if(n==="")throw new F("empty Authorization bearer token");let e=this.cache.get(n);if(e&&this.now()-e.at<De)return{apiKey:n,orgId:e.orgId};let o;try{o=(await this.mint(n,{baseUrl:this.opts.gatewayUrl,expiresIn:kn})).orgId}catch(r){throw r instanceof ve.ClientTokenError&&xn(r.status)?(this.cache.delete(n),new F("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new W(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${r instanceof Error?r.message:String(r)}`)}if(!o)throw new W("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=Ve){let r=this.cache.keys().next();r.done||this.cache.delete(r.value)}return this.cache.set(n,{orgId:o,at:this.now()}),{apiKey:n,orgId:o}}clear(){this.cache.clear()}};var Ot=require("crypto");var le=require("@urun-sh/core");async function gt(t){let e=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!e.ok)throw new Error(`model_catalog fetch failed: ${e.status}`);return await e.json()}function ht(t,n,e,o){let r=t.response??{},i={request_id:e,consumer_id:o,stream:!0,kind:"chat",messages:n};return typeof r.instructions=="string"&&(i.instructions=r.instructions),Array.isArray(r.modalities)&&(i.modalities=r.modalities),typeof r.temperature=="number"&&(i.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(i.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(i.tools=r.tools),i}function yt(t,n,e){let o={request_id:n,consumer_id:e,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(o.model=t.model),t.tools!==void 0&&(o.tools=t.tools),t.tool_choice!==void 0&&(o.tool_choice=t.tool_choice),typeof t.temperature=="number"&&(o.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(o.max_output_tokens=t.max_output_tokens),typeof t.top_p=="number"&&(o.top_p=t.top_p),Array.isArray(t.stop)&&t.stop.length>0&&(o.stop=t.stop),typeof t.reasoning_effort=="string"&&(o.reasoning_effort=t.reasoning_effort),t.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=t.chat_template_kwargs),o}function wt(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 n=t,e=n.body??{};return{type:"error",error:{type:"urun_error",code:n.code??null,message:e.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var bn="llm-resp";async function*He(t,n){let e=`${bn}:${n}`,o=`resp_${n}`;yield{type:"response.created",response:{id:o,status:"in_progress"}};let r=new Map;for await(let i of t.stream(e).messages()){let s=i;if(s.t==="delta"){if(typeof s.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:s.delta}),typeof s.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:s.reasoning}),Array.isArray(s.tool_calls))for(let a of s.tool_calls){let u=typeof a.index=="number"?a.index:0,c=r.get(u)??{};a.id&&(c.id=a.id),a.function?.name&&(c.name=a.function.name),r.set(u,c),yield{type:"response.function_call_arguments.delta",item_id:`fc_${n}_${u}`,tool_index:u,call_id:c.id,name:c.name,delta:a.function?.arguments??""}}}else if(s.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...s.body}};return}else if(s.t==="error"){yield wt(s);return}}}var Sn="llm",xe=class{constructor(n){this.session=n;this.sessionTag=n.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(n){n.session_tag=this.sessionTag,this.session.doc(Sn).set({requests:{[n.request_id]:{payload:n,consumer_id:n.consumer_id,stream:n.stream}}})}sendResponses(n,e){let o=yt(n,e,this.consumerId);return this.write(o),He(this.session,e)}sendResponseCreate(n,e,o){let r=ht(n,e,o,this.consumerId);return this.write(r),He(this.session,o)}};var _t=0;function Rn(){return _t+=1,`req_${Date.now().toString(36)}_${_t.toString(36)}`}var be=class{transport;constructor(n){this.transport=new xe(n)}responses={create:async n=>{let e=Rn(),o=this.transport.sendResponses(n,e);return Object.assign((async function*(){yield*o})(),{requestId:e})}}};function An(t){let n=t?.type;return n==="response.created"||n==="response.in_progress"}function En(t){let n=t?.type;return n==="response.completed"||n==="error"}function vt(t){return async function(e){return(async function*(){for(let r=1;r<=2;r++){let{app:i,entry:s}=await t.sessionFor(e.model),a=!1,u=!1;try{let c=await t.createStream(s,e);for await(let p of c){if(En(p)&&(a=!0),An(p)){if(r>1)continue}else u=!0;yield p}}catch(c){if(r<2&&!u){await t.evict(i,s);continue}throw c}if(a)return;if(r<2&&!u){await t.evict(i,s);continue}return}})()}}var On=3,In="llm",Tn=new Set(["paused","error"]);function kt(t,n){let e=t.doc(In),o=typeof e.onConnectionState=="function",r=typeof t.onPhase=="function";if(!o&&!r)throw new Error(`session for app "${n}" 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,s=new Set,a=[],u=c=>{if(!i){i=c;for(let p of[...s])p(c);s.clear()}};return o&&a.push(e.onConnectionState(c=>{c.consecutiveFailures<On||u(new H(`the pooled session for app "${n}" 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.`))})),r&&a.push(t.onPhase(c=>{Tn.has(c.name)&&u(new H(`the pooled session for app "${n}" 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),()=>{}):(s.add(c),()=>s.delete(c))},dispose(){s.clear();for(let c of a.splice(0))c()}}}async function*Be(t,n){let e=n.gone();if(e)throw e;let o=t[Symbol.asyncIterator](),r,i=new Promise((s,a)=>{r=n.onGone(u=>a(u))});i.catch(()=>{});try{for(;;){let s=await Promise.race([o.next(),i]);if(s.done)return;yield s.value}}finally{r?.(),o.return?.(void 0)}}function xt(t,n,e){let o=t[e];if(typeof o!="function")throw new Error(`app "${n}" has no function "${e}" (set URUN_FUNCTION)`);let r=o();if(typeof r.end!="function")throw new Error(`app "${n}" function "${e}" returned a session without end()`);return r}function Cn(t,n){let{baseUrl:e,orgId:o,fnName:r,auth:i,subject:s}=t,a=f=>({session:f,responses:new be(f),gone:kt(f,n)});if(i.lane==="jwt"){let f=(0,le.App)(n,{baseUrl:e,orgId:o,jwt:i.jwt});return a(xt(f,n,r))}let{apiKey:u,gatewayUrl:c}=i,p=(0,le.App)(n,{baseUrl:e,orgId:o,getAccessToken:async()=>(await(0,le.createClientToken)(u,{baseUrl:c,expiresIn:300,allowedFunctions:[`${n}/${r}`],...s===void 0?{}:{subject:s}})).token});return a(xt(p,n,r))}function Pn(t){let n=t.session.id;if(typeof n!="string"||n.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 n}var Un=new Set(["error","paused"]);function bt(t){let{auth:n,catalog:e}=t,o=null,r=s=>{let a=Cn(t,s);return a.gone.onGone(()=>{o?.evict(s,a)}),a},i=new me({defaultApp:t.defaultApp,fnName:t.fnName,openSession:r,closeSession:async s=>{s.gone.dispose(),await s.session.end()},listApps:n.lane==="api-key"?()=>ot({apiUrl:t.apiUrl,apiKey:n.apiKey}):null,listCatalog:e?()=>gt(e):null,sessionKey:Pn});return o=i,t.defaultApp!==null&&i.seed(t.defaultApp,r(t.defaultApp)),i}function St(t,n=ut){let e=new WeakMap,o=new WeakMap,r=new WeakMap;return{createResponse:vt({sessionFor:i=>t.sessionFor(i),evict:(i,s)=>t.evict(i,s),createStream:async(i,s)=>Be(await i.responses.responses.create(s),i.gone)}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),openAudio:async i=>{let{entry:s}=await t.sessionFor(i),a=e.get(s);return a||(a=(async()=>it(s.session,await n()))(),e.set(s,a),a.catch(()=>e.delete(s))),a},openVideo:async i=>{let{entry:s}=await t.sessionFor(i),a=o.get(s);return a||(a=at(s.session),o.set(s,a)),a},openVideoOut:async i=>{let{entry:s}=await t.sessionFor(i),a=r.get(s);return a||(a=ct(s.session),r.set(s,a)),a},sessionHandle:async i=>(await t.handleFor(i)).handle,createResponseOn:async(i,s)=>{let{entry:a}=await t.sessionForHandle(i);return Be(await a.responses.responses.create(s),a.gone)},onSessionEnd:async(i,s)=>{let{entry:a}=await t.sessionForHandle(i),u=a.session;if(typeof u.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let c=!1;return u.onPhase(p=>{if(c||!Un.has(p.name))return;c=!0;let f=u.endsAt??null;s({timeLeftMs:f?Math.max(0,f.getTime()-Date.now()):null,reason:p.reason??`session ${p.name}`})})}}}var Nn=fe(require("os"),1),$n=fe(require("path"),1),Ln=require("url"),Mn=require("util");function Rt(t,n="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`${n} 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 Se(t,n="URUN_GATEWAY_URL"){let e=new URL(t),o=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!o)throw new Error(`${n} must be https (got ${t}) \u2014 the org API key rides the request's Authorization header`);return t}var Fe=8080,Re="serve",At="0.0.0.0";function Dn(t,n,e){let o=(t[n]??"").trim();if(!o)throw new Error(`${n} is not set \u2014 ${e}`);return o}function Et(t=process.env){let n=(t.PORT??"").trim(),e=n===""?Fe:Number(n);if(!Number.isInteger(e)||e<0||e>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(n)}`);let o=Rt(Se(Dn(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")),r=(t.URUN_API_URL??"").trim(),i=r?Se(r,"URUN_API_URL"):`${o.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!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 u=s?{catalogUrl:Se(s,"URUN_CATALOG_URL"),anonKey:a}:null;return{port:e,baseUrl:o,apiUrl:i,catalog:u}}var je=512;function Ge(t){return`urun-inference-proxy-${(0,Ot.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var ne=class{constructor(n){this.opts=n}opts;tenants=new Map;build(n){if(this.opts.build)return this.opts.build(n);let e=bt({baseUrl:this.opts.baseUrl,orgId:n.orgId,defaultApp:null,fnName:Re,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:n.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:Ge(n.apiKey)});return{router:e,clients:St(e)}}clientsFor(n){let e=this.tenants.get(n.apiKey);if(e)return this.tenants.delete(n.apiKey),this.tenants.set(n.apiKey,e),e.clients;for(;this.tenants.size>=je;){let r=this.tenants.entries().next();if(r.done)break;let[i,s]=r.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let o=this.build(n);return this.tenants.set(n.apiKey,o),o.clients}get size(){return this.tenants.size}async closeAll(){let n=[...this.tenants.values()].map(o=>o.router);this.tenants.clear();let e=[];if(await Promise.all(n.map(async o=>{try{await o.closeAll()}catch(r){e.push(String(r instanceof Error?r.message:r))}})),e.length>0)throw new Error(`failed to close ${e.length} tenant backhaul(s): ${e.join("; ")}`)}};var Je=5e3,We=3e3,Vn="/api/client-tokens";function qe(t,n,e){t.writeHead(n,{"content-type":"application/json"}),t.end(JSON.stringify(e))}function It(t,n,e,o){qe(t,n,{error:{message:e,type:o}})}async function Hn(t,n=fetch){let e=`${t.replace(/\/+$/,"")}${Vn}`;try{let o=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(We)});return o.status===404?{ready:!1,detail:`${e} answered 404 \u2014 this is not a uRun control plane`}:o.status>=500?{ready:!1,detail:`${e} answered HTTP ${o.status}`}:{ready:!0,detail:`${e} answered HTTP ${o.status}`}}catch(o){return{ready:!1,detail:`${e} unreachable: ${o instanceof Error?o.message:String(o)}`}}}function Ct(t){let n=t.resolver??new te({gatewayUrl:t.baseUrl}),e=t.registry??new ne({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),o=t.probeControlPlane??(()=>Hn(t.baseUrl)),r=async u=>n.resolve(ke(u.headers.authorization)),i=mt({clients:async u=>e.clientsFor(await r(u)),statusOf:u=>u instanceof F?{status:u.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:u instanceof W?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null}),s=null;return{server:(0,Tt.createServer)((u,c)=>{let p=new URL(u.url??"/","http://localhost");(async()=>{if(u.method==="GET"&&p.pathname==="/healthz"){qe(c,200,{ok:!0});return}if(u.method==="GET"&&p.pathname==="/readyz"){let f=Date.now();if(!s||f-s.at>=Je){let m=await o();s={at:f,...m}}qe(c,s.ready?200:503,{ok:s.ready,control_plane:s.detail});return}if(p.pathname!=="/v1"&&!p.pathname.startsWith("/v1/")){It(c,404,`no route for ${u.method} ${p.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface plus /healthz and /readyz`,"invalid_request_error");return}i(u,c)})().catch(f=>{if(!c.headersSent){It(c,500,String(f instanceof Error?f.message:f),"proxy_error");return}c.end()})}),closeAll:()=>e.closeAll()}}0&&(module.exports={BIND_HOST,ControlPlaneUnavailableError,DEFAULT_PORT,MAX_CACHED_KEYS,MAX_TENANTS,ORG_BINDING_TTL_MS,OrgResolver,ProxyAuthError,READINESS_TIMEOUT_MS,READINESS_TTL_MS,SERVE_FUNCTION,TenantRegistry,bearerFrom,createHostedProxy,resolveHostedConfig,tenantSubject});
|
|
56
|
+
`)),l.end()})}}var Wt=(t,e)=>Object.assign(new Error(e),{status:t});function ps(t){let n=new URL(t.url??"/","http://localhost").searchParams.get("model")?.trim();return n===""?void 0:n}async function fs(t,e){if(!t.supportsAudio)throw Wt(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 n;try{n=await t.supportsAudio(e)}catch(s){throw s instanceof B?Wt(404,s.message):s}if(!n)throw Wt(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (catalog task is neither stt nor tts) \u2014 this realtime lane serves only audio-task models; chat models ride /v1/chat/completions`);if(!t.openAudio)throw Wt(501,"an audio-capable model needs a router-backed client (openAudio) to open its native session audio bridge \u2014 refusing loudly rather than binding a voiceless session");let r={audio:await t.openAudio(e)},o={clients:t,voice:n,audioSession:r};return e!==void 0&&(o.model=e),o}var G=require("@prometheus-io/client"),ms=require("http");var gs=9464,Jt="/metrics",Me="(other)",Mn="(none)",Dn=64,Bn=128,tu=["/v1/responses","/v1/chat/completions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits",Bt,ut],nu=new Set(tu);function Fn(t){return nu.has(t)?t:Me}function jn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var De=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Mn:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,Me):(this.admitted.add(e),e):Me}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},Be=class{registry=new G.Registry;modelLabel=new De(Dn);orgLabel=new De(Bn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new G.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 G.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 G.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 G.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 G.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 G.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]}),this.ledgerQueue=new G.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"},ts()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ns()/1e3)}}),this.labelCardinality=new G.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 G.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]}),e.defaultMetrics!==!1&&(0,G.collectDefaultMetrics)({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=Fn(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 u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?Me:e.method,status_class:jn(e.status),stream:u,model:s,org:i}),this.duration.observe({lane:n,stream:u,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 Kt(t){return(0,ms.createServer)((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Jt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Jt}
|
|
57
|
+
`);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)}
|
|
58
|
+
`);return}n.end()})})}var qn=require("crypto"),hs=require("http"),ys=9465,Hn="x-urun-key-id",Gn="x-urun-key-fingerprint",Vn="urun-ratelimit-bucket:",Wn="urun-ratelimit-tier:",zt="anonymous",ru=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Jn(t){return(0,qn.createHash)("sha256").update(`${Vn}${t}`).digest("hex")}function Kn(t){return(0,qn.createHash)("sha256").update(`${Wn}${t}`).digest("hex")}function zn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return ru.test(n)?n:null}function Yt(){return(0,hs.createServer)((t,e)=>{let n=zn(t.headers.authorization);e.setHeader(Hn,n===null?zt:Jn(n)),e.setHeader(Gn,n===null?zt:Kn(n)),e.writeHead(200),e.end()})}var Xt=require("@urun-sh/core"),z=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},ge=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function Se(t){let e=(t??"").trim();if(e==="")throw new z("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 z("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var ou=60,Yn=6e4,Xn=4096;function su(t){return t===401||t===403}var Fe=class{constructor(e){this.opts=e;this.mint=e.mint??Xt.createClientToken,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new z("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Yn)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:ou})).orgId}catch(o){throw o instanceof Xt.ClientTokenError&&su(o.status)?(this.cache.delete(e),new z("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new ge(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new ge("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=Xn){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};var en=require("crypto");var mt=require("@urun-sh/core");async function _s(t){let n=await(t.fetchImpl??fetch)(`${t.catalogUrl}/model_catalog?select=model_id,variant,gpu_spec,engine,task,description,size_gb,hf_repo,engine_args,updated_at`,{headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`}});if(!n.ok)throw new Error(`model_catalog fetch failed: ${n.status}`);return await n.json()}function ws(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 vs(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),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),r}function bs(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 iu="llm-resp";async function*Qn(t,e){let n=`${iu}:${e}`,r=`resp_${e}`;yield{type:"response.created",response:{id:r,status:"in_progress"}};let o=new Map;for await(let s of t.stream(n).messages()){let i=s;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:r,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:r,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let a of i.tool_calls){let u=typeof a.index=="number"?a.index:0,d=o.get(u)??{};a.id&&(d.id=a.id),a.function?.name&&(d.name=a.function.name),o.set(u,d),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${u}`,tool_index:u,call_id:d.id,name:d.name,delta:a.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:r,status:"completed",...i.body}};return}else if(i.t==="error"){yield bs(i);return}}}var au="llm",Qt=class{constructor(e){this.session=e;this.sessionTag=e.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(e){e.session_tag=this.sessionTag,this.session.doc(au).set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,n){let r=vs(e,n,this.consumerId);return this.write(r),Qn(this.session,n)}sendResponseCreate(e,n,r){let o=ws(e,n,r,this.consumerId);return this.write(o),Qn(this.session,r)}};var ks=0;function uu(){return ks+=1,`req_${Date.now().toString(36)}_${ks.toString(36)}`}var Zt=class{transport;constructor(e){this.transport=new Qt(e)}responses={create:async e=>{let n=uu(),r=this.transport.sendResponses(e,n);return Object.assign((async function*(){yield*r})(),{requestId:n})}}};var xs=require("@urun-sh/core"),Zn=2;function du(t){let e=t?.type;return e==="response.created"||e==="response.in_progress"}function lu(t){let e=t?.type;return e==="response.completed"||e==="error"}function Rs(t){return async function(n,r){return(async function*(){for(let s=1;s<=Zn;s++){let{app:i,entry:a,identity:u}=await t.sessionFor(n.model);r?.({sessionId:t.sessionIdOf?.(a)??null,identity:u});let d=!1,l=!1;try{let c=await t.createStream(a,n);for await(let m of c){if(lu(m)&&(d=!0),du(m)){if(s>1)continue}else l=!0;yield m}}catch(c){if(c instanceof xs.SessionFailedError&&(c.kind==="never-live"||c.kind==="create-failed"))throw c;if(s<Zn&&!l){await t.evict(i,a);continue}throw c}if(d)return;if(s<Zn&&!l){await t.evict(i,a);continue}return}})()}}var cu=3,pu="llm",fu=new Set(["paused","error"]);function Ss(t,e){let n=t.doc(pu),r=typeof n.onConnectionState=="function",o=typeof t.onPhase=="function";if(!r&&!o)throw new Error(`session for app "${e}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let s=null,i=!1,a=new Set,u=[],d=l=>{if(!s){s=l;for(let c of[...a])c(l);a.clear()}};return r&&u.push(n.onConnectionState(l=>{i&&(l.consecutiveFailures<cu||d(new V(`the pooled session for app "${e}" is gone: its doc backhaul failed ${l.consecutiveFailures} consecutive times (last close ${l.lastCloseCode===null?"by provider liveness reap":`code ${l.lastCloseCode}`}${l.lastCloseReason?`, reason ${JSON.stringify(l.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),o&&u.push(t.onPhase(l=>{if(l.name==="live"){i=!0;return}i&&fu.has(l.name)&&d(new V(`the pooled session for app "${e}" lost its compute binding (phase "${l.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>s,onGone(l){return s?(l(s),()=>{}):(a.add(l),()=>a.delete(l))},dispose(){a.clear();for(let l of u.splice(0))l()}}}async function*er(t,e){let n=e.gone();if(n)throw n;let r=t[Symbol.asyncIterator](),o,s=new Promise((i,a)=>{o=e.onGone(u=>a(u))});s.catch(()=>{});try{for(;;){let i=await Promise.race([r.next(),s]);if(i.done)return;yield i.value}}finally{o?.(),r.return?.(void 0)}}function Es(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){let{baseUrl:n,orgId:r,auth:o,subject:s}=t,i=e.fnName??t.fnName,a=Ye(e),u=t.sessionStartOptions?.(a),d=e.sharedApp?{sharedApp:!0,...u}:u,l=v=>({session:v,responses:new Zt(v),gone:Ss(v,a)});if(o.lane==="jwt"){let v=(0,mt.App)(e.appSlug,{baseUrl:n,orgId:r,jwt:o.jwt});return l(Es(v,e.appSlug,i,d))}let{apiKey:c,gatewayUrl:m}=o,p=(0,mt.App)(e.appSlug,{baseUrl:n,orgId:r,getAccessToken:async()=>(await(0,mt.createClientToken)(c,{baseUrl:m,expiresIn:300,allowedFunctions:[`${e.appSlug}/${i}`],...s===void 0?{}:{subject:s},...e.sharedApp?{sharedApp:!0}:{}})).token});return l(Es(p,e.appSlug,i,d))}function gu(t){let e=t.session.id;if(typeof e!="string"||e.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return e}var hu=new Set(["error","paused"]);function nr(t){let{auth:e,catalog:n}=t,r=null,o=i=>{let a=Ye(i),u=mu(t,i);return t.onSessionOpen&&typeof u.session.id=="string"&&u.session.id!==""&&t.onSessionOpen(a,u.session.id),u.gone.onGone(()=>{r?.evict(a,u)}),u},s=new At({defaultApp:t.defaultApp,fnName:t.fnName,openSession:o,closeSession:async i=>{if(i.gone.dispose(),t.release==="detach"){if(typeof i.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');i.session.detach();return}await i.session.end()},listApps:e.lane==="api-key"?()=>ao({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,listCatalog:n?()=>_s(n):null,listPrices:n?()=>zr(n):null,shared:e.lane==="api-key"?()=>Gr({apiUrl:t.apiUrl,apiKey:e.apiKey}):null,sessionKey:gu});return r=s,t.defaultApp!==null&&s.seed(t.defaultApp,o({appSlug:t.defaultApp})),s}async function tr(t){let e=t.whenLive;if(typeof e!="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 e.call(t)}function rr(t,e=xr){let n=new WeakMap,r=new WeakMap,o=new WeakMap;return{createResponse:Rs({sessionFor:s=>t.sessionFor(s),sessionIdOf:s=>{let i=s.session.id;return typeof i=="string"&&i.length>0?i:null},evict:(s,i)=>t.evict(s,i),createStream:async(s,i)=>(await tr(s.session),er(await s.responses.responses.create(i),s.gone))}),listModels:()=>t.modelList(),openRouterModels:()=>t.openRouterModels(),supportsImages:(s,i)=>t.supportsImages(s,i),listImageModels:()=>t.imageModelList(),catalogIdentity:s=>t.catalogIdentityFor(s),servingAppSlug:async s=>await t.servingAppSlugFor(s),supportsAudio:s=>t.supportsAudio(s),openAudio:async s=>{let{entry:i}=await t.sessionFor(s),a=n.get(i);return a||(a=(async()=>(await tr(i.session),br(i.session,await e())))(),n.set(i,a),a.catch(()=>n.delete(i))),a},openVideo:async s=>{let{entry:i}=await t.sessionFor(s),a=r.get(i);return a||(a=kr(i.session),r.set(i,a)),a},openVideoOut:async s=>{let{entry:i}=await t.sessionFor(s),a=o.get(i);return a||(a=Sr(i.session),o.set(i,a)),a},sessionHandle:async s=>(await t.handleFor(s)).handle,createResponseOn:async(s,i)=>{let{entry:a}=await t.sessionForHandle(s);return await tr(a.session),er(await a.responses.responses.create(i),a.gone)},onSessionEnd:async(s,i)=>{let{entry:a}=await t.sessionForHandle(s),u=a.session;if(typeof u.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let d=!1;return u.onPhase(l=>{if(d||!hu.has(l.name))return;d=!0;let c=u.endsAt??null;i({timeLeftMs:c?Math.max(0,c.getTime()-Date.now()):null,reason:l.reason??`session ${l.name}`})})}}}var or=8080,gt="serve",As="0.0.0.0";function yu(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Is(t=process.env){let e=(t.PORT??"").trim(),n=e===""?or: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=To(Ut(yu(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?Ut(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 u=i?{catalogUrl:Ut(i,"URUN_CATALOG_URL"),anonKey:a}:null;return{port:n,baseUrl:r,apiUrl:s,catalog:u}}var sr=512;function Ge(t){return`urun-inference-proxy-${(0,en.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}var je=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let r=this.opts.build(e);return{router:r.router,clients:this.label(r.clients,e)}}let n=nr({baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:gt,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,subject:Ge(e.apiKey),release:"detach"});return{router:n,clients:this.label(rr(n),e)}}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>=sr;){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}async closeAll(){let e=[...this.tenants.values()].map(r=>r.router);this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r.closeAll()}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},tn=512,ir=1024,qe=class extends Error{constructor(){super(`conversation capacity reached (${tn} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function _u(t,e,n,r){let o=nr({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:gt,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",sessionStartOptions:s=>{let i=r.get(s);return i===void 0?void 0:{sessionId:i}},onSessionOpen:(s,i)=>{r.set(s,i)}});return{clients:rr(o),release:async()=>{await o.closeAll()}}}var He=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Ge(e.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(e,r):_u(this.opts,e,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(e,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=tn;){let e=this.byCaller.keys().next();if(e.done)throw new qe;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 qe;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){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,(0,en.randomUUID)())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===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 a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),createResponseOn:(i,a)=>o().backhaul.clients.createResponseOn(i,a),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async i=>{let a=o().backhaul.clients.openAudio;if(a===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return a(i)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=ir;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),u=a===void 0?void 0:this.byCaller.get(a.apiKey),d=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||d===void 0||a.apiKey!==e.apiKey)throw new V("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 n=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.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 nn="/inference-usage",Os=25e3;var wu=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ts(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=wu.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 rn=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${nn}`,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(Os)})}catch(i){throw new U(`the uRun usage surface (POST ${nn}) could not be reached within ${Os}ms: ${Ts(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new z("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 U(`the uRun usage surface (POST ${nn}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new U(`the uRun usage surface (POST ${nn}) answered HTTP ${o.status} with a body that is not JSON: ${Ts(i)}`)}return Xo(s,this.opts.onRejectedRow)}};var lr="/inference-ledger",cr=1e4,Ve=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},ur=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},q=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},dr=class extends z{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},vu=[["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",Cs],["cost_nano_usd",Cs],["price_version",t=>t===null||typeof t=="string"]];function bu(t){for(let[e,n]of vu){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function ku(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"}:bu(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Cs(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ar(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Ps(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 xu(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&&Ps(t.started_at,n.started_at)&&Ps(t.completed_at,n.completed_at)&&ar(t.prompt_tokens,n.prompt_tokens)&&ar(t.completion_tokens,n.completion_tokens)&&ar(t.output_units,n.output_units)}function pr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new q(`${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 q(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new q(`${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 q(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=d=>{if(!(d in n))throw new q(`${e} answered a row with no ${d} field: ${JSON.stringify(t)}`);let l=n[d];if(l===null)return null;if(typeof l!="string")throw new q(`${e} answered a non-string ${d}: ${JSON.stringify(l)}`);if(!/[^\s]/.test(l))throw new q(`${e} answered a BLANK ${d} (${JSON.stringify(l)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return l},i=s("price_version"),a=s("unpriced_reason"),u=o!=null;if(u&&(i===null||a!==null))throw new q(`${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(!u&&(i!==null||a===null))throw new q(`${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 We=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${lr}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(n),signal:AbortSignal.timeout(cr)})}catch(u){throw new q(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(o.status===409){let u=await o.text().catch(()=>""),d=ku(u);throw d.status==="found"&&xu(n,d.row)?new ur(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 Ve(`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 Ve(`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(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new dr("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(!o.ok){let u=await o.text().catch(d=>`<body unreadable: ${d instanceof Error?d.message:String(d)}>`);throw new q(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${u.slice(0,400)}`)}let s;try{s=await o.json()}catch(u){throw new q(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let i=s?.recorded;if(i===void 0)throw new q(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let a=pr(i,`the uRun ledger surface at ${r}`);if(a.inference_id!==n.inference_id)throw new q(`the uRun ledger surface at ${r} answered for inference_id ${a.inference_id} when asked about ${n.inference_id}`);return a}};var mr=5e3,gr=3e3,Ru="/api/client-tokens";function fr(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function $s(t,e,n,r){fr(t,e,{error:{message:n,type:r}})}async function Su(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Ru}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(gr)});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 Ns(t){let e=t.resolver??new Fe({gatewayUrl:t.baseUrl}),n=t.registry??new je({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>Su(t.baseUrl)),o=t.usageClient??new rn({apiUrl:t.apiUrl}),s=t.ledgerClient??new We({apiUrl:t.apiUrl}),i=new Be(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),a=async h=>e.resolve(Se(h.headers.authorization)),u=h=>h instanceof z?{status:h.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:h instanceof ge?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,d=cs({clients:async h=>n.clientsFor(await a(h)),usage:{authorize:h=>Se(h.headers.authorization),lookup:(h,f)=>o.lookup(h,f)},statusOf:u,...t.requestLog?{requestLog:t.requestLog}:{},observe:h=>i.observe(h),ledger:{write:(h,f)=>s.write(Se(h.headers.authorization),f),observe:h=>i.observeLedger(h),...t.ledgerLog?{report:t.ledgerLog}:{}}}),l=null,c=(0,Ls.createServer)((h,f)=>{let g=new URL(h.url??"/","http://localhost");(async()=>{if(h.method==="GET"&&g.pathname==="/healthz"){fr(f,200,{ok:!0});return}if(h.method==="GET"&&g.pathname==="/readyz"){let A=Date.now();if(!l||A-l.at>=mr){let R=await r();l={at:A,...R}}fr(f,l.ready?200:503,{ok:l.ready,control_plane:l.detail});return}let w=g.pathname==="/v1"||g.pathname.startsWith("/v1/"),b=g.pathname.startsWith("/partners/");if(!w&&!b){$s(f,404,`no route for ${h.method} ${g.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 and /readyz`,"invalid_request_error");return}d(h,f)})().catch(w=>{if(!f.headersSent){$s(f,500,String(w instanceof Error?w.message:w),"proxy_error");return}f.end()})}),m=t.conversations??new He({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),p=[gn(c,{authenticate:async h=>{let f=await e.resolve(h),g=m.connectionFor(f);return{clients:g.clients,scope:Ge(f.apiKey),onBindResumeHandle:g.bindResumeHandle,clientsForResume:g.clientsForResume,release:g.release}}}),Rn(c,{clients:async h=>n.clientsFor(await a(h)),statusOf:u}).close,Nt(c,{resolver:{resolve:async h=>{let f=await e.resolve(Se(h.headers.authorization)),g=m.connectionFor(f),w;try{w=await fs(g.clients,ps(h))}catch(b){throw g.release().catch(()=>{}),b}return{...w,release:g.release}}}})];c.on("upgrade",(h,f)=>{let g=new URL(h.url??"/","http://localhost");g.pathname===bt||g.pathname===kn||g.pathname===st||f.destroyed||(f.write(`HTTP/1.1 404 Not Found\r
|
|
59
|
+
Connection: close\r
|
|
60
|
+
\r
|
|
61
|
+
no WS route for ${g.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),f.destroy())});let v=async()=>{for(let h of p)await h();await m.detachAll()};return{server:c,metricsServer:Kt(i),metrics:i,edgeIdentityServer:Yt(),closeAll:()=>n.closeAll(),closeWebSockets:v}}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});
|