@urun-sh/openai 0.6.43 → 0.6.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ResponsesClient-2EsjJUz1.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
- package/dist/{ResponsesClient-BIcQ6p6Z.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
- package/dist/chunk-64VO62LW.js +1 -0
- package/dist/chunk-7KRHHEKZ.js +1 -0
- package/dist/chunk-BA3NCMS5.js +6 -0
- package/dist/chunk-DMRZZTYI.js +4 -0
- package/dist/chunk-FNAZ2XBE.js +20 -0
- package/dist/chunk-G6AFKOVS.js +1 -0
- package/dist/{chunk-FF3RWDFM.js → chunk-HB5KNEY5.js} +1 -1
- package/dist/{chunk-ZCF6EV4Y.js → chunk-VQSCBUKT.js} +20 -19
- package/dist/{chunk-JMSVHETI.js → chunk-X5BLQXHK.js} +1 -1
- package/dist/chunk-XNRPTMSL.js +1 -0
- package/dist/chunk-Y774TOE7.js +2 -0
- package/dist/{composite-BoS9-74g.d.cts → composite-DM2sT1Sp.d.cts} +1 -1
- package/dist/{composite-D4_XPSas.d.ts → composite-DNNAm0PY.d.ts} +1 -1
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +4 -4
- package/dist/gemini-live.d.ts +4 -4
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +48 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +43 -42
- package/dist/hosted/index.d.cts +4 -4
- package/dist/hosted/index.d.ts +4 -4
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.d.cts +2 -2
- package/dist/pi-extension/index.d.ts +2 -2
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +41 -41
- package/dist/pooler/bin.cjs +25 -25
- package/dist/pooler/bin.js +24 -24
- package/dist/proxy/cli.cjs +48 -47
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +19 -18
- package/dist/proxy/index.d.cts +5 -5
- package/dist/proxy/index.d.ts +5 -5
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-PsmsZT62.d.cts → translator-C6MpaZS-.d.cts} +1 -1
- package/dist/{translator-BemK1Of5.d.ts → translator-CaOqL-V8.d.ts} +1 -1
- package/dist/{types-CxWQ84Ew.d.cts → types-DiYzfHYN.d.cts} +2 -5
- package/dist/{types-CxWQ84Ew.d.ts → types-DiYzfHYN.d.ts} +1 -1
- package/dist/{video-out-DPLqpGbQ.d.cts → video-out-A8qMuI36.d.cts} +1 -1
- package/dist/{video-out-DkMqKSOi.d.ts → video-out-IoTqIbAw.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-27HP3RMZ.js +0 -6
- package/dist/chunk-2NKCALKY.js +0 -22
- package/dist/chunk-2RO722HS.js +0 -2
- package/dist/chunk-7DUSLXPG.js +0 -1
- package/dist/chunk-BFIKVTQB.js +0 -1
- package/dist/chunk-GDH2D3S6.js +0 -1
- package/dist/chunk-MOX5FG2R.js +0 -1
- package/dist/chunk-YRBUHHI3.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as m}from"./chunk-YSFSRI3D.js";m();var M=24e3,v="audio",w=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),i=Math.floor(r.byteLength/2),a=new Int16Array(i);for(let s=0;s<i;s++)a[s]=r.readInt16LE(s*2);this.source.onData(a),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}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 i of this.outHandlers)i(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function N(t,e,n=1e4){try{return await I(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function I(t,e,n){let r=new w(e,{sampleRate:24e3}),i=await r.startOutbound(),a=t.stream(v);await a.attach(i),typeof a.emit=="function"&&r.setDataEmit(u=>a.emit(u));let s=await L(t,n);return await r.startInbound(s),r}function L(t,e){let n=t.stream(v);return n.track!=null?Promise.resolve(n.track):new Promise((r,i)=>{let a,s=setTimeout(()=>{a?.(),i(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=o=>{o!=null&&(clearTimeout(s),a?.(),r(o))};a=n.on?.("track",u),n.track!=null&&u(n.track)})}var b="rt-video-in",k=256e3;function q(t){let e=t.stream(b),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${b}') 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>k)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${k}-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 U=24e3,f=480,_=111,x=50,h=null;async function B(){if(h)return;let t=await import("opusscript");h=t.default??t}function P(){if(!h)throw new Error("[opus-guard] opusscript module not loaded");return new h(U,1,2048)}var g=class{constructor(e=P){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=x}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let i=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,i}catch(i){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${i instanceof Error?i.message:String(i)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function J(){let t=await import("werift");await B();let e=new g;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,i=Math.random()*65535&65535,a=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:n,onData:u=>{let o=new Int16Array(s.length+u.length);o.set(s,0),o.set(u,s.length);let d=0;for(;o.length-d>=f;){let c=o.subarray(d,d+f);d+=f;let l=Buffer.from(c.buffer,c.byteOffset,c.byteLength),y=e.encode(l,f);if(y===null){s=o.slice(d);break}i=i+1&65535,a=a+f>>>0;let A=new t.RtpHeader({version:2,payloadType:_,sequenceNumber:i,timestamp:a,ssrc:r,marker:!1}),R=new t.RtpPacket(A,y);n.writeRtp(R)}s=o.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(a=>{if(a.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${a.payload.length} B > 3828 B max`);return}let s;try{s=e.decode(a.payload)}catch(o){if(e.wedged)throw o;return}let u=new Int16Array(s.length/2);for(let o=0;o<u.length;o++)u[o]=s.readInt16LE(o*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function Y(){let t=await import("@roamhq/wrtc");return{createSource:()=>{let e=new t.nonstandard.RTCAudioSource;return{track:e.createTrack(),onData:r=>e.onData({samples:r,sampleRate:24e3})}},createSink:e=>{let n={onframe:null},r=new t.nonstandard.RTCAudioSink(e);return r.ondata=i=>{n.onframe?.(i)},n}}}m();import{WtControlDecoder as D,consumeWtDataStreams as F,encodeWtControlFrame as W,STREAM_END as $}from"@urun-sh/core";var p="rt-video-out",C="urun.videoOut.v1",E="h264";function O(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 z(t,e){if(O(t,"encodeVideoOutRecord"),e.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:t.seq,ptsUs:t.ptsUs,codec:t.codec,key:t.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let r=new Uint8Array(2+n.byteLength+e.byteLength);return r[0]=n.byteLength&255,r[1]=n.byteLength>>8,r.set(n,2),r.set(e,2+n.byteLength),r}function S(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(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}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 i=r;O(i,"decodeVideoOutRecord");let a=t.subarray(2+e);if(a.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:i,au:a.slice()}}async function K(t){let e=t.wtDataEndpoint;if(typeof e!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await e.call(t),r=n.sessionId??t.sessionId;if(typeof r!="string"||r.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:r,stream:p,codec:E,framing:C}}var X="urun.videoOut.v2-ws";function Z(t){let e=t.stream(p);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${p}') 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,i=new Set,a=o=>{for(let d of r)d(o)},s=!1,u=async()=>{for await(let o of e.messages()){if(!(o instanceof Uint8Array)){a(new Error(`openSessionVideoOutLane: "${p}" delivered a non-BINARY \xA75 payload (${typeof o}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=S(o)}catch(c){a(c instanceof Error?c:new Error(String(c)));continue}for(let c of n)c(d)}for(let o of i)o()};return{codec:E,onOutputFrame:o=>(n.add(o),s||(s=!0,u().catch(d=>a(d instanceof Error?d:new Error(String(d))))),()=>n.delete(o)),onLaneError:o=>(r.add(o),()=>r.delete(o)),onEnd:o=>(i.add(o),()=>i.delete(o))}}function H(t){if(t.length%2!==0||/[^0-9a-fA-F]/.test(t))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(t)})`);let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}async function ee(t,e,n){let r=n??(typeof globalThis.WebTransport=="function"?(d,c)=>new globalThis.WebTransport(d,c):void 0);if(!r)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let i=r(t.url,{serverCertificateHashes:t.certHashes.map(d=>({algorithm:"sha-256",value:H(d)}))});await i.ready;let a=await i.createBidirectionalStream();await a.writable.getWriter().write(W({t:"hello",token:t.token,sessionId:t.sessionId}));let s=a.readable.getReader(),u=new D,o=!1;for(;!o;){let{value:d,done:c}=await s.read();if(c)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let l of u.push(d)){if(l.t==="hello-ack"){o=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(l.t)} before hello-ack)`)}}await F(i.incomingUnidirectionalStreams,{onData:(d,c)=>{if(d===t.stream){if(c===$){e.onEnd?.();return}if(!(c instanceof Uint8Array)){e.onLaneError(new Error(`consumeVideoOut: "${t.stream}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{e.onFrame(S(c))}catch(l){e.onLaneError(l instanceof Error?l:new Error(String(l)))}}},onLaneError:d=>e.onLaneError(d)})}export{M as a,w as b,N as c,b as d,k as e,q as f,J as g,Y as h,p as i,C as j,E as k,z as l,S as m,K as n,X as o,Z as p,ee as q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as r}from"./chunk-YSFSRI3D.js";r();async function d(e,t,o){if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((i,s)=>{let u=e.onSynced(()=>{clearTimeout(n),i()});n=setTimeout(()=>{u(),s(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${o} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}export{d as a};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{h as m}from"./chunk-J3KCHTSA.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.44";var y=4141,A=g,M={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \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 e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
|
|
2
|
+
`)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of h)n[i]=a[i]}}var D=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&D.has(t)}function se(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function ae(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
3
|
+
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ue(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
4
|
+
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
|
5
|
+
`)}catch(o){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
|
|
6
|
+
`)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",t),e.proc.on("unhandledRejection",t),()=>{e.proc.off("uncaughtException",t),e.proc.off("unhandledRejection",t)}}function de(e,t){let n="pass --port 0 for an OS-assigned ephemeral port";return t?`port ${e} is held by another urun-openai proxy serving app ${t.app} (org ${t.org}, fn ${t.fn}, version ${t.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${n}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}c();var w=class extends Error{status=500;constructor(t){super(t),this.name="LaneTargetError"}},b=class extends Error{pool;constructor(t){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=t}};var U=class extends Error{pool;model;constructor(t,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=t,this.model=n}};export{w as a,b,U as c,M as d,O as e,F as f,H as g,V as h,X as i,z as j,Q as k,Z as l,ee as m,te as n,$ as o,f as p,ne as q,L as r,re as s,oe as t,ie as u,se as v,ae as w,ue as x,de as y};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as ne}from"./chunk-CAR4AEQJ.js";import{e as ue,f as B,g as pe,h as fe}from"./chunk-VQSCBUKT.js";import{c as Z,f as $,g as ee,p as oe}from"./chunk-64VO62LW.js";import{a as me,b as W}from"./chunk-MJSK6W3W.js";import{c as le}from"./chunk-BA3NCMS5.js";import{a as j}from"./chunk-HB5KNEY5.js";import{b as Y,d as U}from"./chunk-G6AFKOVS.js";import{b as te,c as se,d as re,g as ie,j as T,k as V,l as R,m as ae,p as H,q as I,r as ce,s as de}from"./chunk-J3KCHTSA.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as J,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as He,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as Be,SessionFailedError as K}from"@urun-sh/core";v();import{SessionFailedError as Ie}from"@urun-sh/core";var G=2;function _e(e){let o=e?.type;return o==="response.created"||o==="response.in_progress"}function Le(e){let o=e?.type;return o==="response.completed"||o==="error"}function ge(e){return async function(t,i){let a=await e.sessionFor(t.model);return(async function*(){for(let l=1;l<=G;l++){let{app:g,entry:y,identity:h}=l===1?a:await e.sessionFor(t.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:h});let d=!1,p=!1;try{let f=await e.createStream(y,t);for await(let m of f){if(Le(m)&&(d=!0),_e(m)){if(l>1)continue}else p=!0;yield m}}catch(f){if(f instanceof Ie&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,f)}catch{}throw f}if(l<G&&!p){await e.evict(g,y);continue}throw f}if(d)return;if(l<G&&!p){await e.evict(g,y);continue}return}})()}}import{randomUUID as ve}from"crypto";v();import{request as Te}from"http";var Re="/pooler/v1/inference",k=class extends Error{constructor(t,i,a,c){super(a);this.status=t;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Fe=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let o=e.messages?.find(t=>t.role==="system"||t.role==="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content)},Ne=e=>{let o=e.messages?.find(t=>t.role!=="system"&&t.role!=="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let t=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(t===void 0)return;if(typeof t=="string")return t;if(t!==null&&typeof t=="object"&&"content"in t){let i=t.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(t)}},we=e=>new Promise((o,t)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>o(Buffer.concat(i).toString("utf8"))),e.on("error",t)}),Me=async e=>{let o="pooler_error",t=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await we(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(o=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(t=a.message)}}catch{}return new k(e.status,o,t,e.retryAfterSeconds)};async function De(e,o,t,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Re}`),l=JSON.stringify({region:e.region,model:i,request_id:t,streaming:a,payload:o,affinity:{systemPrompt:Fe(o),firstMessage:Ne(o)}});return new Promise((g,y)=>{let h=Te({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},d=>{let p=Number(d.headers["retry-after"]??"");g({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(p)?p:void 0,body:d})});h.on("error",d=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),h.end(l)})}var ye=e=>{if(!e.startsWith("data: "))return null;let o=e.slice(6).trim();if(o===""||o==="[DONE]")return null;let t;try{t=JSON.parse(o)}catch{return null}if(t===null||typeof t!="object")return null;let i=t;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*xe(e){let o="";for await(let i of e.body)for(o+=String(i);;){let a=o.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);if(a===-1)break;let c=o.slice(0,a);o=o.slice(a+2);let l=ye(c);l!==null&&(yield l)}let t=ye(o);t!==null&&(yield t)}async function on(e,o,t,i){let a=Y(o,t,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await De(e,a,t,c,o.stream===!0);if(l.status>=400)throw await Me(l);let g=o.stream===!0?U(t,xe(l)):await Ce(l,t);return(async function*(){yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}},yield*g})()}async function Ce(e,o){let t=await we(e.body),i=null;try{let c=JSON.parse(t);c!==null&&typeof c=="object"&&(i=c)}catch{i=null}if(i===null)throw new k(502,"pooler_bad_body","the pooler answered a non-object body");let a=i;return U(o,(async function*(){yield a})())}v();import{encodeStreamEnvelope as he}from"@urun-sh/core";var Ue="audio";function Se(e){let o=e.streamEndpoint(Ue);return{sessionId:e.id,appendInputAudio(t,i){let a=Buffer.from(t,"base64");if(a.byteLength!==0){if(i===void 0){o.send(he(new Uint8Array(a)));return}o.send(he({pcm16:t,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}v();import{encodeStreamEnvelope as $e}from"@urun-sh/core";var je="rt-video-in";function Pe(e){let o=e.streamEndpoint(je);return{sendInputFrame:async t=>{o.send($e(t))}}}var We=0,Ge=4,Je=4;function Tn(e,o){let t=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let h=Number.parseInt(y,10);if(!Number.isInteger(h)||h<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return h},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):We;if(!Number.isInteger(a)||a<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=t("URUN_DECISION_POOL_MAX",Math.max(a,Ge));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:t("URUN_DECISION_POOL_INFLIGHT_CAP",Je),replicaId:(e.URUN_REPLICA_ID??"").trim()||o||"proxy"}}function Rn(e){let o=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!o)return B;let t=Number.parseInt(o,10);if(!Number.isInteger(t)||t<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return t*1e3}function q(e,o,t,i){let a=e[t];if(typeof a!="function")throw new Error(`app "${o}" has no function "${t}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${o}" function "${t}" returned a session without end()`);return c}function Ae(e,o,t,i){let{baseUrl:a,orgId:c,auth:l}=e,g=o.fnName??e.fnName,y=e.sessionStartOptions?.(t),h=i||y||o.sharedApp?{...o.sharedApp?{sharedApp:!0}:{},...y,...i}:void 0,d=w=>({session:w,responses:new j(w),gone:me(w,t)});if(l.lane==="jwt"){let w=J(o.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return d(q(w,o.appSlug,g,h))}if(l.lane==="machine"||l.lane==="user"){let w=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:x}=l,_=(typeof e.subject=="function"?e.subject():e.subject)??ve(),L=J(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(w,{baseUrl:x,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:_,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(q(L,o.appSlug,g,h))}let{apiKey:p,gatewayUrl:f}=l,m=(typeof e.subject=="function"?e.subject():e.subject)??ve(),S=J(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(p,{baseUrl:f,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:m,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(q(S,o.appSlug,g,h))}function ke(e){let o=e.session.id;if(typeof o!="string"||o.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 o}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let o=e.status.error?.httpStatus,t=e.status.error?.code;return o===410||o===409&&(t==="cancelled"||t==="expired")?!0:t==="client_ended"}var qe=new Set(["error","paused"]);function Fn(e){let{auth:o,catalog:t}=e,i=null,a=(l,g)=>{let y=Ae(e,l,g);return e.onSessionOpen&&typeof y.session.id=="string"&&y.session.id!==""&&e.onSessionOpen(g,y.session.id),y.gone.onGone(()=>{i?.evict(g,y)}),y},c=new de({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:a,closeSession:async l=>{if(l.gone.dispose(),l.audioDispose?.(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:o.lane==="api-key"?()=>ae({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,listCatalog:e.catalogRows??(t?()=>ne(t):null),listPrices:t?()=>re(t):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return te(l)}:o.lane==="api-key"?()=>se({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,sessionKey:ke});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},I({appSlug:e.defaultApp}))),c}function Nn(e,o){let t=e.decisionPool;if(!t)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=t.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
4
|
+
`)},y=(d,p)=>{let f=a.get(p);if(f)return f;let m=new ue({min:t.min,max:t.max,idleGraceMs:t.idleGraceMs,inFlightCap:t.inFlightCap,replicaId:i,openSlot:async S=>{let w=Ae(e,d,p,{concurrencyKey:S.concurrencyKey});return w.gone.onGone(()=>m.markSessionDead(w)),await D(w.session),g(`slot attached pool=${p} slot=${S.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async S=>{S.gone.dispose(),S.audioDispose?.(),await S.session.end()},onDetach:(S,w)=>g(`slot detached pool=${p} slot=${S.concurrencyKey} reason=${w}`),terminalOpenFailure:S=>S instanceof K&&X(S)});return c.set(p,{target:d,env:t}),a.set(p,m),m},h=async(d,p)=>{let f=c.get(p);if(f)try{let m=await o.poolTuningFor(d);y(d,p).retune({min:m?.min??f.env.min,max:m?.max??f.env.max,inFlightCap:m?.in_flight_cap??f.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){g(`pool tuning refresh failed pool=${p} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let d={appSlug:e.defaultApp};await y(d,I(d)).boot()},async sessionFor(d){let p=await o.resolveTargetFor(d),f=I(p),m=y(p,f);await h(p,f);let S=await m.acquire({timeoutMs:m.requestWaitMs}),w=l.get(S.entry)??[];return w.push(S),l.set(S.entry,w),{app:f,entry:S.entry,identity:ce(p)}},async warmFor(d){let p=await o.resolveTargetFor(d);await y(p,I(p)).boot()},end(d){let p=l.get(d)?.shift();p&&(l.get(d)?.length===0&&l.delete(d),p.release())},evict(d){for(let p of a.values())p.evict(d)},markSessionDead(d){for(let p of a.values())p.markSessionDead(d)},reap(){for(let[d,{target:p}]of c)h(p,d).then(()=>{let f=a.get(d);f&&f.reap()})},async pingReady(d){for(let p of a.values())if(await p.pingReady(d))return!0;return!1},stats(){return[...a.entries()].map(([d,p])=>({poolKey:d,...p.stats()}))},async drain(d){await Promise.all([...a.values()].map(p=>p.drain({timeoutMs:d})))},async close(){await Promise.all([...a.values()].map(d=>d.close()))}}}function Ke(e){return Be(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:He:be}async function D(e,o){let t=e.whenLive;if(typeof t!="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 t.call(e,{timeout:Ke(e.phase),signal:o})}async function Xe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}async function Oe(e){let o=e.phase?.name;if(o==="live"||o==="paused"){if(typeof e.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");e.detach();return}if(typeof e.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await e.end()}function M(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Mn(e,o=ee,t,i,a=B,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,h=new WeakMap,d=new WeakMap,p=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},f="lane",m=n=>{let s=R(n);if(!c||!s||s.app!==f)return null;let r=c.entryFor(s.key);if(!r)throw new T(`the lane behind this handle (${s.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:s.key,entry:r}},S=async n=>m(n)?.entry??(await e.sessionForHandle(n)).entry,w=n=>{let s=l.get(n);if(!s){let r={waiting:0,gone:new AbortController};d.set(n,r),s=(async()=>{if(await D(n.session,r.gone.signal),r.gone.signal.aborted)throw M(r.gone.signal);d.get(n)===r&&d.delete(n);let u=await Z(n.session,await o());return Object.assign(u,{sessionId:n.session.id})})(),l.set(n,s),s.then(u=>{l.get(n)===s&&(n.audioDispose=()=>u.dispose())},()=>{}),s.catch(()=>{l.get(n)===s&&l.delete(n)}),s.then(()=>{d.get(n)===r&&d.delete(n)},()=>{d.get(n)===r&&d.delete(n)})}return s},x=n=>{let s=h.get(n);return s||(s=(async()=>{let r=await w(n);return{appendInputAudio:(u,E)=>r.appendInputAudio(u,E),onOutputAudio:u=>r.onOutputAudio(u),sessionId:p(n)}})(),h.set(n,s),s.catch(()=>{h.get(n)===s&&h.delete(n)})),s},_=async(n,s,r,u=!1)=>{let E=()=>u?Oe(n.session):Xe(n.session);if(r?.aborted){let O=d.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await E().catch(()=>{}),M(r)}let b=s(n),P=d.get(n);return P!==void 0&&P.waiting++,r===void 0?b:new Promise((O,A)=>{let z=()=>{P!==void 0&&--P.waiting===0&&d.get(n)===P&&(P.gone.abort(),d.delete(n),l.delete(n),h.delete(n),E().catch(()=>{})),A(M(r))};r.addEventListener("abort",z,{once:!0});let Q=()=>r.removeEventListener("abort",z);b.then(C=>{Q(),O(C)},C=>{Q(),A(C)})})},L=async(n,s,r)=>{try{return await r}catch(u){throw(u instanceof T||u instanceof K&&X(u))&&(e.evict(n,s),u instanceof K&&t?.(n,u.kind==="never-live"?"never-live":"create-failed")),u}};return{createResponse:ge({sessionFor:c?async n=>{let s=await e.resolveTargetFor(n);if(s.sharedApp)try{let r=await c.sessionFor(n,s);return{app:r.app,entry:r.entry,identity:r.identity}}catch(r){if(r instanceof le)return i?i.sessionFor(n):e.sessionFor(n);if(r instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${r.name} ${r.code}: ${r.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw r}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>p(n),evict:(n,s)=>{c&&c.owns(s)?c.evict(s):i?i.evict(s):e.evict(n,s)},onAdmissionVerdict:(n,s,r)=>{X(r)&&(c&&c.owns(s)?c.evict(s):i?i.markSessionDead(s):e.evict(n,s),t?.(n,r.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>{try{await D(n.session);let r=pe(W(await n.responses.responses.create(s),n.gone),a);if(!i&&!c)return r;let u=n;return(async function*(){try{yield*r}catch(b){throw fe(b)&&(c&&c.owns(u)?c.evict(u):i&&(b instanceof T?i.markSessionDead(u):i.evict(u))),b}finally{c&&c.owns(u)?c.release(u):i?.end(u)}})()}catch(r){throw c&&c.owns(n)?c.release(n):i&&i.end(n),r}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,s)=>e.supportsImages(n,s),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,s)=>{let{app:r,entry:u}=await e.sessionFor(n);return await L(r,u,_(u,w,s))},openAudioOn:async(n,s,r,u)=>{let E=m(n);if(E){let A=E.entry.session;return Se(A)}let{app:b,entry:P}=await e.sessionForHandle(n);if(u&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;u({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let O=R(n)?.app.startsWith(H)??!1;return await L(b,P,_(P,x,s,O))},openTurnsOn:async function*(n,s){if(s?.aborted)throw M(s);let r=await S(n);yield*ie(r.session,s)},openVideoOn:async n=>{let s=m(n);if(s)return Pe(s.entry.session);let{entry:r}=await e.sessionForHandle(n),u=g.get(r);return u||(u=$(r.session),g.set(r,u)),u},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),r=g.get(s);return r||(r=$(s.session),g.set(s,r)),r},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),r=y.get(s);return r||(r=oe(s.session),y.set(s,r)),r},sessionHandle:async n=>{if(c){let s=await e.resolveTargetFor(n);if(s.sharedApp){let r=await c.sessionFor(n,s),u=p(r.entry);if(u===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return V(f,u)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:r,entry:u}=await e.dedicatedSessionFor(n);return V(r,ke(u))},releaseSessionHandle:n=>{let s=R(n);if(!s)return;if(s.app.startsWith(H)){(async()=>{let u=null;try{u=(await e.sessionForHandle(n)).entry}catch{return}await Oe(u.session).catch(()=>{}),await e.evict(s.app,u)})();return}if(!c||s.app!==f)return;let r=c.entryFor(s.key);r&&c.release(r)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:r}=await e.sessionForHandle(n);await e.evict(s,r)},createResponseOn:async(n,s,r)=>{let u=await S(n);await D(u.session);let E=r!==void 0&&m(n)?new j({...u.session,consumerId:r},{sessionTag:r}):u.responses;return W(await E.responses.create(s),u.gone)},onSessionEnd:async(n,s)=>{let r=m(n);if(r)return r.entry.gone.onGone(P=>s({timeLeftMs:null,reason:P.message}));let{entry:u}=await e.sessionForHandle(n),E=u.session;if(typeof E.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let b=!1;return E.onPhase(P=>{if(b||!qe.has(P.name))return;b=!0;let O=E.endsAt??null;s({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}export{k as a,on as b,Tn as c,Rn as d,Fn as e,Nn as f,Mn as g};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{a as $e,b as Ot,c as Ct,e as xe,f as Nt,g as He}from"./chunk-DMRZZTYI.js";import{A as Lt,B as It,C as At,D as Ut,E as Tt,b as it,d as at,i as dt,j as ut,l as pt,m as ht,n as gt,o as mt,p as yt,q as wt,r as bt,t as vt,u as ce,v as _t,w as St,x as kt,y as Et,z as Rt}from"./chunk-VQSCBUKT.js";import{a as ot}from"./chunk-X5BLQXHK.js";import{a as xt,e as Ht}from"./chunk-Y774TOE7.js";import{a as Pt}from"./chunk-MJSK6W3W.js";import{a as lt,b as ae,c as ct,o as ft,p as le}from"./chunk-BA3NCMS5.js";import{a as $t,c as ee,e as De}from"./chunk-XNRPTMSL.js";import{a as nt}from"./chunk-HB5KNEY5.js";import{e as rt,j as oe,n as st,o as ie,p as Ne}from"./chunk-J3KCHTSA.js";import{c as U}from"./chunk-YSFSRI3D.js";U();import{Counter as J,Gauge as de,Histogram as ue,Registry as An,collectDefaultMetrics as Un}from"@prometheus-io/client";import{createServer as Tn}from"http";var Os=9464,Dt="/metrics",fe="(other)",On="(none)",Pn=64,Cn=128,Nn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",vt,St,rt],$n=new Set(Nn);function xn(t){return $n.has(t)?t:fe}function Hn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?On:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,fe):(this.admitted.add(e),e):fe}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},he=class{registry=new An;modelLabel=new pe(Pn);orgLabel=new pe(Cn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new de({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new J({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 ue({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 ue({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 J({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 J({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 J({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of kt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new de({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"},Et()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Rt()/1e3)}}),this.labelCardinality=new de({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 J({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new de({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new ue({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new ue({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new J({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new J({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&Un({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=xn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?fe:e.method,status_class:Hn(e.status),stream:l,model:o,org:i}),this.duration.observe({lane:n,stream:l,model:o,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Mt(t){return Tn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Dt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Dt}
|
|
2
|
+
`);return}let s=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(s)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
|
|
3
|
+
`);return}n.end()})})}U();import{createHash as Ft}from"crypto";import{createServer as Dn}from"http";var xs=9465,Mn="x-urun-key-id",Wn="x-urun-key-fingerprint",Fn="urun-ratelimit-bucket:",Bn="urun-ratelimit-tier:",Wt="anonymous",Kn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Gn(t){return Ft("sha256").update(`${Fn}${t}`).digest("hex")}function jn(t){return Ft("sha256").update(`${Bn}${t}`).digest("hex")}function Jn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Kn.test(n)?n:null}function Bt(){return Dn((t,e)=>{let n=Jn(t.headers.authorization);e.setHeader(Mn,n===null?Wt:Gn(n)),e.setHeader(Wn,n===null?Wt:jn(n)),e.writeHead(200),e.end()})}U();import{createClientToken as zn,ClientTokenError as Kt}from"@urun-sh/core";import{createPublicKey as qn,verify as Vn}from"crypto";var Gt="urun-session-gateway",Yn="machine",Qn=3e5;function Jt(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var P=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},z=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},B=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function we(t){let e=(t??"").trim();if(e==="")throw new P("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 P("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Xn=60,Zn=6e4,er=4096;function tr(t){return t===401||t===403}var ne=class{constructor(e){this.opts=e;this.mint=e.mint??zn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new P("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<Zn)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let s,o;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Xn});s=i.orgId,o={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Kt&&i.status===402?(this.cache.delete(e),new z(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof Kt&&tr(i.status)?(this.cache.delete(e),new P(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new B(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!s)throw new B(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=er){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:s,at:this.now(),...o}),{apiKey:e,orgId:s,credential:n,...o}}clear(){this.cache.clear()}};function te(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function jt(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var ge=class{constructor(e,n,r,s){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=s}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof B?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<Qn)return r.keys;let s=this.inFlight.get(e);if(s!==void 0)return s;let o=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,o);let i=await o;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),s=n===""?void 0:r.find(o=>o.kid===n&&jt(o));return s===void 0&&(r=await this.keys(e,!0),s=n===""?void 0:r.find(o=>o.kid===n&&jt(o))),s}};function zt(t,e,n){try{let r=qn({key:n,format:"jwk"});return Vn("RSA-SHA256",t,r,e)}catch{return!1}}var me=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new ge(e.fetchImpl??fetch,e.now??Date.now,n=>new B("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new P("malformed machine token");let o,i;try{o=te(n),i=te(r)}catch{throw new P("malformed machine token")}if(o.alg!=="RS256")throw new P(`machine token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let a=typeof o.kid=="string"?o.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new P(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==Gt)throw new P(`machine token audience must be ${Gt} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==Yn)throw new P(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let p=typeof i.org_id=="string"?i.org_id:"";if(p==="")throw new P("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");let _=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(_===void 0)throw new P(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let A=Buffer.from(`${n}.${r}`,"ascii"),T=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!zt(A,T,_))throw new P("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:p,credential:"machine"}}},nr="https://api.workos.com/sso/jwks/";function rr(t){return`${nr}${t.slice(t.lastIndexOf("/")+1)}`}var Me=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new ge(e.fetchImpl??fetch,this.now,n=>new B("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Jt(e))return!1;try{let n=te(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new P("malformed user token");let o,i;try{o=te(n),i=te(r)}catch{throw new P("malformed user token")}if(o.alg!=="RS256")throw new P(`user token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let a=typeof o.kid=="string"?o.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new P(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let p=typeof i.org_id=="string"?i.org_id:"";if(p==="")throw new P("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new P("user token is expired \u2014 re-authenticate and retry");let _=await this.cache.keyFor(rr(l),a);if(_===void 0)throw new P(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let A=Buffer.from(`${n}.${r}`,"ascii"),T=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!zt(A,T,_))throw new P("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new P("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:p,credential:"user"}}},ye=class{verifier;bindings;constructor(e){this.verifier=new Me({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new ne({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new P("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function We(t,e,n,r){if(Jt(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}U();var sr=8080,Fe="serve",Gs="0.0.0.0";function or(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function js(t=process.env){let e=(t.PORT??"").trim(),n=e===""?sr: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=ft(le(or(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")),s=(t.URUN_API_URL??"").trim(),o=s?le(s,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=i?{catalogUrl:le(i,"URUN_CATALOG_URL"),anonKey:a}:null,p=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!p!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let _=p?{keyId:d,key:p}:void 0,A={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},T=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],c=T.filter((u,y)=>Object.values(A)[y]==="");if(c.length!==0&&c.length!==T.length)throw new Error(`${T.join(", ")} must be set together (or all left unset) \u2014 missing: ${c.join(", ")}, which would half-configure the lane plane`);let w=c.length===0?A:void 0,v={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},g=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],b=g.filter((u,y)=>Object.values(v)[y]==="");if(b.length!==0&&b.length!==g.length)throw new Error(`${g.join(", ")} must be set together (or all left unset) \u2014 missing: ${b.join(", ")}, which would half-configure the pooler cutover`);let E=b.length===0?v:void 0,h={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},f=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=f.filter((u,y)=>Object.values(h)[y]==="");if(S.length!==0&&S.length!==f.length)throw new Error(`${f.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let L=h.issuers.split(",").map(u=>u.trim()).filter(u=>u!=="");if(L.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let m=Number(h.tokenTtlS);if(S.length===0&&(!Number.isFinite(m)||m<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(h.tokenTtlS)}`);let I=S.length===0?{jwksBaseUrl:h.jwksBaseUrl,issuers:L,tokenTtlS:m}:void 0,O=(t.URUN_WORKOS_ISSUERS??"").trim(),$=O.split(",").map(u=>u.trim()).filter(u=>u!=="");if(O!==""&&$.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let u of $){let y;try{y=new URL(u)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(u)}`)}if(y.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${u}) \u2014 the issuer is the user rung's trust root`)}return{port:n,baseUrl:r,apiUrl:o,catalog:l,ledgerSigning:_,lane:w,pooler:E,machine:I,...$.length>0?{userIssuers:$}:{}}}U();import{createHash as ir,randomUUID as qt}from"crypto";var ar=512;function be(t){return`urun-inference-proxy-${ir("sha256").update(t).digest("hex").slice(0,32)}`}var ve=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let s=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;if(o===void 0)return s;let i=this.opts.lanes;return Object.assign(Object.create(s),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await s.createResponse(a,l);let p=`px_${qt()}`;return Ot(o,a,p,p)}})}build(e){if(this.opts.build){let o=this.opts.build(e);return o.decision&&this.ensureDecisionReaper(),{router:o.router,clients:this.label(o.clients,e,o.router),decision:o.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Fe,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:Ct(process.env,process.env.HOSTNAME)??void 0},r=xe(n),s=n.decisionPool?Nt(n,r):null;return s&&this.ensureDecisionReaper(),{router:r,clients:this.label(He(r,void 0,void 0,s??void 0,void 0,this.opts.lanes),e,r),decision:s??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=ar;){let s=this.tenants.entries().next();if(s.done)break;let[o,i]=s.value;this.tenants.delete(o),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let s=[r.router.closeAll().catch(o=>{n.push(String(o instanceof Error?o.message:o))})];r.decision&&s.push(r.decision.close().catch(o=>{n.push(String(o instanceof Error?o.message:o))})),await Promise.all(s)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Vt=512,lr=1024,Be=class extends Error{constructor(){super(`conversation capacity reached (${Vt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function cr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(ie))return{concurrencyKey:e};if(n.startsWith(ie)||n.startsWith(Ne))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(ie)||n.startsWith(Ne)||t.set(n,r)}}}function dr(t,e,n,r,s){let o=xe({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Fe,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...cr(r,s)});return{clients:He(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var _e=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let s={id:n,subject:r!==void 0?`${be(e.apiKey)}:live`:`${be(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,s):dr(this.opts,e,s,o,r);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n,r){let s=this.byCaller.get(e.apiKey);s===void 0&&(s=new Map,this.byCaller.set(e.apiKey,s));let o=s.get(n);if(o!==void 0)return s.delete(n),s.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,s.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Vt;){let e=!1;for(let[n,r]of this.byCaller){for(let[s,o]of r)if(!(o.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),o.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new Be}}dropHandleIndexFor(e,n){for(let[r,s]of this.byHandle)s.apiKey===e&&s.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,s=!1,o=()=>(r===null&&(r=this.attachEntry(e,qt(),n)),r),i={createResponse:(a,l)=>o().backhaul.clients.createResponse(a,l),catalogIdentity:a=>o().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=o().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(a)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:a=>o().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=o().backhaul.clients.dedicatedSessionHandle;return l===void 0?o().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>o().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,l,p)=>o().backhaul.clients.createResponseOn(a,l,p),onSessionEnd:(a,l)=>o().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let p=o().backhaul.clients.openAudio;if(p===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return p(a,l)},i.openVideo=async a=>{let l=o().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=o().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=o().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=o().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=o().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(a)},i.speechSessionHandle=async a=>{let l=o().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(a)},i.openAudioOn=async(a,l,p)=>{let d=o().backhaul.clients.openAudioOn;if(d===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return d(a,l,p)},i.openVideoOn=async(a,l)=>{let p=o().backhaul.clients.openVideoOn;if(p===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return p(a,l)},i.openTurnsOn=(a,l)=>{let p=o().backhaul.clients.openTurnsOn;if(p===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return p(a,l)},i.evictSpeechSession=async a=>{let l=o().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(a)},i.supportsTranscription=async a=>{let l=o().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=o().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(a)},i.listSpeechToTextModels=async()=>{let a=o().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=lr;){let p=this.byHandle.keys().next();if(p.done)break;this.byHandle.delete(p.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),p=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||p===void 0?void 0:p.get(l.conversationId);if(l===void 0||d===void 0||l.apiKey!==e.apiKey)throw new oe("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(s)return;s=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let s of r.values())e.push(s.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(s){n.push(String(s instanceof Error?s.message:s))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};U();var ur="/inference-ledger",fr=1e4,Se=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},je=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},M=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Je=class extends P{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ze=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},pr=[["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",Ke],["output_minutes",Ke],["cost_nano_usd",Ke],["price_version",t=>t===null||typeof t=="string"]];function hr(t){for(let[e,n]of pr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function gr(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"}:hr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ke(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Ge(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function mr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Yt(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 yr(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&&Yt(t.started_at,n.started_at)&&Yt(t.completed_at,n.completed_at)&&Ge(t.prompt_tokens,n.prompt_tokens)&&Ge(t.completion_tokens,n.completion_tokens)&&Ge(t.output_units,n.output_units)&&mr(t.output_minutes,n.output_minutes)}function wr(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
|
|
4
|
+
`)}async function br(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",r,n.encode(wr(t)));return{signature:Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function vr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new M(`${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 M(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new M(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let s=n.cost_nano_usd;if(s!=null&&!(typeof s=="number"&&Number.isInteger(s)&&s>=0))throw new M(`${e} answered cost_nano_usd ${JSON.stringify(s)}, which is neither a non-negative integer nor null`);let o=p=>{if(!(p in n))throw new M(`${e} answered a row with no ${p} field: ${JSON.stringify(t)}`);let d=n[p];if(d===null)return null;if(typeof d!="string")throw new M(`${e} answered a non-string ${p}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new M(`${e} answered a BLANK ${p} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=o("price_version"),a=o("unpriced_reason"),l=s!=null;if(l&&(i===null||a!==null))throw new M(`${e} answered a PRICED row (cost_nano_usd ${String(s)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!l&&(i!==null||a===null))throw new M(`${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:s===void 0?null:s,price_version:i,unpriced_reason:a}}var ke=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ur}`,s;try{s=this.opts.signing?JSON.stringify({...n,...await br(n,this.opts.signing)}):JSON.stringify(n)}catch(p){throw new M(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${p instanceof Error?p.message:String(p)}`)}let o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:s,signal:AbortSignal.timeout(fr)})}catch(p){throw new M(`the uRun ledger surface at ${r} could not be reached: ${p instanceof Error?p.message:String(p)}`)}if(o.status===409){let p=await o.text().catch(()=>""),d=gr(p);throw d.status==="found"&&yr(n,d.row)?new je(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 Se(`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 Se(`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). ${p.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Je("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 p=await o.text().catch(_=>`<body unreadable: ${_ instanceof Error?_.message:String(_)}>`),d;try{let _=JSON.parse(p);if(_!==null&&typeof _=="object"&&"error"in _){let A=_.error;A!==null&&typeof A=="object"&&"code"in A&&(d=A.code)}}catch{}throw d==="ledger_signature_invalid"?new ze(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+p.slice(0,400)):new M(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${p.slice(0,400)}`)}let i;try{i=await o.json()}catch(p){throw new M(`the uRun ledger surface at ${r} answered a body that is not JSON: ${p instanceof Error?p.message:String(p)}`)}let a=i?.recorded;if(a===void 0)throw new M(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=vr(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new M(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};U();import{createServer as ms}from"http";U();import{createCipheriv as _r,createDecipheriv as Sr,hkdfSync as kr,randomBytes as Er,randomUUID as Zt}from"crypto";import{resolve4 as Rr}from"dns/promises";U();var Qt="/realtime/openai.quic-relay";async function Xt(t){let e=await fetch(`${t.sfuBase}${Qt}${t.query}`,{method:"POST",headers:{"content-type":"application/json",authorization:t.upstreamHeaders.authorization??""},body:"{}"});if(e.status!==201){let o=await e.text().catch(()=>"");throw new Error(`quic relay ${t.sfuBase}${Qt} -> ${e.status} ${o}`)}let n=await e.json(),r=new URL(t.sfuBase).host,s=n.url??`https://${r}:${n.wtPort??4443}/wt`;return{status:201,body:{callId:n.callId,url:s,token:n.token,certHashes:n.certHashes},location:`/v1/realtime/calls/${n.callId}`}}var qe="/v1/realtime/calls",en="/v1/realtime/client_secrets",Lr="session-server-ts-pods.urun.svc.cluster.local",tn=8081,Ir="/realtime/openai.relay",Ar=262144,Ur=600;function nn(t){let e=t.secret===void 0?void 0:Buffer.from(kr("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>Nr(await Rr(Lr))),r=(s,o,i,a)=>{s.writeHead(o,{"content-type":"application/json"}),s.end(JSON.stringify({error:{message:i,type:"invalid_request_error",...a?{code:a}:{}}}))};return async(s,o)=>{let i=new URL(s.url??"/","http://proxy");if(s.method!=="POST"||i.pathname!==qe&&i.pathname!==en)return!1;let a=await Or(s);if(a===null)return r(o,413,"request body too large"),!0;let l=(s.headers.authorization??"").replace(/^Bearer\s+/i,"");if(l.startsWith("ek_")){let g=e===void 0?null:Cr(e,l.slice(3));if(g===null)return r(o,401,"invalid or expired client secret","invalid_api_key"),!0;s.headers.authorization=`Bearer ${g}`}try{await t.authorize(s)}catch(g){let b=typeof g=="object"&&g!==null&&"status"in g&&typeof g.status=="number"?g.status:401;return r(o,b,g instanceof Error?g.message:String(g)),!0}if(i.pathname===en){if(e===void 0)return r(o,501,"client secrets are not configured on this proxy"),!0;let g=a.length===0?{}:JSON.parse(a.toString("utf8")),b=typeof g=="object"&&g!==null&&"session"in g?g.session:null,E=Math.floor(Date.now()/1e3)+Ur,h=(s.headers.authorization??"").replace(/^Bearer\s+/i,"");return o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({value:`ek_${Pr(e,h,E)}`,expires_at:E,session:b})),!0}if(i.searchParams.get("transport")==="quic"){let g=i.searchParams.get("model");if(g===null)return r(o,400,"model is required (?model=)"),!0;let b=`quic_${Zt().replaceAll("-","")}`,E=new URLSearchParams(i.searchParams);E.set("model",g),E.set("call_id",b);let h="no media edge resolved";for(let f of await n())try{let S=await Xt({sfuBase:`http://${f}:${tn}`,query:`?${E}`,upstreamHeaders:{authorization:s.headers.authorization??""}});return o.writeHead(201,{"content-type":"application/json",location:`${qe}/${S.body.callId}`}),o.end(JSON.stringify(S.body)),!0}catch(S){h=`${f}: ${String(S)}`}return r(o,502,`no media edge accepted the quic call (${h})`),!0}let{sdp:p,session:d}=await Tr(s.headers["content-type"]??"",a);if(p===void 0)return r(o,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)"),!0;let _=typeof d=="object"&&d!==null&&"model"in d&&typeof d.model=="string"?d.model:void 0,A=i.searchParams.get("model")??_;if(A===void 0)return r(o,400,"model is required (?model= or session.model)"),!0;let T=`rtc_${Zt().replaceAll("-","")}`,c=new URLSearchParams(i.searchParams);c.set("model",A),c.set("call_id",T);let w=JSON.stringify({sdp:p,...d!==void 0?{session:d}:{}}),v="no media edge resolved";for(let g of await n()){let b;try{b=await fetch(`http://${g}:${tn}${Ir}?${c}`,{method:"POST",headers:{"content-type":"application/json",authorization:s.headers.authorization??""},body:w,signal:AbortSignal.timeout(1e4)})}catch(h){v=`${g}: ${String(h)}`;continue}let E=await b.text();if(b.status===201)return o.writeHead(201,{"content-type":"application/sdp",location:`${qe}/${T}`}),o.end(E),!0;if(b.status>=500||b.status===404||b.status===405||b.status===501){v=`${g}: ${b.status} ${E}`;continue}return r(o,b.status,E),!0}return r(o,503,`no media edge answered the offer (${v})`,"media_edge_unavailable"),!0}}async function Tr(t,e){if(t.startsWith("application/sdp"))return{sdp:e.toString("utf8")};if(!t.startsWith("multipart/form-data"))return{};let n=await new Response(new Uint8Array(e),{headers:{"content-type":t}}).formData(),r=n.get("sdp"),s=n.get("session");return{...typeof r=="string"?{sdp:r}:{},...typeof s=="string"?{session:JSON.parse(s)}:{}}}async function Or(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>Ar)return null;e.push(r)}return Buffer.concat(e)}function Pr(t,e,n){let r=Er(12),s=_r("aes-256-gcm",t,r),o=Buffer.concat([s.update(JSON.stringify({b:e,e:n}),"utf8"),s.final()]);return Buffer.concat([r,s.getAuthTag(),o]).toString("base64url")}function Cr(t,e){try{let n=Buffer.from(e,"base64url"),r=Sr("aes-256-gcm",t,n.subarray(0,12));r.setAuthTag(n.subarray(12,28));let s=JSON.parse(Buffer.concat([r.update(n.subarray(28)),r.final()]).toString("utf8"));if(typeof s!="object"||s===null||!("b"in s)||!("e"in s))return null;let{b:o,e:i}=s;return typeof o!="string"||typeof i!="number"?null:i>Date.now()/1e3?o:null}catch{return null}}function Nr(t){for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}U();import{SessionAllocationError as zr}from"@urun-sh/core";import{createWebsocketDocConnector as qr}from"@urun-sh/core/internal";import Vr from"ws";U();import{request as $r}from"http";var xr="/pooler/v1/lanes/pick",Hr="/pooler/v1/lanes/status",Dr=1e4,re=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function rn(t,e,n,r,s){return new Promise((o,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),p=$r({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:s},d=>{let _=[];d.on("data",A=>_.push(A)),d.on("end",()=>{let A=Buffer.concat(_).toString("utf8"),T=null;try{T=A===""?null:JSON.parse(A)}catch{T=null}o({status:d.statusCode??0,json:T})}),d.on("error",A=>i(new $e(502,"pooler_unreachable",`the pooler channel failed: ${A.message}`)))});p.on("timeout",()=>{p.destroy(new re(`pooler lane surface timed out after ${s}ms (${e} ${n})`))}),p.on("error",d=>i(new $e(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),p.end(l)})}function sn(t,e,n,r){if(t===400&&Mr(e)?.code==="lane_target")return new ct(n,r);if(t===503)return new ae(n);let s=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${s}`)}function Mr(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function on(t){return{async pick({pool:e,app:n,fn:r,sharedApp:s,model:o,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),xt),l=await rn(t,"POST",xr,{pool:e,app:n,fn:r,model:o,hold_ms:a,...s?{shared_app:!0}:{}},a+Dr);if(l.status!==200)throw sn(l.status,l.json,e,o);return(l.json?.lanes??[]).filter(d=>typeof d.lane_id=="string"&&d.lane_id!==""&&typeof d.host=="string"&&d.host!=="").map(d=>({laneId:d.lane_id,host:d.host}))},async status(){let e=await rn(t,"GET",Hr,void 0,5e3);if(e.status!==200)throw sn(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}U();import*as q from"yjs";import{SessionDocumentImpl as Wr}from"@urun-sh/core/internal";var Fr=3e4;function Br(t){return(e,n,r)=>{let s=t(e);q.applyUpdate(n,q.encodeStateAsUpdate(s));let o=a=>q.applyUpdate(s,a),i=a=>q.applyUpdate(n,a);return n.on("update",o),s.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",o),s.off("update",i)}}}}function Ve(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Br(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,s=!1,o=d=>{if(s)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let _=r.get(d);return _||(_=new Wr(d,e,n),r.set(d,_)),_},i=new Map,a=d=>{if(s)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let _=i.get(d);if(!_){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);_=t.streamEndpoint(d),i.set(d,_)}return _},l=d=>{let _="llm-resp:";if(!d.startsWith(_))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${_}<rid>)`);async function*A(){let T=a(d);try{yield*T.messages()}finally{i.delete(d),await T.close()}}return{messages:()=>A(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return o(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let _=o("llm");if(_.synced===!0)return;let A=d?.timeout??t.whenLiveTimeoutMs??Fr;await new Promise((T,c)=>{let w=setTimeout(()=>{v(),c(new Error(`lane ${e} llm doc never synced within ${A}ms`))},A),v=_.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",g),T()}),g=()=>{clearTimeout(w),v(),c(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",g,{once:!0})})},destroy(){s=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,_]of i)i.delete(d),_.close()}}}U();import Ee,{WebSocketServer as Kr}from"ws";import{ENVELOPE_KIND as dn,STREAM_END as Gr,StreamFragmentReassembler as jr}from"@urun-sh/core";var an="/stream/";function ln(t){if(!t.startsWith(an))return null;let e=t.slice(an.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Ie(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Re(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>dn.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Le=class{reassembler=new jr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===Gr&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},Qe=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,s=this.channels.get(r);return s||this.channels.set(r,s={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),s}deliver(e,n,r,s){let o=this.chan(e,n),i=[...o.peers].filter(a=>a!==r);if(i.length===0){let a=o.pending;a.bytes+s.byteLength>cn&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${cn} bytes)`))),a.list.push({envelope:s,producer:r}),a.bytes+=s.byteLength;return}for(let a of i)a.deliver(s)}attach(e,n,r){let s=this.chan(e,n);s.peers.add(r);let o=s.pending;if(o.list.length===0)return;let i=o.list.filter(a=>a.producer!==r);o.list=o.list.filter(a=>a.producer===r),o.bytes=o.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let s=`${e}::${n}`,o=this.channels.get(s);if(o){for(let i of[...o.peers])i===r&&o.peers.delete(i);o.peers.size===0&&o.pending.list.length===0&&this.channels.delete(s)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let s=this.channels.get(r);this.channels.delete(r);for(let o of s?.peers??[])o.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},cn=8*1024*1024,F=new Qe;function un(t,e){let n=new Le,r={send(s){F.deliver(t,e,r,s)},deliver(s){if(!n.isEnded){try{Re(s)}catch(o){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(o)}`);return}n.push(n.feed(s))}},messages:()=>n.iterate(),async close(){n.finish(),F.detach(t,e,r)}};return F.attach(t,e,r),r}function Jr(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function fn(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,s=new Ee(r,Ie(e)),o=new Le;return s.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Re(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}o.push(o.feed(a))}),s.addEventListener("close",()=>{o.finish(new Error(`lane stream ${r} closed before END`))}),s.addEventListener("error",()=>{o.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Re(i),s.readyState!==Ee.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);s.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>o.iterate(),async close(){o.finish();try{s.close(1e3)}catch{}}}}function Ye(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",s=`${n}\r
|
|
5
|
+
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
6
|
+
Connection: close\r
|
|
7
|
+
Content-Type: text/plain; charset=utf-8\r
|
|
8
|
+
Content-Length: ${Buffer.byteLength(s)}\r
|
|
9
|
+
\r
|
|
10
|
+
${s}`)}function pn(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,s=new Kr({noServer:!0,handleProtocols:(c,w)=>{let v=ln(new URL(w.url??"/","http://localhost").pathname);if(!v)return!1;let g=Ie(v.name);return c.has(g)?g:!1}}),o=new Map,i=new Set,a=!1,l=new Map,p=(c,w,v)=>{r>0&&l.set(c,{at:Date.now(),label:w,reap:v})},d=c=>{let w=l.get(c);w&&(w.at=Date.now())},_=r>0?setInterval(()=>{let c=Date.now();for(let[w,v]of l)c-v.at<r||(l.delete(w),console.warn(`[lane-stream] ${v.label}: lease expired (no data for ${r} ms) \u2014 terminating`),v.reap())},Math.max(10,Math.floor(r/4))):void 0;_?.unref?.();let A=(c,w,v,g)=>{let b={client:v,upstream:g,laneId:c,name:w};i.add(b);let E=h=>{if(i.delete(b)){l.delete(v),console.warn(`[lane-stream] ${c}/${w}: host-affinity pump torn down (${h})`);for(let f of[v,g])try{(f.readyState===Ee.OPEN||f.readyState===Ee.CONNECTING)&&f.close(1001,"lane stream pump closed")}catch{}}};if(p(v,`${c}/${w} pump`,()=>{for(let h of[v,g])try{h.terminate()}catch{}E("lease expired")}),n>0){let h=(f,S)=>{let L=!0,m=()=>{L=!0};f.on("pong",m),f.on("message",m);let I=setInterval(()=>{if(!L){console.warn(`[lane-stream] ${c}/${w}: pong timeout on ${S} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${S} dial never sends a close)`),clearInterval(I);try{f.terminate()}catch{}E(`${S} pong timeout`);return}L=!1;try{f.ping()}catch{}},n);I.unref?.();let O=()=>clearInterval(I);f.once("close",O),f.once("error",O)};h(v,"client"),h(g,"host")}v.on("message",h=>{d(v);try{g.send(h,{binary:!0})}catch(f){E(`upstream send failed: ${String(f)}`)}}),g.on("message",h=>{d(v);try{v.send(h,{binary:!0})}catch(f){E(`client send failed: ${String(f)}`)}}),v.on("close",()=>E("client socket closed")),v.on("error",()=>E("client socket error")),g.on("close",()=>E("host socket closed")),g.on("error",()=>E("host socket error"))},T=(c,w,v)=>{let g;try{g=new URL(c.url??"/","http://localhost")}catch{Ye(w,400,"malformed upgrade URL");return}w.on("error",()=>w.destroy());let b=ln(g.pathname);b&&(a||w.destroyed||(async()=>{let E=g.searchParams.get("token")??"",h=null;try{h=E===""?null:await e.verifyToken(E,b.laneId,b.name)}catch{h=null}if(h===null){Ye(w,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let f=await e.hostOf(b.laneId).catch(()=>null);if(f&&f!==e.selfAddress)try{let S=await e.podToPodDial(b.laneId,b.name,f);s.handleUpgrade(c,w,v,L=>{A(b.laneId,b.name,L,S)});return}catch(S){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${f} failed (${String(S)}) \u2014 falling back to the local relay`)}}s.handleUpgrade(c,w,v,f=>{let S=Jr(f,()=>d(f));if(o.set(f,S),F.attach(b.laneId,b.name,S),p(f,`${b.laneId}/${b.name}`,()=>f.terminate()),n>0){let m=!0,I=()=>{m=!0};f.on("pong",I),f.on("message",I);let O=setInterval(()=>{if(!m){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(O),f.terminate();return}m=!1;try{f.ping()}catch{}},n);O.unref?.();let $=()=>clearInterval(O);f.once("close",$),f.once("error",$)}f.on("message",m=>{d(f);let I=new Uint8Array(m);try{Re(I)}catch(O){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(O)}`);return}F.deliver(b.laneId,b.name,S,I),I[1]===dn.END&&F.detach(b.laneId,b.name,S)});let L=()=>{o.delete(f),l.delete(f),F.detach(b.laneId,b.name,S)};f.on("close",L),f.on("error",L)})})().catch(()=>{w.destroyed||Ye(w,500,"lane stream upgrade failed")}))};return t.on("upgrade",T),{async close(){a=!0,t.off("upgrade",T),clearInterval(_),l.clear(),F.clear();for(let c of o.values())c.close(1001,"lane stream host shutting down");o.clear();for(let c of i)for(let w of[c.client,c.upstream])try{w.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}function Yr(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new lt(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}var Qr={"prod-usw2":["us-west1"]};function hn(t){let e=t.now??Date.now,n=new Map,r=new Map,s=new Set,o=new Map,i=new Set,a=(c,w,v,g,b,E)=>{let h=v?m=>un(c,m):m=>fn(c,m,{hostUrl:`ws://${g}/stream/${c}`,token:()=>ee(c,t.tokenSecret,void 0,void 0,E)}),f=v?Ve({laneId:c,roomDoc:m=>t.roomDoc(c,m),streamEndpoint:h}):Ve({laneId:c,streamEndpoint:h,connector:qr({serverUrl:`ws://${g}/doc`,sessionId:c,token:()=>ee(c,t.tokenSecret,void 0,void 0,E),WebSocketPolyfill:Vr})}),S=v?l(c):Pt(f,`lane:${c}`,{armOnFirstSync:!0}),L={session:f,responses:new nt(f,{sessionTag:null}),gone:S,goneWatch:S,laneId:c,pool:w,inFlight:0,laneSession:f,self:v,host:g??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(c,L),S.onGone(()=>p(L)),L},l=c=>{let w=null,v=!1,g=new Set,b=h=>{if(!w){w=h;for(let f of[...g])f(h);g.clear()}},E=t.hostedSignal?.(c,h=>{if(h){v=!0;return}v&&b(new oe(`the lane ${c} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>w,onGone(h){return w?(h(w),()=>{}):(g.add(h),()=>g.delete(h))},dispose(){E?.(),g.clear()}}},p=c=>{d(c)&&(n.delete(c.laneId),r.delete(c.laneId),c.goneWatch?.dispose(),F.forgetLane(c.laneId))},d=c=>{let w=c.laneId;return typeof w=="string"&&n.get(w)===c},_=c=>{d(c)&&(c.self&&!t.closeLane||(i.add(c.laneId),c.self&&t.closeLane?.(c.laneId),p(c)))},A=(c,w)=>{throw t.metrics?.observeLane503Fast(w??""),o.set(c,e()),new ae(c)},T=async(c,w)=>{let v=Yr(w);s.add(v);let g=e();try{let b=await t.laneWarmWaitMsFor?.(c,w)??t.laneColdWakeDefaultMs??0,E;try{E=await t.plane.pick({pool:v,app:w.appSlug,fn:w.fnName??"",model:c,holdMs:b,...w.sharedApp?{sharedApp:!0}:{}})}catch(I){throw I instanceof re?new zr(`lane pick hold expired for ${v}: ${I.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):I}t.metrics?.observeLaneReady(c??"",E.length);let h=await t.currentReleaseOf?.(w)??null,f=new Set(E.map(I=>I.laneId));for(let I of i)f.has(I)||i.delete(I);let L=E.filter(I=>{let O=n.get(I.laneId);return O!==void 0&&h!==null&&O.mintedRelease!==""&&O.mintedRelease!==h&&(O.retireWhenIdle=!0,O.inFlight===0)?(_(O),!1):!i.has(I.laneId)}).map(I=>({laneId:I.laneId,self:I.host===t.selfAddress,host:I.host,region:I.region})).sort((I,O)=>{let $=Qr[t.seatRegion??""]??[],u=new Map($.map((k,C)=>[k,C])),y=$.length===0?0:(I.region!==void 0?u.get(I.region):void 0)??$.length,R=$.length===0?0:(O.region!==void 0?u.get(O.region):void 0)??$.length;return y!==R?y-R:I.self!==O.self?I.self?-1:1:(r.get(I.laneId)??0)-(r.get(O.laneId)??0)})[0];L||A(v,c);let m=n.get(L.laneId);return m?.goneWatch?.gone()&&(p(m),m=void 0),m&&(m.pool!==v||m.self!==L.self||m.host!==L.host)&&(p(m),m=void 0),m||(m=a(L.laneId,v,L.self,L.host,h,w.sharedOrgId??void 0)),m.inFlight+=1,r.set(L.laneId,(r.get(L.laneId)??0)+1),{app:v,entry:m,identity:{kind:"catalog",model_id:w.modelId??c??"",variant:w.variant??""}}}finally{t.metrics?.observeLanePick(c??"",e()-g)}};return{sessionFor(c,w){return T(c,w)},release(c){d(c)&&(c.inFlight=Math.max(0,c.inFlight-1),r.set(c.laneId,c.inFlight),c.inFlight===0&&c.retireWhenIdle&&_(c))},owns(c){return d(c)},entryFor(c){return n.get(c)??null},evict(c){d(c)&&(c.gone.dispose(),n.delete(c.laneId),r.set(c.laneId,0),c.laneSession.destroy())},async status(){let c=[...new Set([...s,...[...n.values()].map(g=>g.pool)])].sort(),w=await t.plane.status().catch(()=>[]),v=new Map(Xr(w));return Promise.all(c.map(async g=>{let b=v.get(g)??{pool:g,lanes:[],lastDemandAt:null};return{pool:g,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(E=>E.pool===g).map(E=>({laneId:E.laneId,inFlight:E.inFlight,self:E.self,host:E.host})),lastRefusalAt:o.get(g)??null}}))},async close(){for(let c of n.values())c.gone.dispose(),c.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(c=>({pool:c.pool,laneId:c.laneId,inFlight:c.inFlight}))}}}function Xr(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}U();var Zr="urun:node-scheduler:apps:v1";function es(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function gn(t){return async e=>{let n=es(e);if(n===null)return null;try{let r=await t.hget(Zr,n);if(r===null||r==="")return null;let s=JSON.parse(r);if(typeof s!="object"||s===null)return null;let o=s.current_release_id;if(typeof o!="string")return null;let i=o.trim();return i===""?null:i}catch{return null}}}U();import{WebSocketServer as fs}from"ws";U();import*as yn from"yjs";import*as Q from"y-protocols/sync";import*as K from"y-protocols/awareness";import*as N from"lib0/encoding";import*as X from"lib0/decoding";import*as wn from"lib0/map";import ns from"lodash.debounce";U();var mn=()=>{};var rs=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,ss=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,os=0,is=1;var as=process.env.GC!=="false"&&process.env.GC!=="0",ls=process.env.YPERSISTENCE,Ae=null;if(typeof ls=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Y=new Map,Ue=0,Ze=1,cs=(t,e,n)=>{let r=N.createEncoder();N.writeVarUint(r,Ue),Q.writeUpdate(r,t);let s=N.toUint8Array(r);n.conns.forEach((o,i)=>se(n,i,s))},Xe=class extends yn.Doc{constructor(e){super({gc:as}),this.name=e,this.conns=new Map,this.awareness=new K.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:s,removed:o},i)=>{let a=r.concat(s,o);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(_=>{d.add(_)}),o.forEach(_=>{d.delete(_)}))}let l=N.createEncoder();N.writeVarUint(l,Ze),N.writeVarUint8Array(l,K.encodeAwarenessUpdate(this.awareness,a));let p=N.toUint8Array(l);this.conns.forEach((d,_)=>{se(this,_,p)})};this.awareness.on("update",n),this.on("update",cs),!1}},et=(t,e=!0)=>wn.setIfUndefined(Y,t,()=>{let n=new Xe(t);return n.gc=e,Ae!==null&&Ae.bindState(t,n),Y.set(t,n),n}),ds=(t,e,n)=>{try{let r=N.createEncoder(),s=X.createDecoder(n);switch(X.readVarUint(s)){case Ue:N.writeVarUint(r,Ue),Q.readSyncMessage(s,r,e,t),N.length(r)>1&&se(e,t,N.toUint8Array(r));break;case Ze:{K.applyAwarenessUpdate(e.awareness,X.readVarUint8Array(s),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},V=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),K.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Ae!==null&&(Ae.writeState(t.name,t).then(()=>{t.destroy()}),Y.delete(t.name))}e.close()},se=(t,e,n)=>{e.readyState!==os&&e.readyState!==is&&V(t,e);try{e.send(n,r=>{r!=null&&V(t,e)})}catch{V(t,e)}},us=3e4,bn=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let s=et(n,r);s.conns.set(t,new Set),t.on("message",a=>ds(t,s,new Uint8Array(a)));let o=!0,i=setInterval(()=>{if(!o)s.conns.has(t)&&V(s,t),clearInterval(i);else if(s.conns.has(t)){o=!1;try{t.ping()}catch{V(s,t),clearInterval(i)}}},us);t.on("close",()=>{V(s,t),clearInterval(i)}),t.on("pong",()=>{o=!0});{let a=N.createEncoder();N.writeVarUint(a,Ue),Q.writeSyncStep1(a,s),se(s,t,N.toUint8Array(a));let l=s.awareness.getStates();if(l.size>0){let p=N.createEncoder();N.writeVarUint(p,Ze),N.writeVarUint8Array(p,K.encodeAwarenessUpdate(s.awareness,Array.from(l.keys()))),se(s,t,N.toUint8Array(p))}}};var tt="/doc/",_n=30,ps=1e4,vn="llm";function hs(t){if(!t.startsWith(tt))return null;let e=t.slice(tt.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function Z(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",s=`${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(s)}\r
|
|
15
|
+
\r
|
|
16
|
+
${s}`)}function Sn(t,e){let n=new fs({noServer:!0}),r=new Set,s=new Map,o=new Map,i=h=>s.get(`${h}/${vn}`)??0,a=h=>o.get(h)??0,l=new Map,p=new Map,d=new Set,_=new Set,A=new Map,T=new Map,c=4096,w=!1,v=(h,f,S)=>{let L=i(h)>0,m=a(h),I=m>0,O=`${h}/${f}`,$=s.get(O)??0;S>0?s.set(O,S):s.delete(O);let u=m+S-$;u>0?o.set(h,u):o.delete(h);let y=i(h)>0,R=u>0;if(L!==y){y?g(h):b(h);for(let k of l.get(h)??[])k(y)}I&&!R&&queueMicrotask(()=>{let k=`${h}/`;for(let[C,x]of[...Y.entries()])!C.startsWith(k)||x.conns.size>0||(Y.delete(C),x.destroy())})},g=h=>{if(!e.hostRegistry||p.has(h))return;let f=()=>{e.hostRegistry?.setHost(h,e.selfAddress).catch(()=>{})};f();let S=setInterval(f,ps);S.unref?.(),p.set(h,S)},b=h=>{let f=p.get(h);f&&(clearInterval(f),p.delete(h)),e.hostRegistry&&e.hostRegistry.delHost(h,e.selfAddress).catch(()=>{})},E=(h,f,S)=>{let L;try{L=new URL(h.url??"/","http://localhost")}catch{Z(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>_.delete(f));let m=hs(L.pathname);if(!m){if(L.pathname.startsWith(tt)){Z(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}_.add(f);return}d.add(f);let I=!1;(async()=>{if(T.has(m.laneId)){Z(f,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let O=L.searchParams.get("token")??"",$=null;try{$=O===""?null:await e.verifyToken(O,m.laneId,m.docName)}catch{$=null}if($===null){Z(f,401,"invalid or missing lane doc token");return}let u=$;if(u.tenant!==void 0&&e.laneTenantOf){let y=null;try{y=await e.laneTenantOf(m.laneId)}catch{y=null}if(y==null||y==="")e.onLaneTenantMissing?.();else if(u.tenant!==y){Z(f,403,"lane doc token org does not match the lane record");return}}w||f.destroyed||(I=!0,n.handleUpgrade(h,f,S,y=>{d.delete(f),r.add(y),y.on("close",()=>r.delete(y));let R=A.get(m.laneId);R||(R=new Set,A.set(m.laneId,R)),R.add(y),y.on("close",()=>{R.delete(y),R.size===0&&A.delete(m.laneId)});let k=u.scope===$t||u.scope===void 0&&typeof u.app=="string"&&typeof u.fn=="string"&&u.aud==="sfu";if(k){let x=`${m.laneId}/${m.docName}`,W=(s.get(x)??0)+1;v(m.laneId,m.docName,W),W>1&&m.docName===vn&&e.hostRegistry?.setHost(m.laneId,e.selfAddress).catch(()=>{})}y.on("close",()=>{if(!k)return;let x=`${m.laneId}/${m.docName}`;v(m.laneId,m.docName,Math.max(0,(s.get(x)??1)-1))}),bn(y,h,{docName:`${m.laneId}/${m.docName}`,gc:!0})}))})().catch(()=>{!I&&!f.destroyed&&Z(f,500,"lane doc upgrade failed")}).finally(()=>d.delete(f))};return t.on("upgrade",E),{async close(){w=!0,t.off("upgrade",E);for(let f of[...p.keys()])b(f);await new Promise(f=>{if(r.size===0&&d.size===0){f();return}let S=r.size+d.size,L=()=>{S-=1,S<=0&&f()};for(let m of r)m.once("close",L);for(let m of d)m.once("close",L);for(let m of r)m.close(1001,"lane doc host shutting down");for(let m of d)m.destroy()}),s.clear(),o.clear(),l.clear()},roomDoc(h,f){return et(`${h}/${f}`,!0)},isHosted(h){return i(h)>0},onHostedChange(h,f){let S=l.get(h);return S||(S=new Set,l.set(h,S)),S.add(f),f(i(h)>0),()=>{S.delete(f)}},closeLane(h){if(T.set(h,!0),T.size>c){let f=T.keys().next().value;f!==void 0&&T.delete(f)}b(h);for(let f of A.get(h)??[])f.close(1001,`lane ${h} retired \u2014 the app's release moved`)}}}import ys from"ws";import ws from"ioredis";U();var Te="/inference-usage",kn=25e3;var gs=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function En(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=gs.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 Oe=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Te}`,s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(kn)})}catch(i){throw new ce(`the uRun usage surface (POST ${Te}) could not be reached within ${kn}ms: ${En(i)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new P("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!s.ok){let i=await s.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new ce(`the uRun usage surface (POST ${Te}) answered HTTP ${s.status} (${a})`)}let o;try{o=await s.json()}catch(i){throw new ce(`the uRun usage surface (POST ${Te}) answered HTTP ${s.status} with a body that is not JSON: ${En(i)}`)}return _t(o,this.opts.onRejectedRow)}};var bs=5e3,vs=1e3,_s=1500,Ss=3e3,ks="/api/client-tokens";function Pe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Rn(t,e,n,r){Pe(t,e,{error:{message:n,type:r}})}async function Es(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${ks}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Ss)});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 Ai(t){let e=t.resolver??new ne({gatewayUrl:t.baseUrl}),n=t.machine?new me({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new ye({issuers:t.userIssuers,gatewayUrl:t.baseUrl}):null,s=new he(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,i=null,a=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let u=new ws(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),y=Ht({redis:u});return{registry:hn({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:on({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(k,C)=>o?.onHostedChange(k,C)??(()=>()=>{}),roomDoc:(k,C)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(k,C)},metrics:s,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(k,C)=>y.rows().then(x=>{let W=st(x,C);return W?.warm_wait_s!==void 0?W.warm_wait_s*1e3:void 0}),currentReleaseOf:gn(u),closeLane:k=>o?.closeLane(k)}),catalog:y,redis:u}})(),l=t.registry??new ve({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),p=t.probeControlPlane??(()=>Es(t.baseUrl)),d=async()=>{let u=null;for(let k of l.decisionPools()){u=k;break}if(!u)return null;let y=u.stats();if(y.some(k=>k.draining))return{ok:!1,detail:"decision pool draining"};if(y.every(k=>k.attached===0&&k.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let R=await u.pingReady(_s);return{ok:R,detail:R?"a decision slot answered its session ping":"no decision slot answered its session ping"}},_=t.usageClient??new Oe({apiUrl:t.apiUrl}),A=t.ledgerClient??new ke({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),T=process.env.URUN_SHARED_ORG_ID?.trim(),c=process.env.URUN_SHARED_ORG_API_KEY?.trim();T&&c&&(async()=>{try{await l.decisionWarmerFor({orgId:T,apiKey:c})?.warmFor(Ut)}catch(u){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(u instanceof Error?u.message:u)}
|
|
17
|
+
`)}})();let w=async u=>We(we(u.headers.authorization),e,n,r),v=async u=>{let y=await w(u);if(y.billingAudience==="platform"&&y.creditsAdmissionOk===!1){let R=y.creditsRefusalReason;throw new z(R==="spend_cap_reached"||R==="insufficient_credits"?R:void 0)}return y},g=u=>u instanceof P?{status:u.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:u instanceof z?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...u.code!==void 0?{code:u.code}:{}}:u instanceof B?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:u.detail}:null,b={write:(u,y)=>A.write(we(u.headers.authorization),y),observe:u=>s.observeLedger(u),...t.ledgerLog?{report:t.ledgerLog}:{}},E=Tt({clients:async u=>l.clientsFor(await v(u)),usage:{authorize:u=>we(u.headers.authorization),lookup:(u,y)=>_.lookup(u,y)},statusOf:g,...t.requestLog?{requestLog:t.requestLog}:{},observe:u=>s.observe(u),ledger:b}),h=nn({authorize:async u=>{await v(u)},...t.lane?{secret:t.lane.tokenSecret}:{}}),f=null,S=null,L=ms((u,y)=>{let R=new URL(u.url??"/","http://localhost");(async()=>{if(u.method==="GET"&&R.pathname==="/healthz"){Pe(y,200,{ok:!0});return}if(u.method==="GET"&&R.pathname==="/readyz"){let x=Date.now();if((!f||x-f.at>=bs)&&(f={at:x,...await p()}),!S||x-S.at>=vs){let j=await d();S=j===null?{at:x,ok:!0,detail:null}:{at:x,ok:j.ok,detail:j.detail}}let W=(f?.ready??!1)&&S.ok,G=S.detail===null?f?.detail??"control plane not yet probed":`${f?.detail??"control plane not yet probed"}; ${S.detail}`;Pe(y,W?200:503,{ok:W,control_plane:G});return}if(u.method==="GET"&&R.pathname==="/lanez"){Pe(y,200,{pools:a?await a.registry.status():null});return}let k=R.pathname==="/v1"||R.pathname.startsWith("/v1/"),C=R.pathname.startsWith("/partners/");if(!k&&!C){Rn(y,404,`no route for ${u.method} ${R.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}await h(u,y)||E(u,y)})().catch(k=>{if(!y.headersSent){Rn(y,500,String(k instanceof Error?k.message:k),"proxy_error");return}y.end()})}),m=t.conversations??new _e({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),I=new WeakMap,O=[it(L,{authenticate:async u=>{let y=await We(u,e,n,r),R=m.connectionFor(y);return{clients:R.clients,scope:be(y.apiKey),onBindResumeHandle:R.bindResumeHandle,clientsForResume:R.clientsForResume,release:R.release}}}),ut(L,{clients:async u=>l.clientsFor(await v(u)),statusOf:g}).close,ht(L,{resolver:{resolve:async(u,y,R)=>{let k=await v(u),C=m.connectionFor(k,wt(u)),x;try{x=await bt(gt(C.clients,t.realtimeCompanions),mt(u),y,yt(u),R)}catch(j){throw C.release().catch(()=>{}),j}let W=x.release,G={...x,release:async()=>{await W?.(),await C.release()}};return I.set(G,k.orgId),G}},onSessionEnded:u=>{At({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:at(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:u.binding.model??null,stream:null,org:I.get(u.binding)??null,duration_ms:u.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:u.connected_ms/1e3,session_id:u.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:u.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:b,req:u.req})}})];if(t.lane&&a){let u=t.lane,y=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=Sn(L,{verifyToken:(k,C)=>De(k,C,u.tokenSecret,void 0,y),selfAddress:u.selfAddress,laneTenantOf:k=>a.redis.get(`lane_tenant:${k}`),onLaneTenantMissing:()=>s.observeLaneDocTenantMissing(),previousTokenSecret:y,hostRegistry:{setHost:(k,C)=>a.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${k}`,C,String(_n)),delHost:k=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${k}`,u.selfAddress)}}),i=pn(L,{verifyToken:(k,C)=>De(k,C,u.tokenSecret,void 0,y),selfAddress:u.selfAddress,hostOf:async k=>{let C=await a.redis.get(`lane_hosts:${k}`);return C&&C.trim()!==""?C.trim():null},podToPodDial:(k,C,x)=>new Promise((W,G)=>{(async()=>{let j=await a.redis.get(`lane_tenant:${k}`),Ln=ee(k,u.tokenSecret,void 0,void 0,j||void 0),In=`ws://${x}/stream/${encodeURIComponent(k)}/${encodeURIComponent(C)}?token=${encodeURIComponent(Ln)}`,Ce=new ys(In,Ie(C));Ce.once("open",()=>W(Ce)),Ce.once("error",G)})().catch(G)})});let R=a;O.push(async()=>{await o.close(),await i.close(),await R.registry.close(),R.redis.quit().catch(()=>{})})}L.on("upgrade",(u,y)=>{let R=new URL(u.url??"/","http://localhost");R.pathname===ot||R.pathname===dt||R.pathname===pt||o!==null&&R.pathname.startsWith("/doc/")||i!==null&&R.pathname.startsWith("/stream/")||y.destroyed||(y.write(`HTTP/1.1 404 Not Found\r
|
|
18
|
+
Connection: close\r
|
|
19
|
+
\r
|
|
20
|
+
no WS route for ${R.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let $=async()=>{for(let u of O)await u();await m.detachAll()};return{server:L,metricsServer:Mt(s),metrics:s,edgeIdentityServer:Bt(),registry:l,closeAll:()=>l.closeAll(),closeWebSockets:$}}async function Ui(t,e,n){n&&await n();let r=new Promise(s=>t.close(()=>s()));t.closeAllConnections(),await r,await Lt()||It(),await e()}export{Os as a,Dt as b,fe as c,On as d,Pn as e,Cn as f,xn as g,Hn as h,pe as i,he as j,Mt as k,xs as l,Mn as m,Wn as n,Fn as o,Bn as p,Wt as q,Gn as r,jn as s,Jn as t,Bt as u,P as v,B as w,we as x,Zn as y,er as z,ne as A,sr as B,Fe as C,Gs as D,js as E,ar as F,be as G,ve as H,Vt as I,lr as J,Be as K,_e as L,ur as M,fr as N,Se as O,M as P,vr as Q,ke as R,bs as S,Ss as T,Ai as U,Ui as V};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();import{gcRequest as w}from"@urun-sh/core/internal";i();var v="llm-resp";async function*h(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let c=typeof a.index=="number"?a.index:0,u=n.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield y(r);return}}}async function*g(e,t){let o=`${v}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*h(t,e.stream(o).messages())}finally{try{w(e.doc("llm"),t)}catch{}}}i();var k=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=f(t,o,this.consumerId);return this.write(n),g(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=_(t,o,n,this.consumerId);return this.write(s),g(this.session,n)})}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{_ as a,f as b,y as c,h as d,g as e,k as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as r}from"./chunk-
|
|
1
|
+
import{f as r}from"./chunk-G6AFKOVS.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(t,n){this.transport=new r(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=a(),i=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*i})(),{requestId:n})}}};export{o as a};
|