@urun-sh/openai 0.6.49 → 0.6.50

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.
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-C452ZIU5.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.49";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)}
1
+ import{h as m}from"./chunk-C452ZIU5.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.50";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
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
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
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}
@@ -0,0 +1,4 @@
1
+ import{a as te}from"./chunk-CAR4AEQJ.js";import{e as pe,f as W,g as fe,h as me}from"./chunk-V6WQRPUO.js";import{c as ee,f as V,g as ne,p as oe}from"./chunk-64VO62LW.js";import{a as ge,b as G}from"./chunk-XGAF2NDT.js";import{c as ue}from"./chunk-6WTMEJZS.js";import{a as H}from"./chunk-Q3AIBMET.js";import{b as Z,d as j}from"./chunk-PXV7QBSD.js";import{b as se,c as re,d as ie,g as ae,j as F,m as B,n as _,o as ce,r as R,s as L,t as de,u as le}from"./chunk-C452ZIU5.js";import{c as b}from"./chunk-YSFSRI3D.js";b();import{App as J,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Be,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as We,SessionFailedError as z}from"@urun-sh/core";b();import{SessionFailedError as _e}from"@urun-sh/core";var q=2;function Le(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Te(e){let t=e?.type;return t==="response.completed"||t==="error"}function ye(e){return async function(r,i){let a=await e.sessionFor(r.model);return(async function*(){for(let l=1;l<=q;l++){let{app:g,entry:y,identity:S}=l===1?a:await e.sessionFor(r.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:S});let p=!1,u=!1;try{let f=await e.createStream(y,r);for await(let m of f){if(Te(m)&&(p=!0),Le(m)){if(l>1)continue}else u=!0;yield m}}catch(f){if(f instanceof _e&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,f)}catch{}throw f}if(l<q&&!u){await e.evict(g,y);continue}throw f}if(p)return;if(l<q&&!u){await e.evict(g,y);continue}return}})()}}import{randomUUID as Oe}from"crypto";b();import{request as Fe}from"http";var Re="/pooler/v1/inference",k=class extends Error{constructor(r,i,a,c){super(a);this.status=r;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Me=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let t=e.messages?.find(r=>r.role==="system"||r.role==="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content)},Ne=e=>{let t=e.messages?.find(r=>r.role!=="system"&&r.role!=="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let r=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(r===void 0)return;if(typeof r=="string")return r;if(r!==null&&typeof r=="object"&&"content"in r){let i=r.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(r)}},he=e=>new Promise((t,r)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>t(Buffer.concat(i).toString("utf8"))),e.on("error",r)}),De=async e=>{let t="pooler_error",r=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await he(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"&&(t=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(r=a.message)}}catch{}return new k(e.status,t,r,e.retryAfterSeconds)};async function xe(e,t,r,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Re}`),l=JSON.stringify({region:e.region,model:i,request_id:r,streaming:a,payload:t,affinity:{systemPrompt:Me(t),firstMessage:Ne(t)}});return new Promise((g,y)=>{let S=Fe({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))}},p=>{let u=Number(p.headers["retry-after"]??"");g({status:p.statusCode??0,retryAfterSeconds:Number.isFinite(u)?u:void 0,body:p})});S.on("error",p=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${p.message}`))),S.end(l)})}var we=e=>{if(!e.startsWith("data: "))return null;let t=e.slice(6).trim();if(t===""||t==="[DONE]")return null;let r;try{r=JSON.parse(t)}catch{return null}if(r===null||typeof r!="object")return null;let i=r;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*Ce(e){let t="";for await(let i of e.body)for(t+=String(i);;){let a=t.indexOf(`
2
+
3
+ `);if(a===-1)break;let c=t.slice(0,a);t=t.slice(a+2);let l=we(c);l!==null&&(yield l)}let r=we(t);r!==null&&(yield r)}async function on(e,t,r,i){let a=Z(t,r,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await xe(e,a,r,c,t.stream===!0);if(l.status>=400)throw await De(l);let g=t.stream===!0?j(r,Ce(l)):await Ue(l,r);return(async function*(){yield{type:"response.created",response:{id:`resp_${r}`,status:"in_progress"}},yield*g})()}async function Ue(e,t){let r=await he(e.body),i=null;try{let c=JSON.parse(r);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 j(t,(async function*(){yield a})())}b();import{encodeStreamEnvelope as Se}from"@urun-sh/core";var $e="audio";function Pe(e){let t=e.streamEndpoint($e);return{sessionId:e.id,appendInputAudio(r,i){let a=Buffer.from(r,"base64");if(a.byteLength!==0){if(i===void 0){t.send(Se(new Uint8Array(a)));return}t.send(Se({pcm16:r,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}b();import{encodeStreamEnvelope as je}from"@urun-sh/core";var Ve="rt-video-in";function ve(e){let t=e.streamEndpoint(Ve);return{sendInputFrame:async r=>{t.send(je(r))}}}var Ge=0,qe=4,Je=4;function Fn(e,t){let r=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let S=Number.parseInt(y,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):Ge;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=r("URUN_DECISION_POOL_MAX",Math.max(a,qe));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:r("URUN_DECISION_POOL_INFLIGHT_CAP",Je),replicaId:(e.URUN_REPLICA_ID??"").trim()||t||"proxy"}}function Rn(e){let t=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!t)return W;let r=Number.parseInt(t,10);if(!Number.isInteger(r)||r<=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 r*1e3}function K(e,t,r,i){let a=e[r];if(typeof a!="function")throw new Error(`app "${t}" has no function "${r}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${t}" function "${r}" returned a session without end()`);return c}function ke(e,t,r,i){let{baseUrl:a,orgId:c,auth:l}=e,g=t.fnName??e.fnName,y=e.sessionStartOptions?.(r),S={...t.sharedApp?{sharedApp:!0}:{},...y,...i,presenceIdleMs:3e4},p=h=>({session:h,responses:new H(h),gone:ge(h,r)});if(l.lane==="jwt"){let h=J(t.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return p(K(h,t.appSlug,g,S))}if(l.lane==="machine"||l.lane==="user"){let h=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:I}=l,C=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),T=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(h,{baseUrl:I,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:C,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(T,t.appSlug,g,S))}let{apiKey:u,gatewayUrl:f}=l,m=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),w=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(u,{baseUrl:f,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:m,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(w,t.appSlug,g,S))}function Ie(e){let t=e.session.id;if(typeof t!="string"||t.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 t}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let t=e.status.error?.httpStatus,r=e.status.error?.code;return t===410||t===409&&(r==="cancelled"||r==="expired")?!0:r==="client_ended"}var Ke=new Set(["error","paused"]);function Mn(e){let{auth:t,catalog:r}=e,i=null,a=(l,g)=>{let y=ke(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 le({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:t.lane==="api-key"?()=>ce({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:e.catalogRows??(r?()=>te(r):null),listPrices:r?()=>ie(r):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return se(l)}:t.lane==="api-key"?()=>re({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,sessionKey:Ie});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},L({appSlug:e.defaultApp}))),c}function Nn(e,t){let r=e.decisionPool;if(!r)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=r.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=p=>{process.stderr.write(`[decision-pool] ${p}
4
+ `)},y=(p,u)=>{let f=a.get(u);if(f)return f;let m=new pe({min:r.min,max:r.max,idleGraceMs:r.idleGraceMs,inFlightCap:r.inFlightCap,replicaId:i,onLease:w=>w.session.activity?.(),openSlot:async w=>{let h=ke(e,p,u,{concurrencyKey:w.concurrencyKey});return h.gone.onGone(I=>I.bindingLost?m.evict(h):m.markSessionDead(h)),await x(h.session),g(`slot attached pool=${u} slot=${w.concurrencyKey} session=${h.session.id??"(no id)"}`),h},closeSlot:async w=>{w.gone.dispose(),w.audioDispose?.(),await w.session.end()},onDetach:(w,h)=>g(`slot detached pool=${u} slot=${w.concurrencyKey} reason=${h}`),terminalOpenFailure:w=>w instanceof z&&X(w)});return c.set(u,{target:p,env:r}),a.set(u,m),m},S=async(p,u)=>{let f=c.get(u);if(f)try{let m=await t.poolTuningFor(p);y(p,u).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=${u} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let p={appSlug:e.defaultApp};await y(p,L(p)).boot()},async sessionFor(p){let u=await t.resolveTargetFor(p),f=L(u),m=y(u,f);await S(u,f);let w=await m.acquire({timeoutMs:m.requestWaitMs}),h=l.get(w.entry)??[];return h.push(w),l.set(w.entry,h),{app:f,entry:w.entry,identity:de(u)}},async warmFor(p){let u=await t.resolveTargetFor(p);await y(u,L(u)).boot()},end(p){let u=l.get(p)?.shift();u&&(l.get(p)?.length===0&&l.delete(p),u.release())},evict(p){for(let u of a.values())u.evict(p)},markSessionDead(p){for(let u of a.values())u.markSessionDead(p)},reap(){for(let[p,{target:u}]of c)S(u,p).then(()=>{let f=a.get(p);f&&f.reap()})},async pingReady(p){for(let u of a.values())if(await u.pingReady(p))return!0;return!1},stats(){return[...a.entries()].map(([p,u])=>({poolKey:p,...u.stats()}))},async drain(p){await Promise.all([...a.values()].map(u=>u.drain({timeoutMs:p})))},async close(){await Promise.all([...a.values()].map(p=>p.close()))}}}function ze(e){return We(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:Be:be}async function x(e,t){let r=e.whenLive;if(typeof r!="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 r.call(e,{timeout:ze(e.phase),signal:t})}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 Ae(e){let t=e.phase?.name;if(t==="live"||t==="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 D(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Dn(e,t=ne,r,i,a=W,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,S=new WeakMap,p=new Map,u=new WeakMap,f=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},m="lane",w=n=>{let s=_(n);if(!c||!s||s.app!==m)return null;let o=c.entryFor(s.key);if(!o)throw new F(`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:o}},h=async n=>w(n)?.entry??(await e.sessionForHandle(n)).entry,I=n=>{let s=l.get(n);if(!s){let o={waiting:0,gone:new AbortController};u.set(n,o),s=(async()=>{if(await x(n.session,o.gone.signal),o.gone.signal.aborted)throw D(o.gone.signal);u.get(n)===o&&u.delete(n);let d=await ee(n.session,await t());return Object.assign(d,{sessionId:n.session.id})})(),l.set(n,s),s.then(d=>{l.get(n)===s&&(n.audioDispose=()=>d.dispose())},()=>{}),s.catch(()=>{l.get(n)===s&&l.delete(n)}),s.then(()=>{u.get(n)===o&&u.delete(n)},()=>{u.get(n)===o&&u.delete(n)})}return s},C=n=>{let s=S.get(n);return s||(s=(async()=>{let o=await I(n);return{appendInputAudio:(d,v)=>o.appendInputAudio(d,v),onOutputAudio:d=>o.onOutputAudio(d),sessionId:f(n)}})(),S.set(n,s),s.catch(()=>{S.get(n)===s&&S.delete(n)})),s},T=async(n,s,o,d=!1)=>{let v=()=>d?Ae(n.session):Xe(n.session);if(o?.aborted){let O=u.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await v().catch(()=>{}),D(o)}let E=s(n),P=u.get(n);return P!==void 0&&P.waiting++,o===void 0?E:new Promise((O,A)=>{let Q=()=>{P!==void 0&&--P.waiting===0&&u.get(n)===P&&(P.gone.abort(),u.delete(n),l.delete(n),S.delete(n),v().catch(()=>{})),A(D(o))};o.addEventListener("abort",Q,{once:!0});let Y=()=>o.removeEventListener("abort",Q);E.then($=>{Y(),O($)},$=>{Y(),A($)})})},U=async(n,s,o)=>{try{return await o}catch(d){throw(d instanceof F||d instanceof z&&X(d))&&(e.evict(n,s),d instanceof z&&r?.(n,d.kind==="never-live"?"never-live":"create-failed")),d}};return{createResponse:ye({sessionFor:c?async n=>{let s=await e.resolveTargetFor(n);if(s.sharedApp)try{let o=await c.sessionFor(n,s);return{app:o.app,entry:o.entry,identity:o.identity}}catch(o){if(o instanceof ue)return i?i.sessionFor(n):e.sessionFor(n);if(o instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${o.name} ${o.code}: ${o.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw o}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>f(n),evict:(n,s)=>{c&&c.owns(s)?c.evict(s):i?i.evict(s):e.evict(n,s)},onAdmissionVerdict:(n,s,o)=>{X(o)&&(c&&c.owns(s)?c.evict(s):i?i.markSessionDead(s):e.evict(n,s),r?.(n,o.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>{try{await x(n.session);let o=fe(G(await n.responses.responses.create(s),n.gone),a);if(!i&&!c)return o;let d=n;return(async function*(){try{yield*o}catch(E){throw me(E)&&(c&&c.owns(d)?c.evict(d):i&&(E instanceof F&&!E.bindingLost?i.markSessionDead(d):i.evict(d))),E}finally{c&&c.owns(d)?c.release(d):i?.end(d)}})()}catch(o){throw c&&c.owns(n)?c.release(n):i&&i.end(n),o}}}),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:o,entry:d}=await e.sessionFor(n);return await U(o,d,T(d,I,s))},openAudioOn:async(n,s,o,d)=>{let v=w(n);if(v){let A=v.entry.session;return Pe(A)}let{app:E,entry:P}=await e.sessionForHandle(n);if(d&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;d({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=_(n)?.app.startsWith(R)??!1;return await U(E,P,T(P,C,s,O))},openTurnsOn:async function*(n,s){if(s?.aborted)throw D(s);let o=await h(n);yield*ae(o.session,s)},openVideoOn:async n=>{let s=w(n);if(s)return ve(s.entry.session);let{entry:o}=await e.sessionForHandle(n),d=g.get(o);return d||(d=V(o.session),g.set(o,d)),d},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),o=g.get(s);return o||(o=V(s.session),g.set(s,o)),o},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),o=y.get(s);return o||(o=oe(s.session),y.set(s,o)),o},sessionHandle:async n=>{if(c){let s=await e.resolveTargetFor(n);if(s.sharedApp){let o=await c.sessionFor(n,s),d=f(o.entry);if(d===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return B(m,d)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:o,entry:d}=await e.dedicatedSessionFor(n);return B(o,Ie(d))},touchSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);o||(o=new Map,p.set(n,o)),o.set(s,Date.now());let d=null;try{d=await h(n)}catch{return}d.session.activity?.()})()},detachSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);if(o?.delete(s),o&&o.size===0&&p.delete(n),o&&o.size>0)return;let d=null;try{d=await h(n)}catch{return}d.session.presenceDetach?.()})()},releaseSessionHandle:n=>{let s=_(n);if(!s)return;if(s.app.startsWith(R)){(async()=>{let d=null;try{d=(await e.sessionForHandle(n)).entry}catch{return}await Ae(d.session).catch(()=>{}),await e.evict(s.app,d)})();return}if(!c||s.app!==m)return;let o=c.entryFor(s.key);o&&c.release(o)},endDedicatedSession:async n=>{let s=_(n);if(!s||!s.app.startsWith(R))return;let o=null;try{o=(await e.sessionForHandle(n)).entry}catch{return}if(typeof o.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let d=await o.session.end();return await e.evict(s.app,o),d},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:o}=await e.sessionForHandle(n);await e.evict(s,o)},createResponseOn:async(n,s,o)=>{let d=await h(n);await x(d.session);let v=o!==void 0&&w(n)?new H({...d.session,consumerId:o},{sessionTag:o}):d.responses;return G(await v.responses.create(s),d.gone)},onSessionEnd:async(n,s)=>{let o=w(n);if(o)return o.entry.gone.onGone(P=>s({timeLeftMs:null,reason:P.message}));let{entry:d}=await e.sessionForHandle(n),v=d.session;if(typeof v.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return v.onPhase(P=>{if(E||!Ke.has(P.name))return;E=!0;let O=v.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,Fn as c,Rn as d,Mn as e,Nn as f,Dn as g};
@@ -0,0 +1,20 @@
1
+ import{a as xe,b as Ut,c as Nt,e as De,f as $t,g as He}from"./chunk-OZVX4WPP.js";import{A as It,B as At,C as Ot,D as Pt,E as Tt,b as at,d as lt,i as ut,j as ft,l as pt,m as gt,n as mt,o as yt,p as wt,q as bt,r as vt,t as _t,u as ce,v as St,w as kt,x as Et,y as Rt,z as Lt}from"./chunk-V6WQRPUO.js";import{a as it}from"./chunk-X5BLQXHK.js";import{a as Dt,e as Ht}from"./chunk-XKKQ2NEZ.js";import{a as Ct}from"./chunk-XGAF2NDT.js";import{a as ct,b as ae,c as dt,o as ht,p as le}from"./chunk-6WTMEJZS.js";import{a as xt,c as ee,e as Me}from"./chunk-XNRPTMSL.js";import{a as rt}from"./chunk-Q3AIBMET.js";import{e as st,j as oe,p as ot,q as ie,r as $e}from"./chunk-C452ZIU5.js";import{c as O}from"./chunk-YSFSRI3D.js";O();import{Counter as J,Gauge as de,Histogram as ue,Registry as On,collectDefaultMetrics as Pn}from"@prometheus-io/client";import{createServer as Tn}from"http";var Us=9464,Mt="/metrics",fe="(other)",Un="(none)",Cn=64,Nn=128,$n=["/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",_t,kt,st],xn=new Set($n);function Dn(t){return xn.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 he=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Un: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}},pe=class{registry=new On;modelLabel=new he(Cn);orgLabel=new he(Nn);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 Et)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"},Rt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Lt()/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&&Pn({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=Dn(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),a=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:a}),this.duration.observe({lane:n,stream:l,model:o,org:a},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:a},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 Wt(t){return Tn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Mt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Mt}
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()})})}O();import{createHash as Bt}from"crypto";import{createServer as Mn}from"http";var Ds=9465,Wn="x-urun-key-id",Fn="x-urun-key-fingerprint",Bn="urun-ratelimit-bucket:",Kn="urun-ratelimit-tier:",Ft="anonymous",Gn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function jn(t){return Bt("sha256").update(`${Bn}${t}`).digest("hex")}function Jn(t){return Bt("sha256").update(`${Kn}${t}`).digest("hex")}function zn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Gn.test(n)?n:null}function Kt(){return Mn((t,e)=>{let n=zn(t.headers.authorization);e.setHeader(Wn,n===null?Ft:jn(n)),e.setHeader(Fn,n===null?Ft:Jn(n)),e.writeHead(200),e.end()})}O();import{createClientToken as qn,ClientTokenError as Gt}from"@urun-sh/core";import{createPublicKey as Vn,verify as Yn}from"crypto";var jt="urun-session-gateway",Qn="machine",Xn=3e5;function zt(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var U=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 U("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 U("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Zn=60,er=6e4,tr=4096;function nr(t){return t===401||t===403}var ne=class{constructor(e){this.opts=e;this.mint=e.mint??qn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new U("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<er)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 a=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Zn});s=a.orgId,o={...a.billingAudience!==void 0?{billingAudience:a.billingAudience}:{},...a.creditsAdmissionOk!==void 0?{creditsAdmissionOk:a.creditsAdmissionOk}:{},...a.creditsRefusalReason!==void 0?{creditsRefusalReason:a.creditsRefusalReason}:{}}}catch(a){throw a instanceof Gt&&a.status===402?(this.cache.delete(e),new z(a.code==="spend_cap_reached"||a.code==="insufficient_credits"?a.code:void 0)):a instanceof Gt&&nr(a.status)?(this.cache.delete(e),new U(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}: ${a instanceof Error?a.message:String(a)}`)}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>=tr){let a=this.cache.keys().next();a.done||this.cache.delete(a.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<Xn)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 a=await o;return this.entries.set(e,{keys:a,at:this.now()}),a}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 qt(t,e,n){try{let r=Vn({key:n,format:"jwk"});return Yn("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 U("malformed machine token");let o,a;try{o=te(n),a=te(r)}catch{throw new U("malformed machine token")}if(o.alg!=="RS256")throw new U(`machine token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new U(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(a.aud!==jt)throw new U(`machine token audience must be ${jt} (got ${JSON.stringify(a.aud??null)})`);if(a.token_use!==Qn)throw new U(`bearer is a ${JSON.stringify(String(a.token_use??""))} token, not a machine token`);let p=typeof a.org_id=="string"?a.org_id:"";if(p==="")throw new U("machine token carries no org_id \u2014 no tenancy to route by");let f=typeof a.exp=="number"?a.exp:0;if(f<=Math.floor(this.now()/1e3))throw new U("machine token is expired \u2014 re-mint and retry");let b=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,i);if(b===void 0)throw new U(`machine token kid ${JSON.stringify(i)} is not in the machine issuer's JWKS`);let A=Buffer.from(`${n}.${r}`,"ascii"),P=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!qt(A,P,b))throw new U("machine token signature failed verification");if(f<=Math.floor(this.now()/1e3))throw new U("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:p,credential:"machine"}}},rr="https://api.workos.com/sso/jwks/";function sr(t){return`${rr}${t.slice(t.lastIndexOf("/")+1)}`}var We=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(!zt(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 U("malformed user token");let o,a;try{o=te(n),a=te(r)}catch{throw new U("malformed user token")}if(o.alg!=="RS256")throw new U(`user token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new U(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let p=typeof a.org_id=="string"?a.org_id:"";if(p==="")throw new U("user token carries no org_id \u2014 no tenancy to route by");let f=typeof a.exp=="number"?a.exp:0;if(f<=Math.floor(this.now()/1e3))throw new U("user token is expired \u2014 re-authenticate and retry");let b=await this.cache.keyFor(sr(l),i);if(b===void 0)throw new U(`user token kid ${JSON.stringify(i)} is not in the WorkOS issuer's JWKS`);let A=Buffer.from(`${n}.${r}`,"ascii"),P=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!qt(A,P,b))throw new U("user token signature failed verification");if(f<=Math.floor(this.now()/1e3))throw new U("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 We({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 U("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 Fe(t,e,n,r){if(zt(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}O();var or=8080,Be="serve",js="0.0.0.0";function ir(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===""?or:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=ht(le(ir(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`,a=(t.URUN_CATALOG_URL??"").trim(),i=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!a!=!!i)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=a?{catalogUrl:le(a,"URUN_CATALOG_URL"),anonKey:i}:null,p=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),f=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!p!=!!f)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 b=p?{keyId:f,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()},P=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],c=P.filter((u,y)=>Object.values(A)[y]==="");if(c.length!==0&&c.length!==P.length)throw new Error(`${P.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()},S=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=S.filter((u,y)=>Object.values(v)[y]==="");if(g.length!==0&&g.length!==S.length)throw new Error(`${S.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let k=g.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()},d=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],_=d.filter((u,y)=>Object.values(h)[y]==="");if(_.length!==0&&_.length!==d.length)throw new Error(`${d.join(", ")} must be set together (or all left unset) \u2014 missing: ${_.join(", ")}, which would half-configure the machine-identity rung`);let E=h.issuers.split(",").map(u=>u.trim()).filter(u=>u!=="");if(E.length===0&&_.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(_.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=_.length===0?{jwksBaseUrl:h.jwksBaseUrl,issuers:E,tokenTtlS:m}:void 0,T=(t.URUN_WORKOS_ISSUERS??"").trim(),$=T.split(",").map(u=>u.trim()).filter(u=>u!=="");if(T!==""&&$.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:b,lane:w,pooler:k,machine:I,...$.length>0?{userIssuers:$}:{}}}O();import{createHash as ar,randomUUID as Vt}from"crypto";var lr=512;function be(t){return`urun-inference-proxy-${ar("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 a=this.opts.lanes;return Object.assign(Object.create(s),{createResponse:async(i,l)=>{if(a!==void 0&&r!==void 0&&(await r.resolveTargetFor(i.model).catch(()=>null))?.sharedApp)return await s.createResponse(i,l);let p=`px_${Vt()}`;return Ut(o,i,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:Be,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:Nt(process.env,process.env.HOSTNAME)??void 0},r=De(n),s=n.decisionPool?$t(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>=lr;){let s=this.tenants.entries().next();if(s.done)break;let[o,a]=s.value;this.tenants.delete(o),a.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("; ")}`)}},Yt=512,cr=1024,Ke=class extends Error{constructor(){super(`conversation capacity reached (${Yt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function dr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(ie))return{concurrencyKey:e};if(n.startsWith(ie)||n.startsWith($e))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(ie)||n.startsWith($e)||t.set(n,r)}}}function ur(t,e,n,r,s){let o=De({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Be,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",...dr(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,a=this.opts.build?this.opts.build(e,s):ur(this.opts,e,s,o,r);return{id:n,backhaul:a,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 a=this.build(e,n,r);return a.attachments=1,s.set(n,a),a}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Yt;){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 Ke}}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,Vt(),n)),r),a={createResponse:(i,l)=>o().backhaul.clients.createResponse(i,l),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{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(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),dedicatedSessionHandle:i=>{let l=o().backhaul.clients.dedicatedSessionHandle;return l===void 0?o().backhaul.clients.sessionHandle(i):l(i)},releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),endDedicatedSession:i=>o().backhaul.clients.endDedicatedSession?.(i),touchSessionPresence:(i,l)=>o().backhaul.clients.touchSessionPresence?.(i,l),detachSessionPresence:(i,l)=>o().backhaul.clients.detachSessionPresence?.(i,l),createResponseOn:(i,l,p)=>o().backhaul.clients.createResponseOn(i,l,p),onSessionEnd:(i,l)=>o().backhaul.clients.onSessionEnd(i,l)};return a.openAudio=async(i,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(i,l)},a.openVideo=async i=>{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(i)},a.openVideoOut=async i=>{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(i)},a.supportsAudio=async i=>{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(i)},a.supportsSpeech=async i=>{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(i)},a.speechVoices=async i=>{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(i)},a.speechSessionHandle=async i=>{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(i)},a.openAudioOn=async(i,l,p)=>{let f=o().backhaul.clients.openAudioOn;if(f===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 f(i,l,p)},a.openVideoOn=async(i,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(i,l)},a.openTurnsOn=(i,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(i,l)},a.evictSpeechSession=async i=>{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(i)},a.supportsTranscription=async i=>{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(i)},a.transcriptStreamFor=async i=>{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(i)},a.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===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 i()},{clients:a,bindResumeHandle:i=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=cr;){let p=this.byHandle.keys().next();if(p.done)break;this.byHandle.delete(p.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async i=>{let l=this.byHandle.get(i),p=l===void 0?void 0:this.byCaller.get(l.apiKey),f=l===void 0||p===void 0?void 0:p.get(l.conversationId);if(l===void 0||f===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=f,f.attachments+=1,f.backhaul.clients},release:async()=>{if(s)return;s=!0;let i=r;r=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let 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("; ")}`)}};O();var fr="/inference-ledger",hr=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"}},ze=class extends U{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},qe=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",Ge],["output_minutes",Ge],["cost_nano_usd",Ge],["price_version",t=>t===null||typeof t=="string"]];function gr(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 mr(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"}:gr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ge(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function je(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function yr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Qt(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 wr(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&&Qt(t.started_at,n.started_at)&&Qt(t.completed_at,n.completed_at)&&je(t.prompt_tokens,n.prompt_tokens)&&je(t.completion_tokens,n.completion_tokens)&&je(t.output_units,n.output_units)&&yr(t.output_minutes,n.output_minutes)}function br(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 vr(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(br(t)));return{signature:Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function _r(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 f=n[p];if(f===null)return null;if(typeof f!="string")throw new M(`${e} answered a non-string ${p}: ${JSON.stringify(f)}`);if(!/[^\s]/.test(f))throw new M(`${e} answered a BLANK ${p} (${JSON.stringify(f)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return f},a=o("price_version"),i=o("unpriced_reason"),l=s!=null;if(l&&(a===null||i!==null))throw new M(`${e} answered a PRICED row (cost_nano_usd ${String(s)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(a)}, unpriced_reason ${JSON.stringify(i)}`);if(!l&&(a!==null||i===null))throw new M(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(a)}, unpriced_reason ${JSON.stringify(i)}. 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:a,unpriced_reason:i}}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(/\/+$/,"")}${fr}`,s;try{s=this.opts.signing?JSON.stringify({...n,...await vr(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(hr)})}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(()=>""),f=mr(p);throw f.status==="found"&&wr(n,f.row)?new Je(f.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.`):f.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${f.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 ze("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(b=>`<body unreadable: ${b instanceof Error?b.message:String(b)}>`),f;try{let b=JSON.parse(p);if(b!==null&&typeof b=="object"&&"error"in b){let A=b.error;A!==null&&typeof A=="object"&&"code"in A&&(f=A.code)}}catch{}throw f==="ledger_signature_invalid"?new qe(`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 a;try{a=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 i=a?.recorded;if(i===void 0)throw new M(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=_r(i,`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}};O();import{createServer as ys}from"http";O();import{createCipheriv as Sr,createDecipheriv as kr,hkdfSync as Er,randomBytes as Rr,randomUUID as en}from"crypto";import{resolve4 as Lr}from"dns/promises";O();var Xt="/realtime/openai.quic-relay";async function Zt(t){let e=await fetch(`${t.sfuBase}${Xt}${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}${Xt} -> ${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 Ve="/v1/realtime/calls",tn="/v1/realtime/client_secrets",Ir="session-server-ts-pods.urun.svc.cluster.local",nn=8081,Ar="/realtime/openai.relay",Or=262144,Pr=600,Ee={"access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"authorization, content-type","access-control-max-age":"86400"};function rn(t){let e=t.secret===void 0?void 0:Buffer.from(Er("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>$r(await Lr(Ir))),r=(s,o,a,i,l=!1)=>{s.writeHead(o,{"content-type":"application/json",...l?Ee:{}}),s.end(JSON.stringify({error:{message:a,type:"invalid_request_error",...i?{code:i}:{}}}))};return async(s,o)=>{let a=new URL(s.url??"/","http://proxy"),i=a.pathname===Ve;if(s.method==="OPTIONS"&&i)return o.writeHead(204,Ee),o.end(),!0;if(s.method!=="POST"||!i&&a.pathname!==tn)return!1;let l=await Ur(s);if(l===null)return r(o,413,"request body too large",void 0,i),!0;let p=(s.headers.authorization??"").replace(/^Bearer\s+/i,"");if(p.startsWith("ek_")){let g=e===void 0?null:Nr(e,p.slice(3));if(g===null)return r(o,401,"invalid or expired client secret","invalid_api_key",i),!0;s.headers.authorization=`Bearer ${g}`}try{await t.authorize(s)}catch(g){let k=typeof g=="object"&&g!==null&&"status"in g&&typeof g.status=="number"?g.status:401;return r(o,k,g instanceof Error?g.message:String(g),void 0,i),!0}if(a.pathname===tn){if(e===void 0)return r(o,501,"client secrets are not configured on this proxy"),!0;let g=l.length===0?{}:JSON.parse(l.toString("utf8")),k=typeof g=="object"&&g!==null&&"session"in g?g.session:null,h=Math.floor(Date.now()/1e3)+Pr,d=(s.headers.authorization??"").replace(/^Bearer\s+/i,"");return o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({value:`ek_${Cr(e,d,h)}`,expires_at:h,session:k})),!0}if(a.searchParams.get("transport")==="quic"){let g=a.searchParams.get("model");if(g===null)return r(o,400,"model is required (?model=)",void 0,i),!0;let k=`quic_${en().replaceAll("-","")}`,h=new URLSearchParams(a.searchParams);h.set("model",g),h.set("call_id",k);let d="no media edge resolved";for(let _ of await n())try{let E=await Zt({sfuBase:`http://${_}:${nn}`,query:`?${h}`,upstreamHeaders:{authorization:s.headers.authorization??""}});return o.writeHead(201,{"content-type":"application/json",location:`${Ve}/${E.body.callId}`,...i?Ee:{}}),o.end(JSON.stringify(E.body)),!0}catch(E){d=`${_}: ${String(E)}`}return r(o,502,`no media edge accepted the quic call (${d})`,void 0,i),!0}let{sdp:f,session:b}=await Tr(s.headers["content-type"]??"",l);if(f===void 0)return r(o,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)",void 0,i),!0;let A=typeof b=="object"&&b!==null&&"model"in b&&typeof b.model=="string"?b.model:void 0,P=a.searchParams.get("model")??A;if(P===void 0)return r(o,400,"model is required (?model= or session.model)",void 0,i),!0;let c=`rtc_${en().replaceAll("-","")}`,w=new URLSearchParams(a.searchParams);w.set("model",P),w.set("call_id",c);let v=JSON.stringify({sdp:f,...b!==void 0?{session:b}:{}}),S="no media edge resolved";for(let g of await n()){let k;try{k=await fetch(`http://${g}:${nn}${Ar}?${w}`,{method:"POST",headers:{"content-type":"application/json",authorization:s.headers.authorization??""},body:v,signal:AbortSignal.timeout(1e4)})}catch(d){S=`${g}: ${String(d)}`;continue}let h=await k.text();if(k.status===201)return o.writeHead(201,{"content-type":"application/sdp",location:`${Ve}/${c}`,...i?Ee:{}}),o.end(h),!0;if(k.status>=500||k.status===404||k.status===405||k.status===501){S=`${g}: ${k.status} ${h}`;continue}return r(o,k.status,h,void 0,i),!0}return r(o,503,`no media edge answered the offer (${S})`,"media_edge_unavailable",i),!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 Ur(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>Or)return null;e.push(r)}return Buffer.concat(e)}function Cr(t,e,n){let r=Rr(12),s=Sr("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 Nr(t,e){try{let n=Buffer.from(e,"base64url"),r=kr("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:a}=s;return typeof o!="string"||typeof a!="number"?null:a>Date.now()/1e3?o:null}catch{return null}}function $r(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}O();import{SessionAllocationError as qr}from"@urun-sh/core";import{createWebsocketDocConnector as Vr}from"@urun-sh/core/internal";import Yr from"ws";O();import{request as xr}from"http";var Dr="/pooler/v1/lanes/pick",Hr="/pooler/v1/lanes/status",Mr=1e4,re=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function sn(t,e,n,r,s){return new Promise((o,a)=>{let i=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),p=xr({hostname:i.hostname,port:i.port,path:`${i.pathname}${i.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:s},f=>{let b=[];f.on("data",A=>b.push(A)),f.on("end",()=>{let A=Buffer.concat(b).toString("utf8"),P=null;try{P=A===""?null:JSON.parse(A)}catch{P=null}o({status:f.statusCode??0,json:P})}),f.on("error",A=>a(new xe(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",f=>a(new xe(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`))),p.end(l)})}function on(t,e,n,r){if(t===400&&Wr(e)?.code==="lane_target")return new dt(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 Wr(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function an(t){return{async pick({pool:e,app:n,fn:r,sharedApp:s,model:o,holdMs:a=0}){let i=Math.min(Math.max(Math.trunc(a),0),Dt),l=await sn(t,"POST",Dr,{pool:e,app:n,fn:r,model:o,hold_ms:i,...s?{shared_app:!0}:{}},i+Mr);if(l.status!==200)throw on(l.status,l.json,e,o);return(l.json?.lanes??[]).filter(f=>typeof f.lane_id=="string"&&f.lane_id!==""&&typeof f.host=="string"&&f.host!=="").map(f=>({laneId:f.lane_id,host:f.host}))},async status(){let e=await sn(t,"GET",Hr,void 0,5e3);if(e.status!==200)throw on(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}O();import*as q from"yjs";import{SessionDocumentImpl as Fr}from"@urun-sh/core/internal";var Br=3e4;function Kr(t){return(e,n,r)=>{let s=t(e);q.applyUpdate(n,q.encodeStateAsUpdate(s));let o=i=>q.applyUpdate(s,i),a=i=>q.applyUpdate(n,i);return n.on("update",o),s.on("update",a),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",o),s.off("update",a)}}}}function Ye(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Kr(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=f=>{if(s)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let b=r.get(f);return b||(b=new Fr(f,e,n),r.set(f,b)),b},a=new Map,i=f=>{if(s)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let b=a.get(f);if(!b){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${f}"`);b=t.streamEndpoint(f),a.set(f,b)}return b},l=f=>{let b="llm-resp:";if(!f.startsWith(b))throw new Error(`lane session exposes no stream "${f}" \u2014 only the llm reply lanes (${b}<rid>)`);async function*A(){let P=i(f);try{yield*P.messages()}finally{a.delete(f),await P.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(f){return o(f)},stream:l,streamEndpoint:i,async end(){},async whenLive(f){let b=o("llm");if(b.synced===!0)return;let A=f?.timeout??t.whenLiveTimeoutMs??Br;await new Promise((P,c)=>{let w=setTimeout(()=>{v(),c(new Error(`lane ${e} llm doc never synced within ${A}ms`))},A),v=b.onSynced(()=>{clearTimeout(w),f?.signal?.removeEventListener("abort",S),P()}),S=()=>{clearTimeout(w),v(),c(f?.signal?.reason instanceof Error?f.signal.reason:new Error("aborted"))};f?.signal?.addEventListener("abort",S,{once:!0})})},destroy(){s=!0;for(let f of r.values())f.dispose();r.clear();for(let[f,b]of a)a.delete(f),b.close()}}}O();import Re,{WebSocketServer as Gr}from"ws";import{ENVELOPE_KIND as un,STREAM_END as jr,StreamFragmentReassembler as Jr}from"@urun-sh/core";var ln="/stream/";function cn(t){if(!t.startsWith(ln))return null;let e=t.slice(ln.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 Ae(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Le(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>un.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Ie=class{reassembler=new Jr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===jr&&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})}}},Xe=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),a=[...o.peers].filter(i=>i!==r);if(a.length===0){let i=o.pending;i.bytes+s.byteLength>dn&&(i.list.shift(),i.warned||(i.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${dn} bytes)`))),i.list.push({envelope:s,producer:r}),i.bytes+=s.byteLength;return}for(let i of a)i.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 a=o.list.filter(i=>i.producer!==r);o.list=o.list.filter(i=>i.producer===r),o.bytes=o.list.reduce((i,l)=>i+l.envelope.byteLength,0);for(let{envelope:i}of a)r.deliver(i)}detach(e,n,r){let s=`${e}::${n}`,o=this.channels.get(s);if(o){for(let a of[...o.peers])a===r&&o.peers.delete(a);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")}}},dn=8*1024*1024,F=new Xe;function fn(t,e){let n=new Ie,r={send(s){F.deliver(t,e,r,s)},deliver(s){if(!n.isEnded){try{Le(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 zr(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 hn(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,s=new Re(r,Ae(e)),o=new Ie;return s.addEventListener("message",a=>{let i=new Uint8Array(a.data);try{Le(i)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}o.push(o.feed(i))}),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(a){if(Le(a),s.readyState!==Re.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);s.send(a,{binary:!0})},deliver(a){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 Qe(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 Gr({noServer:!0,handleProtocols:(c,w)=>{let v=cn(new URL(w.url??"/","http://localhost").pathname);if(!v)return!1;let S=Ae(v.name);return c.has(S)?S:!1}}),o=new Map,a=new Set,i=!1,l=new Map,p=(c,w,v)=>{r>0&&l.set(c,{at:Date.now(),label:w,reap:v})},f=c=>{let w=l.get(c);w&&(w.at=Date.now())},b=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;b?.unref?.();let A=(c,w,v,S)=>{let g={client:v,upstream:S,laneId:c,name:w};a.add(g);let k=h=>{if(a.delete(g)){l.delete(v),console.warn(`[lane-stream] ${c}/${w}: host-affinity pump torn down (${h})`);for(let d of[v,S])try{(d.readyState===Re.OPEN||d.readyState===Re.CONNECTING)&&d.close(1001,"lane stream pump closed")}catch{}}};if(p(v,`${c}/${w} pump`,()=>{for(let h of[v,S])try{h.terminate()}catch{}k("lease expired")}),n>0){let h=(d,_)=>{let E=!0,m=()=>{E=!0};d.on("pong",m),d.on("message",m);let I=setInterval(()=>{if(!E){console.warn(`[lane-stream] ${c}/${w}: pong timeout on ${_} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${_} dial never sends a close)`),clearInterval(I);try{d.terminate()}catch{}k(`${_} pong timeout`);return}E=!1;try{d.ping()}catch{}},n);I.unref?.();let T=()=>clearInterval(I);d.once("close",T),d.once("error",T)};h(v,"client"),h(S,"host")}v.on("message",h=>{f(v);try{S.send(h,{binary:!0})}catch(d){k(`upstream send failed: ${String(d)}`)}}),S.on("message",h=>{f(v);try{v.send(h,{binary:!0})}catch(d){k(`client send failed: ${String(d)}`)}}),v.on("close",()=>k("client socket closed")),v.on("error",()=>k("client socket error")),S.on("close",()=>k("host socket closed")),S.on("error",()=>k("host socket error"))},P=(c,w,v)=>{let S;try{S=new URL(c.url??"/","http://localhost")}catch{Qe(w,400,"malformed upgrade URL");return}w.on("error",()=>w.destroy());let g=cn(S.pathname);g&&(i||w.destroyed||(async()=>{let k=S.searchParams.get("token")??"",h=null;try{h=k===""?null:await e.verifyToken(k,g.laneId,g.name)}catch{h=null}if(h===null){Qe(w,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let d=await e.hostOf(g.laneId).catch(()=>null);if(d&&d!==e.selfAddress)try{let _=await e.podToPodDial(g.laneId,g.name,d);s.handleUpgrade(c,w,v,E=>{A(g.laneId,g.name,E,_)});return}catch(_){console.warn(`[lane-stream] ${g.laneId}/${g.name}: host dial to ${d} failed (${String(_)}) \u2014 falling back to the local relay`)}}s.handleUpgrade(c,w,v,d=>{let _=zr(d,()=>f(d));if(o.set(d,_),F.attach(g.laneId,g.name,_),p(d,`${g.laneId}/${g.name}`,()=>d.terminate()),n>0){let m=!0,I=()=>{m=!0};d.on("pong",I),d.on("message",I);let T=setInterval(()=>{if(!m){console.warn(`[lane-stream] ${g.laneId}/${g.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(T),d.terminate();return}m=!1;try{d.ping()}catch{}},n);T.unref?.();let $=()=>clearInterval(T);d.once("close",$),d.once("error",$)}d.on("message",m=>{f(d);let I=new Uint8Array(m);try{Le(I)}catch(T){console.warn(`[lane-stream] ${g.laneId}/${g.name}: dropped malformed envelope: ${String(T)}`);return}F.deliver(g.laneId,g.name,_,I),I[1]===un.END&&F.detach(g.laneId,g.name,_)});let E=()=>{o.delete(d),l.delete(d),F.detach(g.laneId,g.name,_)};d.on("close",E),d.on("error",E)})})().catch(()=>{w.destroyed||Qe(w,500,"lane stream upgrade failed")}))};return t.on("upgrade",P),{async close(){i=!0,t.off("upgrade",P),clearInterval(b),l.clear(),F.clear();for(let c of o.values())c.close(1001,"lane stream host shutting down");o.clear();for(let c of a)for(let w of[c.client,c.upstream])try{w.close(1001,"lane stream host shutting down")}catch{}a.clear()}}}function Qr(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new ct(`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 Xr={"prod-usw2":["us-west1"]};function gn(t){let e=t.now??Date.now,n=new Map,r=new Map,s=new Set,o=new Map,a=new Set,i=(c,w,v,S,g,k)=>{let h=v?m=>fn(c,m):m=>hn(c,m,{hostUrl:`ws://${S}/stream/${c}`,token:()=>ee(c,t.tokenSecret,void 0,void 0,k)}),d=v?Ye({laneId:c,roomDoc:m=>t.roomDoc(c,m),streamEndpoint:h}):Ye({laneId:c,streamEndpoint:h,connector:Vr({serverUrl:`ws://${S}/doc`,sessionId:c,token:()=>ee(c,t.tokenSecret,void 0,void 0,k),WebSocketPolyfill:Yr})}),_=v?l(c):Ct(d,`lane:${c}`,{armOnFirstSync:!0}),E={session:d,responses:new rt(d,{sessionTag:null}),gone:_,goneWatch:_,laneId:c,pool:w,inFlight:0,laneSession:d,self:v,host:S??"",mintedRelease:g??"",retireWhenIdle:!1};return n.set(c,E),_.onGone(()=>p(E)),E},l=c=>{let w=null,v=!1,S=new Set,g=h=>{if(!w){w=h;for(let d of[...S])d(h);S.clear()}},k=t.hostedSignal?.(c,h=>{if(h){v=!0;return}v&&g(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),()=>{}):(S.add(h),()=>S.delete(h))},dispose(){k?.(),S.clear()}}},p=c=>{f(c)&&(n.delete(c.laneId),r.delete(c.laneId),c.goneWatch?.dispose(),F.forgetLane(c.laneId))},f=c=>{let w=c.laneId;return typeof w=="string"&&n.get(w)===c},b=c=>{f(c)&&(c.self&&!t.closeLane||(a.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)},P=async(c,w)=>{let v=Qr(w);s.add(v);let S=e();try{let g=await t.laneWarmWaitMsFor?.(c,w)??t.laneColdWakeDefaultMs??0,k;try{k=await t.plane.pick({pool:v,app:w.appSlug,fn:w.fnName??"",model:c,holdMs:g,...w.sharedApp?{sharedApp:!0}:{}})}catch(I){throw I instanceof re?new qr(`lane pick hold expired for ${v}: ${I.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):I}t.metrics?.observeLaneReady(c??"",k.length);let h=await t.currentReleaseOf?.(w)??null,d=new Set(k.map(I=>I.laneId));for(let I of a)d.has(I)||a.delete(I);let E=k.filter(I=>{let T=n.get(I.laneId);return T!==void 0&&h!==null&&T.mintedRelease!==""&&T.mintedRelease!==h&&(T.retireWhenIdle=!0,T.inFlight===0)?(b(T),!1):!a.has(I.laneId)}).map(I=>({laneId:I.laneId,self:I.host===t.selfAddress,host:I.host,region:I.region})).sort((I,T)=>{let $=Xr[t.seatRegion??""]??[],u=new Map($.map((R,C)=>[R,C])),y=$.length===0?0:(I.region!==void 0?u.get(I.region):void 0)??$.length,L=$.length===0?0:(T.region!==void 0?u.get(T.region):void 0)??$.length;return y!==L?y-L:I.self!==T.self?I.self?-1:1:(r.get(I.laneId)??0)-(r.get(T.laneId)??0)})[0];E||A(v,c);let m=n.get(E.laneId);return m?.goneWatch?.gone()&&(p(m),m=void 0),m&&(m.pool!==v||m.self!==E.self||m.host!==E.host)&&(p(m),m=void 0),m||(m=i(E.laneId,v,E.self,E.host,h,w.sharedOrgId??void 0)),m.inFlight+=1,r.set(E.laneId,(r.get(E.laneId)??0)+1),{app:v,entry:m,identity:{kind:"catalog",model_id:w.modelId??c??"",variant:w.variant??""}}}finally{t.metrics?.observeLanePick(c??"",e()-S)}};return{sessionFor(c,w){return P(c,w)},release(c){f(c)&&(c.inFlight=Math.max(0,c.inFlight-1),r.set(c.laneId,c.inFlight),c.inFlight===0&&c.retireWhenIdle&&b(c))},owns(c){return f(c)},entryFor(c){return n.get(c)??null},evict(c){f(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(S=>S.pool)])].sort(),w=await t.plane.status().catch(()=>[]),v=new Map(Zr(w));return Promise.all(c.map(async S=>{let g=v.get(S)??{pool:S,lanes:[],lastDemandAt:null};return{pool:S,lanes:g.lanes,lastDemandAt:g.lastDemandAt,local:[...n.values()].filter(k=>k.pool===S).map(k=>({laneId:k.laneId,inFlight:k.inFlight,self:k.self,host:k.host})),lastRefusalAt:o.get(S)??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 Zr(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}O();var es="urun:node-scheduler:apps:v1";function ts(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function mn(t){return async e=>{let n=ts(e);if(n===null)return null;try{let r=await t.hget(es,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 a=o.trim();return a===""?null:a}catch{return null}}}O();import{WebSocketServer as hs}from"ws";O();import*as wn 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 bn from"lib0/map";import rs from"lodash.debounce";O();var yn=()=>{};var ss=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,os=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,is=0,as=1;var ls=process.env.GC!=="false"&&process.env.GC!=="0",cs=process.env.YPERSISTENCE,Oe=null;if(typeof cs=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Y=new Map,Pe=0,et=1,ds=(t,e,n)=>{let r=N.createEncoder();N.writeVarUint(r,Pe),Q.writeUpdate(r,t);let s=N.toUint8Array(r);n.conns.forEach((o,a)=>se(n,a,s))},Ze=class extends wn.Doc{constructor(e){super({gc:ls}),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},a)=>{let i=r.concat(s,o);if(a!==null){let f=this.conns.get(a);f!==void 0&&(r.forEach(b=>{f.add(b)}),o.forEach(b=>{f.delete(b)}))}let l=N.createEncoder();N.writeVarUint(l,et),N.writeVarUint8Array(l,K.encodeAwarenessUpdate(this.awareness,i));let p=N.toUint8Array(l);this.conns.forEach((f,b)=>{se(this,b,p)})};this.awareness.on("update",n),this.on("update",ds),!1}},tt=(t,e=!0)=>bn.setIfUndefined(Y,t,()=>{let n=new Ze(t);return n.gc=e,Oe!==null&&Oe.bindState(t,n),Y.set(t,n),n}),us=(t,e,n)=>{try{let r=N.createEncoder(),s=X.createDecoder(n);switch(X.readVarUint(s)){case Pe:N.writeVarUint(r,Pe),Q.readSyncMessage(s,r,e,t),N.length(r)>1&&se(e,t,N.toUint8Array(r));break;case et:{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&&Oe!==null&&(Oe.writeState(t.name,t).then(()=>{t.destroy()}),Y.delete(t.name))}e.close()},se=(t,e,n)=>{e.readyState!==is&&e.readyState!==as&&V(t,e);try{e.send(n,r=>{r!=null&&V(t,e)})}catch{V(t,e)}},fs=3e4,vn=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let s=tt(n,r);s.conns.set(t,new Set),t.on("message",i=>us(t,s,new Uint8Array(i)));let o=!0,a=setInterval(()=>{if(!o)s.conns.has(t)&&V(s,t),clearInterval(a);else if(s.conns.has(t)){o=!1;try{t.ping()}catch{V(s,t),clearInterval(a)}}},fs);t.on("close",()=>{V(s,t),clearInterval(a)}),t.on("pong",()=>{o=!0});{let i=N.createEncoder();N.writeVarUint(i,Pe),Q.writeSyncStep1(i,s),se(s,t,N.toUint8Array(i));let l=s.awareness.getStates();if(l.size>0){let p=N.createEncoder();N.writeVarUint(p,et),N.writeVarUint8Array(p,K.encodeAwarenessUpdate(s.awareness,Array.from(l.keys()))),se(s,t,N.toUint8Array(p))}}};var nt="/doc/",Sn=30,ps=1e4,_n="llm";function gs(t){if(!t.startsWith(nt))return null;let e=t.slice(nt.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 kn(t,e){let n=new hs({noServer:!0}),r=new Set,s=new Map,o=new Map,a=h=>s.get(`${h}/${_n}`)??0,i=h=>o.get(h)??0,l=new Map,p=new Map,f=new Set,b=new Set,A=new Map,P=new Map,c=4096,w=!1,v=(h,d,_)=>{let E=a(h)>0,m=i(h),I=m>0,T=`${h}/${d}`,$=s.get(T)??0;_>0?s.set(T,_):s.delete(T);let u=m+_-$;u>0?o.set(h,u):o.delete(h);let y=a(h)>0,L=u>0;if(E!==y){y?S(h):g(h);for(let R of l.get(h)??[])R(y)}I&&!L&&queueMicrotask(()=>{let R=`${h}/`;for(let[C,x]of[...Y.entries()])!C.startsWith(R)||x.conns.size>0||(Y.delete(C),x.destroy())})},S=h=>{if(!e.hostRegistry||p.has(h))return;let d=()=>{e.hostRegistry?.setHost(h,e.selfAddress).catch(()=>{})};d();let _=setInterval(d,ps);_.unref?.(),p.set(h,_)},g=h=>{let d=p.get(h);d&&(clearInterval(d),p.delete(h)),e.hostRegistry&&e.hostRegistry.delHost(h,e.selfAddress).catch(()=>{})},k=(h,d,_)=>{let E;try{E=new URL(h.url??"/","http://localhost")}catch{Z(d,400,"malformed upgrade URL");return}d.on("error",()=>d.destroy()),d.on("close",()=>b.delete(d));let m=gs(E.pathname);if(!m){if(E.pathname.startsWith(nt)){Z(d,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}b.add(d);return}f.add(d);let I=!1;(async()=>{if(P.has(m.laneId)){Z(d,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let T=E.searchParams.get("token")??"",$=null;try{$=T===""?null:await e.verifyToken(T,m.laneId,m.docName)}catch{$=null}if($===null){Z(d,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(d,403,"lane doc token org does not match the lane record");return}}w||d.destroyed||(I=!0,n.handleUpgrade(h,d,_,y=>{f.delete(d),r.add(y),y.on("close",()=>r.delete(y));let L=A.get(m.laneId);L||(L=new Set,A.set(m.laneId,L)),L.add(y),y.on("close",()=>{L.delete(y),L.size===0&&A.delete(m.laneId)});let R=u.scope===xt||u.scope===void 0&&typeof u.app=="string"&&typeof u.fn=="string"&&u.aud==="sfu";if(R){let x=`${m.laneId}/${m.docName}`,W=(s.get(x)??0)+1;v(m.laneId,m.docName,W),W>1&&m.docName===_n&&e.hostRegistry?.setHost(m.laneId,e.selfAddress).catch(()=>{})}y.on("close",()=>{if(!R)return;let x=`${m.laneId}/${m.docName}`;v(m.laneId,m.docName,Math.max(0,(s.get(x)??1)-1))}),vn(y,h,{docName:`${m.laneId}/${m.docName}`,gc:!0})}))})().catch(()=>{!I&&!d.destroyed&&Z(d,500,"lane doc upgrade failed")}).finally(()=>f.delete(d))};return t.on("upgrade",k),{async close(){w=!0,t.off("upgrade",k);for(let d of[...p.keys()])g(d);await new Promise(d=>{if(r.size===0&&f.size===0){d();return}let _=r.size+f.size,E=()=>{_-=1,_<=0&&d()};for(let m of r)m.once("close",E);for(let m of f)m.once("close",E);for(let m of r)m.close(1001,"lane doc host shutting down");for(let m of f)m.destroy()}),s.clear(),o.clear(),l.clear()},roomDoc(h,d){return tt(`${h}/${d}`,!0)},isHosted(h){return a(h)>0},onHostedChange(h,d){let _=l.get(h);return _||(_=new Set,l.set(h,_)),_.add(d),d(a(h)>0),()=>{_.delete(d)}},closeLane(h){if(P.set(h,!0),P.size>c){let d=P.keys().next().value;d!==void 0&&P.delete(d)}g(h);for(let d of A.get(h)??[])d.close(1001,`lane ${h} retired \u2014 the app's release moved`)}}}import ws from"ws";import bs from"ioredis";O();var Te="/inference-usage",En=25e3;var ms=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Rn(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=ms.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 Ue=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(En)})}catch(a){throw new ce(`the uRun usage surface (POST ${Te}) could not be reached within ${En}ms: ${Rn(a)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new U("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 a=await s.text().catch(()=>null),i=a===null?"body unreadable":`${a.length}-character body`;throw new ce(`the uRun usage surface (POST ${Te}) answered HTTP ${s.status} (${i})`)}let o;try{o=await s.json()}catch(a){throw new ce(`the uRun usage surface (POST ${Te}) answered HTTP ${s.status} with a body that is not JSON: ${Rn(a)}`)}return St(o,this.opts.onRejectedRow)}};var vs=5e3,_s=1e3,Ss=1500,ks=3e3,Es="/api/client-tokens";function Ce(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Ln(t,e,n,r){Ce(t,e,{error:{message:n,type:r}})}async function Rs(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Es}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(ks)});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 Oi(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 pe(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,a=null,i=(()=>{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 bs(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),y=Ht({redis:u});return{registry:gn({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:an({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(R,C)=>o?.onHostedChange(R,C)??(()=>()=>{}),roomDoc:(R,C)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(R,C)},metrics:s,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(R,C)=>y.rows().then(x=>{let W=ot(x,C);return W?.warm_wait_s!==void 0?W.warm_wait_s*1e3:void 0}),currentReleaseOf:mn(u),closeLane:R=>o?.closeLane(R)}),catalog:y,redis:u}})(),l=t.registry??new ve({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),p=t.probeControlPlane??(()=>Rs(t.baseUrl)),f=async()=>{let u=null;for(let R of l.decisionPools()){u=R;break}if(!u)return null;let y=u.stats();if(y.some(R=>R.draining))return{ok:!1,detail:"decision pool draining"};if(y.every(R=>R.attached===0&&R.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let L=await u.pingReady(Ss);return{ok:L,detail:L?"a decision slot answered its session ping":"no decision slot answered its session ping"}},b=t.usageClient??new Ue({apiUrl:t.apiUrl}),A=t.ledgerClient??new ke({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),P=process.env.URUN_SHARED_ORG_ID?.trim(),c=process.env.URUN_SHARED_ORG_API_KEY?.trim();P&&c&&(async()=>{try{await l.decisionWarmerFor({orgId:P,apiKey:c})?.warmFor(Pt)}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=>Fe(we(u.headers.authorization),e,n,r),v=async u=>{let y=await w(u);if(y.billingAudience==="platform"&&y.creditsAdmissionOk===!1){let L=y.creditsRefusalReason;throw new z(L==="spend_cap_reached"||L==="insufficient_credits"?L:void 0)}return y},S=u=>u instanceof U?{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,g={write:(u,y)=>A.write(we(u.headers.authorization),y),observe:u=>s.observeLedger(u),...t.ledgerLog?{report:t.ledgerLog}:{}},k=Tt({clients:async u=>l.clientsFor(await v(u)),usage:{authorize:u=>we(u.headers.authorization),lookup:(u,y)=>b.lookup(u,y)},statusOf:S,...t.requestLog?{requestLog:t.requestLog}:{},observe:u=>s.observe(u),ledger:g}),h=rn({authorize:async u=>{await v(u)},...t.lane?{secret:t.lane.tokenSecret}:{}}),d=null,_=null,E=ys((u,y)=>{let L=new URL(u.url??"/","http://localhost");(async()=>{if(u.method==="GET"&&L.pathname==="/healthz"){Ce(y,200,{ok:!0});return}if(u.method==="GET"&&L.pathname==="/readyz"){let x=Date.now();if((!d||x-d.at>=vs)&&(d={at:x,...await p()}),!_||x-_.at>=_s){let j=await f();_=j===null?{at:x,ok:!0,detail:null}:{at:x,ok:j.ok,detail:j.detail}}let W=(d?.ready??!1)&&_.ok,G=_.detail===null?d?.detail??"control plane not yet probed":`${d?.detail??"control plane not yet probed"}; ${_.detail}`;Ce(y,W?200:503,{ok:W,control_plane:G});return}if(u.method==="GET"&&L.pathname==="/lanez"){Ce(y,200,{pools:i?await i.registry.status():null});return}let R=L.pathname==="/v1"||L.pathname.startsWith("/v1/"),C=L.pathname.startsWith("/partners/");if(!R&&!C){Ln(y,404,`no route for ${u.method} ${L.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)||k(u,y)})().catch(R=>{if(!y.headersSent){Ln(y,500,String(R instanceof Error?R.message:R),"proxy_error");return}y.end()})}),m=t.conversations??new _e({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),I=new WeakMap,T=[at(E,{authenticate:async u=>{let y=await Fe(u,e,n,r),L=m.connectionFor(y);return{clients:L.clients,scope:be(y.apiKey),onBindResumeHandle:L.bindResumeHandle,clientsForResume:L.clientsForResume,release:L.release}}}),ft(E,{clients:async u=>l.clientsFor(await v(u)),statusOf:S}).close,gt(E,{resolver:{resolve:async(u,y,L)=>{let R=await v(u),C=m.connectionFor(R,bt(u)),x;try{x=await vt(mt(C.clients,t.realtimeCompanions),yt(u),y,wt(u),L)}catch(j){throw C.release().catch(()=>{}),j}let W=x.release,G={...x,release:async()=>{await W?.(),await C.release()}};return I.set(G,R.orgId),G}},onSessionEnded:u=>{Ot({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:lt(),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:g,req:u.req})}})];if(t.lane&&i){let u=t.lane,y=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=kn(E,{verifyToken:(R,C)=>Me(R,C,u.tokenSecret,void 0,y),selfAddress:u.selfAddress,laneTenantOf:R=>i.redis.get(`lane_tenant:${R}`),onLaneTenantMissing:()=>s.observeLaneDocTenantMissing(),previousTokenSecret:y,hostRegistry:{setHost:(R,C)=>i.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:${R}`,C,String(Sn)),delHost:R=>i.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${R}`,u.selfAddress)}}),a=pn(E,{verifyToken:(R,C)=>Me(R,C,u.tokenSecret,void 0,y),selfAddress:u.selfAddress,hostOf:async R=>{let C=await i.redis.get(`lane_hosts:${R}`);return C&&C.trim()!==""?C.trim():null},podToPodDial:(R,C,x)=>new Promise((W,G)=>{(async()=>{let j=await i.redis.get(`lane_tenant:${R}`),In=ee(R,u.tokenSecret,void 0,void 0,j||void 0),An=`ws://${x}/stream/${encodeURIComponent(R)}/${encodeURIComponent(C)}?token=${encodeURIComponent(In)}`,Ne=new ws(An,Ae(C));Ne.once("open",()=>W(Ne)),Ne.once("error",G)})().catch(G)})});let L=i;T.push(async()=>{await o.close(),await a.close(),await L.registry.close(),L.redis.quit().catch(()=>{})})}E.on("upgrade",(u,y)=>{let L=new URL(u.url??"/","http://localhost");L.pathname===it||L.pathname===ut||L.pathname===pt||o!==null&&L.pathname.startsWith("/doc/")||a!==null&&L.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 ${L.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let $=async()=>{for(let u of T)await u();await m.detachAll()};return{server:E,metricsServer:Wt(s),metrics:s,edgeIdentityServer:Kt(),registry:l,closeAll:()=>l.closeAll(),closeWebSockets:$}}async function Pi(t,e,n){n&&await n();let r=new Promise(s=>t.close(()=>s()));t.closeAllConnections(),await r,await It()||At(),await e()}export{Us as a,Mt as b,fe as c,Un as d,Cn as e,Nn as f,Dn as g,Hn as h,he as i,pe as j,Wt as k,Ds as l,Wn as m,Fn as n,Bn as o,Kn as p,Ft as q,jn as r,Jn as s,zn as t,Kt as u,U as v,B as w,we as x,er as y,tr as z,ne as A,or as B,Be as C,js as D,Js as E,lr as F,be as G,ve as H,Yt as I,cr as J,Ke as K,_e as L,fr as M,hr as N,Se as O,M as P,_r as Q,ke as R,vs as S,ks as T,Oi as U,Pi as V};