@urun-sh/openai 0.6.36 → 0.6.38

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,6 +1,6 @@
1
1
  import { IncomingMessage, Server } from 'node:http';
2
- import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-C6Gw4HfK.cjs';
3
- export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-C6Gw4HfK.cjs';
2
+ import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-F94H40CD.cjs';
3
+ export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-F94H40CD.cjs';
4
4
  export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-CO8W_hmJ.cjs';
5
5
  import { WebSocket } from 'ws';
6
6
  import '../models-D7F0bLJ3.cjs';
@@ -874,7 +874,7 @@ declare function realtimeModelOf(req: IncomingMessage): string | undefined;
874
874
  * and the bridge opens — a refused upgrade admits nothing. On an stt row
875
875
  * the intent is recorded on the binding (a transcription session).
876
876
  */
877
- declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
877
+ declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
878
878
  /**
879
879
  * The LOCAL lane resolver: fixed pooled clients, optional fixed apiKey (the
880
880
  * same shared-secret rule the local Gemini Live lane applies — a mismatched
@@ -1,6 +1,6 @@
1
1
  import { IncomingMessage, Server } from 'node:http';
2
- import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-DAZrZyLN.js';
3
- export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-DAZrZyLN.js';
2
+ import { P as ProxyClients, f as ProxyHandlerOptions, R as RealtimeCompanionsFor } from '../composite-ClDE3ViI.js';
3
+ export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-ClDE3ViI.js';
4
4
  export { h as GEMINI_LIVE_PATH, V as VIDEO_OUT_SETUP_KEY } from '../translator-Ddd65sXR.js';
5
5
  import { WebSocket } from 'ws';
6
6
  import '../models-D7F0bLJ3.js';
@@ -234,7 +234,7 @@ declare class OpenAIRealtimeConnection<S = unknown> {
234
234
 
235
235
  declare function realtimeModelOf(req: IncomingMessage): string | undefined;
236
236
 
237
- declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
237
+ declare function realtimeBindingFor(clients: Pick<ProxyClients, 'sessionHandle' | 'createResponseOn'> & Partial<Pick<ProxyClients, 'supportsAudio' | 'openAudioOn' | 'supportsTranscription' | 'openTurnsOn' | 'transcriptStreamFor' | 'realtimeCompanionsFor' | 'releaseSessionHandle' | 'dedicatedSessionHandle'>>, model: string | undefined, signal?: AbortSignal, intent?: string): Promise<RealtimeBinding<ProxyClients>>;
238
238
 
239
239
  declare function fixedClientsResolver(clients: ProxyClients, apiKey?: string, realtimeCompanions?: RealtimeCompanionsFor): {
240
240
  resolve(req: IncomingMessage, signal?: AbortSignal): Promise<RealtimeBinding<ProxyClients>>;
@@ -1 +1 @@
1
- import{E as I,a as n,b as p,c as m,l,m as a,n as x,p as s,r as O,s as f}from"../chunk-EPG5XWHE.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-KXKTXZKG.js";import{i as r,j as i}from"../chunk-6K7NOPD5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
1
+ import{E as I,a as n,b as p,c as m,l,m as a,n as x,p as s,r as O,s as f}from"../chunk-YOFTYCYH.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-B26FENQ3.js";import{i as r,j as i}from"../chunk-7AI75MPZ.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{o as GEMINI_LIVE_PATH,a as OPENAI_REALTIME_PATH,l as OpenAIRealtimeConnection,n as ResumptionRegistry,i as SessionGoneError,r as UnknownModelError,t as VIDEO_OUT_SETUP_KEY,p as attachGeminiLive,x as attachOpenAIRealtime,I as createOpenAIProxy,f as fixedClientsResolver,O as realtimeBindingFor,s as realtimeModelOf,m as serveGeminiLiveSocket};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.6.36",
3
+ "version": "0.6.38",
4
4
  "description": "OpenAI-compatible Realtime + Responses SDK over uRun session primitives (not websockets).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -70,7 +70,7 @@
70
70
  "build:bin": "bun build --compile --external @roamhq/wrtc src/proxy/bin.ts --outfile dist/bin/urun-openai && node scripts/assert-bin-transport.mjs"
71
71
  },
72
72
  "peerDependencies": {
73
- "@urun-sh/core": "^0.6.36"
73
+ "@urun-sh/core": "^0.6.38"
74
74
  },
75
75
  "dependencies": {
76
76
  "@prometheus-io/client": "^0.16.1",
@@ -1,6 +0,0 @@
1
- import{c as w}from"./chunk-YSFSRI3D.js";w();w();var p=class extends Error{},_e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function ve(n){if(typeof n!="string")return!1;let e=_e.exec(n);if(!e)return!1;let[,t,o,r,i,a,d]=e.map(Number);if(!Number.isFinite(Date.parse(n)))return!1;let s=new Date(Date.UTC(t,o-1,r,i,a,d));return s.getUTCFullYear()===t&&s.getUTCMonth()===o-1&&s.getUTCDate()===r&&s.getUTCHours()===i&&s.getUTCMinutes()===a&&s.getUTCSeconds()===d}function Re(n){if(n===null||typeof n!="object")return null;let e=n.shared;if(e==null)return null;if(typeof e!="object")throw new p(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:t,endpoints:o,regions:r,compliance:i}=e;if(typeof t!="string"||t==="")throw new p(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(o))throw new p(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let a=o.map((d,s)=>{if(d===null||typeof d!="object")throw new p(`catalog shared endpoints[${s}] is not an object: ${JSON.stringify(d)}`);let l=d;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new p(`catalog shared endpoints[${s}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new p(`catalog shared endpoints[${s}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let u=(c,g)=>{if(l[c]!==void 0&&l[c]!==null&&!g)throw new p(`catalog shared endpoints[${s}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};u("ready",typeof l.ready=="boolean"),u("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),u("ready_since",ve(l.ready_since));for(let c of["model_id","variant"]){let g=l[c];if(g.includes(":"))throw new p(`catalog shared endpoints[${s}] has "${c}" containing ":" (${JSON.stringify(g)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return u("output_free",typeof l.output_free=="boolean"),l});if(r!=null&&(!Array.isArray(r)||!r.every(d=>typeof d=="string"&&d.length>0)))throw new p(`catalog "shared" block regions is malformed: ${JSON.stringify(r)}`);if(i!=null){let d=i;if(typeof i!="object"||typeof d.zdr!="boolean"||typeof d.hipaa!="boolean")throw new p(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let s of Object.keys(d))if(s!=="zdr"&&s!=="hipaa")throw new p(`catalog "shared" block compliance carries "${s}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return a.length===0?null:{shared_org_id:t,endpoints:a,...r!=null?{regions:r}:{},...i!=null?{compliance:i}:{}}}function S(n){return[...n.endpoints].sort((e,t)=>e.model_id.localeCompare(t.model_id)||e.variant.localeCompare(t.variant))}function We(n){let e=n.filter(r=>typeof r.shared_org_id=="string"&&r.shared_org_id!=="");if(e.length===0)return null;let t=e[0].shared_org_id,o=e.map((r,i)=>{let a=d=>new p(`catalog rows[${i}] (${r.model_id}:${r.variant}) shared row is malformed: ${d}`);if(r.shared_org_id!==t)throw a(`shared_org_id ${JSON.stringify(r.shared_org_id)} disagrees with ${JSON.stringify(t)}`);for(let d of["model_id","variant"]){let s=r[d];if(typeof s!="string"||s===""||s.includes(":"))throw a(`"${d}" ${JSON.stringify(s)} is empty or contains ":"`)}if(typeof r.app_slug!="string"||r.app_slug==="")throw a("no app_slug");if(typeof r.function!="string"||r.function==="")throw a("no function");if(r.app_id!==void 0&&r.app_id!==null&&(typeof r.app_id!="string"||r.app_id===""))throw a(`malformed app_id ${JSON.stringify(r.app_id)}`);return{model_id:r.model_id,variant:r.variant,app_slug:r.app_slug,app_id:r.app_id??null,function:r.function,...r.gpu_spec?{gpu_spec:r.gpu_spec}:{},...r.warm!==void 0&&r.warm!==null?{warm:r.warm}:{},...r.compat_default===!0?{compat_default:!0}:{},...r.output_free===!0?{output_free:!0}:{},...r.ready!==void 0&&r.ready!==null?{ready:r.ready}:{},...r.ready_runtimes!==void 0&&r.ready_runtimes!==null?{ready_runtimes:r.ready_runtimes}:{},...r.ready_since?{ready_since:r.ready_since}:{}}});return{shared_org_id:t,endpoints:o}}function D(n,e,t){let o=(e??"").trim();if(o==="")return null;let r=o,i=t,a=o.lastIndexOf(":");a>0&&(r=o.slice(0,a),i=o.slice(a+1));let d=n.endpoints.filter(l=>l.model_id===r);if(d.length===0)return null;if(i!==void 0){let l=d.find(u=>u.variant===i);return l?{shared_org_id:n.shared_org_id,endpoint:l}:null}if(d.length===1)return{shared_org_id:n.shared_org_id,endpoint:d[0]};let s=d.filter(l=>l.compat_default===!0);if(s.length!==1)throw new p(`shared model "${r}" has ${s.length} compat_default rows (exactly one required) among variants ${d.map(l=>l.variant).join(", ")}`);return{shared_org_id:n.shared_org_id,endpoint:s[0]}}async function Ye(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/catalog`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new p(`catalog read failed: GET ${t} \u2192 ${o.status}`);return Re(await o.json())}w();function h(n){return n.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}w();var _=class extends Error{name="ModelPriceError"},j="per_million_input_tokens",U="per_million_output_tokens",Q="model_id,variant,unit,price_usd,effective_at,expires_at",Y={per_request:!0,per_minute:!0,per_output_unit:!0},be=5e3;function Se(n,e){let t=typeof n=="number"?n:typeof n=="string"&&n.trim()!==""?Number(n):NaN;if(!Number.isFinite(t)||t<0)throw new _(`${e}: price_usd is not a non-negative number (${JSON.stringify(n)})`);return t}function X(n,e,t){let o=typeof n=="string"?Date.parse(n):NaN;if(!Number.isFinite(o))throw new _(`${e}: ${t} is not a parseable timestamp (${JSON.stringify(n)})`);return o}function $e(n,e,t){return n===null?null:X(n,e,t)}function Te(n,e){if(n===j)return"input";if(n===U)return"output";if(typeof n=="string"&&Object.hasOwn(Y,n))return null;throw new _(`${e}: unit ${JSON.stringify(n)} is neither a per-token rate (${j} | ${U}) nor a known GPU-time unit (${Object.keys(Y).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function ke(n,e){let t=n.reduce((r,i)=>i.effective_at>r.effective_at?i:r,n[0]),o=n.find(r=>r.effective_at===t.effective_at&&r.usd!==t.usd);return o?{reason:`two ${e} rates are effective at the same instant (${t.usd} and ${o.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:t}}function J(n,e){return`${n}\0${e}`}function Pe(n){if(!Array.isArray(n))throw new _(`model_prices read is not an array: ${JSON.stringify(n)}`);let e=[];for(let t=0;t<n.length;t++){let o=n[t],r=`model_prices[${t}]`;if(o===null||typeof o!="object"||Array.isArray(o))throw new _(`${r} is not an object: ${JSON.stringify(o)}`);let i=o;for(let l of Q.split(","))if(!Object.hasOwn(i,l))throw new _(`${r} has no "${l}" column: ${JSON.stringify(i)}`);let a=Te(i.unit,r);if(a===null)continue;let d=i.model_id;if(typeof d!="string"||d==="")throw new _(`${r} has no model_id (${JSON.stringify(i)})`);let s=i.variant;if(!(s===null||typeof s=="string"&&s!==""))throw new _(`${r} has a non-string variant (${JSON.stringify(s)})`);e.push({model_id:d,variant:s,side:a,usd:Se(i.price_usd,r),effective_at:X(i.effective_at,r,"effective_at"),expires_at:$e(i.expires_at,r,"expires_at")})}return e}function Z(n,e=Date.now(),t){let o=new Map,r=new Map;for(let s of n){if(s.effective_at>e||s.expires_at!==null&&s.expires_at<=e)continue;let l=o.get(s.model_id);l||(l=new Map,o.set(s.model_id,l),r.set(s.model_id,new Map));let u=s.variant??"",c=l.get(u);c||(c={input:[],output:[]},l.set(u,c),r.get(s.model_id).set(u,s.variant)),c[s.side].push({effective_at:s.effective_at,usd:s.usd})}let i=[],a=[];for(let[s,l]of o){let u=l.get(""),c=(g,f,v)=>{let m=g&&g.length>0?g:u?.[f];if(!m||m.length===0)return null;let y=ke(m,f);return"reason"in y?y:y.rate.usd===0?f==="output"&&v!==null&&t?.has(J(s,v))?y.rate:{reason:`the ${f} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:y.rate};for(let[g,f]of r.get(s)){let v=l.get(g),m=c(v?.input,"input",f),y=c(v?.output,"output",f);if(m!==null&&"reason"in m){a.push({model_id:s,variant:f,reason:m.reason});continue}if(y!==null&&"reason"in y){a.push({model_id:s,variant:f,reason:y.reason});continue}m===null||y===null||i.push({model_id:s,variant:f,pricing:{input:m.usd,output:y.usd}})}}let d=(s,l)=>s.model_id.localeCompare(l.model_id)||(s.variant===null?1:0)-(l.variant===null?1:0)||(s.variant??"").localeCompare(l.variant??"");return{prices:i.sort(d),refusals:a.sort(d)}}function A(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===e);if(o)return o.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===null);return r?r.pricing:null}var E={prices:[],refusals:[]};async function tt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${Q}&unit=in.(${t})`,{headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`},signal:AbortSignal.timeout(be)});if(!o.ok)throw new Error(`model_prices fetch failed: ${o.status}`);return Pe(await o.json())}w();var at="/partners/openrouter/models",xe={chat:!0,code:!0,agent:!0,vl:!0},ee={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ce(n){let e=n.toLowerCase();return Object.hasOwn(ee,e)?ee[e]:null}var te={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Ae(n,e){if(!n||n.length===0)return[];let t=[],o=[];for(let r of n){let i=Object.hasOwn(te,r)?te[r]:null;if(i===null){o.push(r);continue}t.some(d=>d.region===r)||t.push({country_code:i,region:r})}return o.length>0&&e(`urun openrouter doc: shared block region(s) ${o.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),t}var ne={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},re={2:"Llama2",3:"Llama3"};function Ee(n){if(!n)return null;let e=n.split("@")[0],t=e.indexOf("/"),o=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<o.length;r+=1){let i=o[r];if(Object.hasOwn(ne,i))return ne[i];let a=o[r+1];if(i==="llama"&&a!==void 0&&Object.hasOwn(re,a))return re[a];if(i==="phi"&&a!==void 0&&/^\d/.test(a))return"Phi"}return null}var Oe=["context_length","max_model_len"];function Me(n){let e=Oe.map(t=>n.engine_args?.[t]).filter(t=>typeof t=="number"&&Number.isFinite(t)&&t>0);return e.length===0?null:e.every(t=>t===e[0])?e[0]:null}function N(n){let e=n.map(Me),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function Ie(n){let e=n.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function K(n){if(n.length===0)return null;let e=n.map(Ie),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function B(n,e){let t=e.filter(r=>r.serve_app_slug===n);return new Set(t.map(r=>r.model_id)).size===1?t:[]}function Ne(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return O(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return O(o);let r=B(n,e);return r.length>0?O(r):null}function O(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e:Le(n),matches:n}:null}function Le(n){let e=n[0],t=o=>n.every(r=>(r[o]??void 0)===(e[o]??void 0))?e[o]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),updated_at:t("updated_at")}}var $=class extends Error{name="ModelCreatedError"};function T(n){if(n.length===0)return 0;let e=`${n[0].model_id}:${n[0].variant}`,t=n.map(u=>u.created_at??void 0);if(t.some(u=>u===void 0))throw new $(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let o=t[0];if(!t.every(u=>u===o))throw new $(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(t)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(r===null)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let i=Number(r[1]),a=Number(r[2]),d=Number(r[3]),s=Date.UTC(i,a-1,d),l=new Date(s);if(l.getUTCFullYear()!==i||l.getUTCMonth()!==a-1||l.getUTCDate()!==d)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 not a real calendar date`);return s/1e3}function b(n){let e={id:n.id,object:n.object,created:n.created,owned_by:n.owned_by,...n.context_length!==void 0?{context_length:n.context_length}:{},...n.pricing!==void 0?{pricing:n.pricing}:{},...n.voices!==void 0?{voices:n.voices}:{},...n.capabilities!==void 0?{capabilities:n.capabilities}:{}};return"image_modes"in n?{...e,image_modes:n.image_modes}:e}function L(n,e,t){let o=Ne(n,e);if(!o)return b({id:n,object:"model",created:0,owned_by:"urun"});let{row:r,matches:i}=o,a=N(i),d=T(i),s=A(r.model_id,r.variant,t),l=se(r,i),u=K(i);return b({id:n,object:"model",created:d,owned_by:"urun",...a!==null?{context_length:a}:{},...s!==null?{pricing:s}:{},...l.published.length>0?{voices:[...l.published]}:{},...u!==null?{capabilities:{reasoning:u}}:{}})}var Fe=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function se(n,e){if((n.task??void 0)!=="tts")return{published:[],defect:null};let t=e.map(i=>i.engine_args?.voices),o=t[0];if(Array.isArray(o)&&o.length>0&&o.every(i=>typeof i=="string")&&t.every(i=>Array.isArray(i)&&i.length===o.length&&i.every((a,d)=>a===o[d])))return{published:[...o],defect:null};let r=t.some(i=>i!=null)?`the catalog's engine_args.voices for ${n.model_id}:${n.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return n.model_id==="qwen3-tts-customvoice"?{published:[...Fe],defect:r}:{published:[],defect:r}}function z(n){let e=n.length>0?O(n):null;return e===null?{published:[],defect:null}:se(e.row,e.matches)}function oe(n){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(n));if(!e)throw new Error(`unrenderable per-token price: ${String(n)}`);let[,t="",o="",r=""]=e,i=t+o,a=t.length-6+(r===""?0:Number(r));return(a<=0?`0.${"0".repeat(-a)}${i}`:`${i.slice(0,a)}.${i.slice(a).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function ie(n){return{input:[{type:"prompt",unit:"token",cost_usd:oe(n.input)}],output:[{type:"completion",unit:"token",cost_usd:oe(n.output)}]}}function De(n,e,t,o){if(e.length===0)return null;let r=O(e);if(!r)return null;let{row:i,matches:a}=r;if(!i.task||xe[i.task]!==!0)return null;let d=N(a),s=A(i.model_id,i.variant,t),l=Ee(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:T(a),quantization:Ce(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&s!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...s?{pricing:ie(s).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...s?{pricing:ie(s).output}:{}}],...o.datacenters.length>0?{datacenters:o.datacenters}:{},...o.compliance?{compliance:o.compliance}:{}}}function ae(n,e,t,o){let r=o??(l=>console.warn(l.trimEnd())),i=n?S(n):[];if(i.length>0){let l=i.filter(u=>u.ready===void 0);if(l.length===i.length)r("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let u=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");r(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${u} carry no ready field and are declared not ready`)}}let a={datacenters:Ae(n?.regions,r),compliance:n?.compliance??null},d=[],s=new Set;for(let l of i){let u=`${l.model_id}:${l.variant}`;if(s.has(u))continue;s.add(u);let c=De(l,e.filter(g=>g.model_id===l.model_id&&g.variant===l.variant),t,a);c&&d.push(c)}return{data:d}}w();var le={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},k=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function de(n){let e=n.t;if(typeof e!="string"||!(e in le))throw new k(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(le).join(", ")}`);let t={kind:e};return typeof n.delta=="string"&&(t.text=n.delta),typeof n.start_ms=="number"&&Number.isFinite(n.start_ms)&&(t.startMs=n.start_ms),t}function je(n){if(typeof n=="string"){let e;try{e=JSON.parse(n)}catch(t){throw new k(`the "stt" transcript lane delivered a string payload that is not valid JSON (${t instanceof Error?t.message:String(t)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new k(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return de(e)}if(n===null||typeof n!="object"||Array.isArray(n))throw new k(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(n)?"array":typeof n}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return de(n)}function ue(n){return n.reason instanceof Error?n.reason:new Error("the turn-lane consumer aborted")}async function Ue(n,e){return e.aborted?"aborted":await new Promise(t=>{let o=!1,r=a=>{o||(o=!0,e.removeEventListener("abort",i),t(a))},i=()=>r("aborted");e.addEventListener("abort",i,{once:!0}),n.then(()=>r("pulled"),()=>r("pulled"))})}function ut(n,e){let t=n.stream("stt");if(typeof t.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*o(){let r=t.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw ue(e);let i=r.next();if(e!==void 0&&await Ue(i,e)==="aborted")throw i.catch(()=>{}),ue(e);let a=await i;if(a.done)return;yield je(a.value)}}finally{let i=r.return?.();i&&i.catch(()=>{})}}return o()}var _t="https://api.urun.sh/v1",P=class extends Error{},I=class extends Error{},G="urs1.";function ce(n,e){return G+Buffer.from(JSON.stringify([n,e]),"utf8").toString("base64url")}function Ke(n){if(!n.startsWith(G))return null;try{let e=JSON.parse(Buffer.from(n.slice(G.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function vt(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/apps`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}function pe(n){if(n.length===0)return[];if(!n.every(t=>(t.task??void 0)==="image"))return[];let e=qe(n);return e===null?[]:[e]}function Be(n){if(n==null)return null;if(typeof n!="object"||Array.isArray(n))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(n)}
2
- `),null;let e={},t=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],o=!1;for(let[r,i]of t){let a=n[r];if(a==null)continue;let d=typeof a=="number"?a:typeof a=="string"?Number.parseInt(a,10):NaN;if(!Number.isInteger(d)||d<i){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(r)}=${JSON.stringify(a)})
3
- `),o=!0;break}e[r]=d}return o||Object.keys(e).length===0?null:e}function ze(n,e){if(n.length===0)return null;let t;return e.modelId&&(t=n.find(o=>o.model_id===e.modelId&&(!e.variant||o.variant===e.variant))),t||(t=n.find(o=>o.serve_app_slug===e.appSlug||h(`${o.model_id}-${o.variant}`)===e.appSlug||h(o.model_id)===e.appSlug)),t?Be(t.engine_args?.pool):null}function H(n,e,t,o,r){if(!r)throw new p(`shared model "${n}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||t===void 0)throw new p(`shared model "${n}" resolved without a catalog id + variant to join on`);let i=o.filter(a=>a.model_id===e&&a.variant===t);if(i.length===0)throw new p(`shared model "${n}" names endpoint ${e}:${t} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function ge(n,e){if(!e.every(r=>(r.task??void 0)==="image"))return[];let t=e.map(r=>r.engine_args?.expects_image),o=t[0];if(typeof o!="boolean"||!t.every(r=>r===o))throw new p(`shared image model "${n}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(t)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[o===!1?"generation":"edit"]}var ye="shared:",fe="speech:";function q(n){return n.sharedApp?ye+n.appSlug:n.appSlug}function he(n){return typeof n.modelId=="string"&&typeof n.variant=="string"?{kind:"catalog",model_id:n.modelId,variant:n.variant}:{kind:"not-a-catalog-model",model:n.appSlug}}function V(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return t;let o=e.filter(i=>h(i.model_id)===n);return new Set(o.map(i=>i.variant)).size===1?o:[]}function He(n){let e=n.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function qe(n){let e=n.map(He),t=e[0];return t!=null&&e.every(o=>o===t)?t:null}var Ge={stt:"stt",tts:"tts"};function R(n){if(n.length===0)return null;let e=n[0].task??void 0,t=n.every(r=>(r.task??void 0)===e),o=e===void 0?void 0:Ge[e];return o!==void 0?t?o:null:t&&n.every(r=>r.engine_args?.realtime===!0)?"decision":null}function we(n,e){let t=V(n,e);return t.length>0?t:B(n,e)}function M(n,e){return we(n.appSlug,e)}function Ve(n){let e=n.map(o=>o.engine_args?.transcript_stream).filter(o=>o!=null);if(e.length===0)return"stt";let t=e[0];if(typeof t!="string"||t.length===0||!e.every(o=>o===t))throw new p(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return t}var F=6e4,me=class{constructor(e){this.opts=e}opts;pool=new Map;apps={current:null};rows={current:null};shared={current:null};async swr(e,t,o){let r=e.current;return r&&Date.now()-r.at<o?r.value:r?(r.refreshing||(r.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{r.refreshing=void 0}})()),r.value):(e.current={at:Date.now(),value:await t()},e.current.value)}seed(e,t){this.pool.set(e,Promise.resolve(t))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??F):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??F):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??F):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??F;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let t=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:t},t}async pricesForListing(e){let t;try{t=await this.priceRows()}catch(r){if(r instanceof _)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
4
- `),E}let o=Z(t,Date.now(),e);for(let r of o.refusals)this.warn(`urun /v1/models: refusing to price ${r.model_id}:${r.variant??"*"} \u2014 ${r.reason}
5
- `);return o}outputFreeKeys(e){let t=new Set;if(!e)return t;for(let o of e.endpoints)o.output_free===!0&&t.add(J(o.model_id,o.variant));return t}warn(e){(this.opts.warn??(o=>console.warn(o.trimEnd())))(e)}servable(e){return e.filter(t=>t.serves==="openai"&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=this.opts.defaultApp,t=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())r.startsWith(ye)||r.startsWith(fe)||t.add(r);let o=[...t].filter(r=>r!==e).sort();return e===null?o:[e,...o]}async noDefaultApp(e){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new P(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${o}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${o}`)}async sharedLane(e){if(!this.opts.shared)return null;let t=await this.sharedBlock();if(!t)return null;let o=D(t,e);if(o)return o;let r=e.lastIndexOf(":"),i=r>0?e.slice(0,r):e,a=r>0?e.slice(r+1):void 0,d=h(i),s=t.endpoints.filter(c=>h(c.model_id)===d&&(a===void 0||c.variant===a)),l=new Set(s.map(c=>c.model_id)),u=[...l][0];return u===void 0||l.size!==1?null:D(t,u,a)}async resolveTarget(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):{appSlug:o};let r=h(t);if(r===o)return{appSlug:o};let i=await this.sharedLane(t);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:i.shared_org_id,gpuSpec:i.endpoint.gpu_spec??void 0,appId:i.endpoint.app_id??void 0};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let a=await this.deployedApps(),d=this.servable(a);if(d.includes(r))return{appSlug:r};let s=d.filter(u=>u.startsWith(`${r}-`));if(s.length===1)return{appSlug:s[0]};if(s.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${s.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=a.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(l)throw new P(`model "${t}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let d=(await this.opts.listCatalog()).find(s=>t===s.model_id||t===`${s.model_id}:${s.variant}`||r===h(s.model_id)||r===h(`${s.model_id}-${s.variant}`));if(d)throw new P(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${d.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):{appSlug:o}}async catalogIdentityFor(e){let t=he(await this.resolveTarget(e));return t.kind==="catalog"?{model_id:t.model_id,variant:t.variant}:null}async poolTuningFor(e){return ze(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return q(await this.resolveTarget(e))}async sessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,q(t))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,fe+q(t))}async acquire(e,t){let o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(e,t)),this.pool.set(t,o),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o,identity:he(e)}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(e);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(e){let{app:t,entry:o}=await this.sessionFor(e);return{app:t,handle:ce(t,this.keyOf(o))}}async speechHandleFor(e){let{app:t,entry:o}=await this.speechSessionFor(e);return{app:t,handle:ce(t,this.keyOf(o))}}async sessionForHandle(e){let t=Ke(e);if(!t)throw new I(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,i=this.pool.get(o),a=i?await i.then(d=>d,()=>null):null;if(a===null)throw new I(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(a)!==r)throw new I(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:a}}async evict(e,t){let o=this.pool.get(e);!o||await o.then(i=>i,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[o,r]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=o.rows,a=o.ok?r:E;o.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
6
- `);let s=(t?S(t):[]).map(l=>{let u=i.filter(W=>W.model_id===l.model_id&&W.variant===l.variant),c=N(u),g=T(u),f=K(u),v=A(l.model_id,l.variant,a),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?s:[...e.map(l=>L(l,i,a)),...s]}}async openRouterModels(){let e=await this.sharedBlock(),[t,o]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return ae(e,t,o,r=>this.warn(r))}async supportsImages(e,t){let o=await this.resolveTarget(e),r=await this.catalogRows();if(o.sharedApp){let i=H(String(e),o.modelId,o.variant,r,this.opts.listCatalog!==null);return ge(`${o.modelId}:${o.variant}`,i).includes(t)}return pe(V(o.appSlug,r)).includes(t)}async supportsAudio(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))!==null:R(M(t,o))!==null}async supportsSpeech(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="tts":R(M(t,o))==="tts"}async supportsTranscription(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="stt":R(M(t,o))==="stt"}async transcriptStreamFor(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):M(t,o);return Ve(r)}async speechVoices(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):M(t,o);return z(r)}async imageModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds()){let a=pe(V(i,e));a.length!==0&&o.push(b({...L(i,e,t),image_modes:a}))}let r=await this.sharedBlock();if(r)for(let i of S(r)){let a=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),d=ge(`${i.model_id}:${i.variant}`,a);if(d.length===0)continue;let s=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(a),owned_by:"urun",image_modes:d});o.push(s)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds())R(we(i,e))==="stt"&&o.push(L(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let a=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(a)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(a),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,We as b,Ye as c,tt as d,at as e,$ as f,ut as g,_t as h,P as i,I as j,ce as k,Ke as l,vt as m,ze as n,fe as o,q as p,he as q,me as r};
@@ -1,2 +0,0 @@
1
- import{a as G}from"./chunk-CAR4AEQJ.js";import{f as Z,g as D,h as ee,i as ne}from"./chunk-EPG5XWHE.js";import{c as j,f as H,g as W,p as B}from"./chunk-6M5JK4YC.js";import{a as oe,b as N}from"./chunk-GQTWIDJ6.js";import{a as F}from"./chunk-4NMMWAKD.js";import{b as V,c as q,d as K,g as J,j as R,k as X,l as M,m as Q,p as b,q as z,r as Y}from"./chunk-6K7NOPD5.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as C,createClientToken as ae,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Se,DEFAULT_WHEN_LIVE_TIMEOUT_MS as ce,isWakingPhase as Pe,SessionFailedError as Ee}from"@urun-sh/core";A();import{SessionFailedError as fe}from"@urun-sh/core";var U=2;function me(e){let i=e?.type;return i==="response.created"||i==="response.in_progress"}function ge(e){let i=e?.type;return i==="response.completed"||i==="error"}function ie(e){return async function(c,l){let u=await e.sessionFor(c.model);return(async function*(){for(let d=1;d<=U;d++){let{app:w,entry:g,identity:S}=d===1?u:await e.sessionFor(c.model);l?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let s=!1,a=!1;try{let p=await e.createStream(g,c);for await(let f of p){if(ge(f)&&(s=!0),me(f)){if(d>1)continue}else a=!0;yield f}}catch(p){if(p instanceof fe&&(p.kind==="never-live"||p.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,p)}catch{}throw p}if(d<U&&!a){await e.evict(w,g);continue}throw p}if(s)return;if(d<U&&!a){await e.evict(w,g);continue}return}})()}}import{randomUUID as de}from"crypto";A();import{encodeStreamEnvelope as we}from"@urun-sh/core";var ye="audio";function re(e){let i=e.streamEndpoint(ye);return{sessionId:e.id,appendInputAudio(c){let l=Buffer.from(c,"base64");l.byteLength!==0&&i.send(we(new Uint8Array(l)))},onOutputAudio(){return()=>{}}}}var ve=0,Ae=4,Oe=4;function Xe(e,i){let c=(d,w)=>{let g=(e[d]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${d} must be a positive integer (got ${JSON.stringify(e[d])})`);return S},l=(e.URUN_DECISION_POOL_MIN??"").trim();if(l==="0")return null;let u=l?Number.parseInt(l,10):ve;if(!Number.isInteger(u)||u<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let r=c("URUN_DECISION_POOL_MAX",Math.max(u,Ae));return{min:u,max:r,idleGraceMs:3e4,inFlightCap:c("URUN_DECISION_POOL_INFLIGHT_CAP",Oe),replicaId:(e.URUN_REPLICA_ID??"").trim()||i||"proxy"}}function Qe(e){let i=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!i)return D;let c=Number.parseInt(i,10);if(!Number.isInteger(c)||c<=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 c*1e3}function x(e,i,c,l){let u=e[c];if(typeof u!="function")throw new Error(`app "${i}" has no function "${c}" (set URUN_FUNCTION)`);let r=l?u(void 0,l):u();if(typeof r.end!="function")throw new Error(`app "${i}" function "${c}" returned a session without end()`);return r}function pe(e,i,c,l){let{baseUrl:u,orgId:r,auth:d}=e,w=i.fnName??e.fnName,g=e.sessionStartOptions?.(c),S=l||g||i.sharedApp?{...i.sharedApp?{sharedApp:!0}:{},...g,...l}:void 0,s=y=>({session:y,responses:new F(y),gone:oe(y,c)});if(d.lane==="jwt"){let y=C(i.appSlug,{baseUrl:u,orgId:r,jwt:d.jwt});return s(x(y,i.appSlug,w,S))}if(d.lane==="machine"){let{machineToken:y,gatewayUrl:k}=d,I=(typeof e.subject=="function"?e.subject():e.subject)??de(),n=C(i.appSlug,{baseUrl:u,orgId:r,getAccessToken:async()=>(await ae(y,{baseUrl:k,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:I,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(n,i.appSlug,w,S))}let{apiKey:a,gatewayUrl:p}=d,f=(typeof e.subject=="function"?e.subject():e.subject)??de(),h=C(i.appSlug,{baseUrl:u,orgId:r,getAccessToken:async()=>(await ae(a,{baseUrl:p,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:f,...i.sharedApp?{sharedApp:!0}:{}})).token});return s(x(h,i.appSlug,w,S))}function be(e){let i=e.session.id;if(typeof i!="string"||i.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 i}function ue(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let i=e.status.error?.httpStatus,c=e.status.error?.code;return i===410||i===409&&(c==="cancelled"||c==="expired")?!0:c==="client_ended"}var Ie=new Set(["error","paused"]);function ze(e){let{auth:i,catalog:c}=e,l=null,u=(d,w)=>{let g=pe(e,d,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{l?.evict(w,g)}),g},r=new Y({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:u,closeSession:async d=>{if(d.gone.dispose(),e.release==="detach"){if(typeof d.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');d.session.detach();return}await d.session.end()},listApps:i.lane==="api-key"?()=>Q({apiUrl:e.apiUrl,apiKey:i.apiKey}):null,listCatalog:e.catalogRows??(c?()=>G(c):null),listPrices:c?()=>K(c):null,shared:i.lane==="api-key"?()=>q({apiUrl:e.apiUrl,apiKey:i.apiKey}):i.lane==="machine"&&e.catalogRows?async()=>{let d=await e.catalogRows();return V(d)}:null,sessionKey:be});return l=r,e.defaultApp!==null&&r.seed(e.defaultApp,u({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),r}function Ye(e,i){let c=e.decisionPool;if(!c)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let l=c.replicaId??"proxy",u=new Map,r=new Map,d=new Map,w=s=>{process.stderr.write(`[decision-pool] ${s}
2
- `)},g=(s,a)=>{let p=u.get(a);if(p)return p;let f=new Z({min:c.min,max:c.max,idleGraceMs:c.idleGraceMs,inFlightCap:c.inFlightCap,replicaId:l,openSlot:async h=>{let y=pe(e,s,a,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>f.markSessionDead(y)),await L(y.session),w(`slot attached pool=${a} slot=${h.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,y)=>w(`slot detached pool=${a} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof Ee&&ue(h)});return r.set(a,{target:s,env:c}),u.set(a,f),f},S=async(s,a)=>{let p=r.get(a);if(p)try{let f=await i.poolTuningFor(s);g(s,a).retune({min:f?.min??p.env.min,max:f?.max??p.env.max,inFlightCap:f?.in_flight_cap??p.env.inFlightCap,idleGraceMs:f?.idle_grace_s!==void 0?f.idle_grace_s*1e3:p.env.idleGraceMs,warmWaitMs:f?.warm_wait_s!==void 0?f.warm_wait_s*1e3:void 0})}catch(f){w(`pool tuning refresh failed pool=${a} reason=${f instanceof Error?f.message:String(f)}`)}};return{async boot(){if(e.defaultApp===null)return;let s={appSlug:e.defaultApp};await g(s,b(s)).boot()},async sessionFor(s){let a=await i.resolveTargetFor(s),p=b(a),f=g(a,p);await S(a,p);let h=await f.acquire({timeoutMs:f.requestWaitMs}),y=d.get(h.entry)??[];return y.push(h),d.set(h.entry,y),{app:p,entry:h.entry,identity:z(a)}},async warmFor(s){let a=await i.resolveTargetFor(s);await g(a,b(a)).boot()},end(s){let a=d.get(s)?.shift();a&&(d.get(s)?.length===0&&d.delete(s),a.release())},evict(s){for(let a of u.values())a.evict(s)},markSessionDead(s){for(let a of u.values())a.markSessionDead(s)},reap(){for(let[s,{target:a}]of r)S(a,s).then(()=>{let p=u.get(s);p&&p.reap()})},async pingReady(s){for(let a of u.values())if(await a.pingReady(s))return!0;return!1},stats(){return[...u.entries()].map(([s,a])=>({poolKey:s,...a.stats()}))},async drain(s){await Promise.all([...u.values()].map(a=>a.drain({timeoutMs:s})))},async close(){await Promise.all([...u.values()].map(s=>s.close()))}}}function _e(e){return Pe(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ce:Se:ce}async function L(e,i){let c=e.whenLive;if(typeof c!="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 c.call(e,{timeout:_e(e.phase),signal:i})}async function le(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()}function _(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Ze(e,i=W,c,l,u=D,r){let d=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,s=new WeakMap,a=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},p="lane",f=n=>{let o=M(n);if(!r||!o||o.app!==p)return null;let t=r.entryFor(o.key);if(!t)throw new R(`the lane behind this handle (${o.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:o.key,entry:t}},h=async n=>f(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=d.get(n);if(!o){let t={waiting:0,gone:new AbortController};s.set(n,t),o=(async()=>{if(await L(n.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(n)===t&&s.delete(n);let m=await j(n.session,await i());return Object.assign(m,{sessionId:n.session.id})})(),d.set(n,o),o.catch(()=>{d.get(n)===o&&d.delete(n)}),o.then(()=>{s.get(n)===t&&s.delete(n)},()=>{s.get(n)===t&&s.delete(n)})}return o},k=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:m=>t.appendInputAudio(m),onOutputAudio:m=>t.onOutputAudio(m),sessionId:a(n)}})(),S.set(n,o),o.catch(()=>{S.get(n)===o&&S.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=s.get(n);throw(d.get(n)===void 0||E!==void 0&&E.waiting===0)&&await le(n.session),_(t)}let m=o(n),P=s.get(n);return P!==void 0&&P.waiting++,t===void 0?m:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&s.get(n)===P&&(P.gone.abort(),s.delete(n),d.delete(n),S.delete(n),le(n.session).catch(()=>{})),v(_(t))};t.addEventListener("abort",O,{once:!0});let $=()=>t.removeEventListener("abort",O);m.then(T=>{$(),E(T)},T=>{$(),v(T)})})};return{createResponse:ie({sessionFor:r?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return l?l.sessionFor(n):e.sessionFor(n)}:l?n=>l.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>a(n),evict:(n,o)=>{r&&r.owns(o)?r.evict(o):l?l.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{ue(t)&&(r&&r.owns(o)?r.evict(o):l?l.markSessionDead(o):e.evict(n,o),c?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await L(n.session);let t=ee(N(await n.responses.responses.create(o),n.gone),u);if(!l&&!r)return t;let m=n;return(async function*(){try{yield*t}catch(E){throw ne(E)&&(r&&r.owns(m)?r.evict(m):l&&(E instanceof R?l.markSessionDead(m):l.evict(m))),E}finally{r&&r.owns(m)?r.release(m):l?.end(m)}})()}catch(t){throw r&&r.owns(n)?r.release(n):l&&l.end(n),t}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),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,o)=>{let{entry:t}=await e.sessionFor(n);return await I(t,y,o)},openAudioOn:async(n,o,t)=>{let m=f(n);if(m){let E=m.entry.session;return re(E)}let{entry:P}=await e.sessionForHandle(n);return await I(P,k,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw _(o);let t=await h(n);yield*J(t.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=H(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=B(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(r){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o),m=a(t.entry);if(m===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return X(p,m)}}return(await e.handleFor(n)).handle},releaseSessionHandle:n=>{let o=M(n);if(!r||o?.app!==p)return;let t=r.entryFor(o.key);t&&r.release(t)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:t}=await e.sessionForHandle(n);await e.evict(o,t)},createResponseOn:async(n,o,t)=>{let m=await h(n);await L(m.session);let P=t!==void 0&&f(n)?new F({...m.session,consumerId:t},{sessionTag:t}):m.responses;return N(await P.responses.create(o),m.gone)},onSessionEnd:async(n,o)=>{let t=f(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:m}=await e.sessionForHandle(n),P=m.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(v=>{if(E||!Ie.has(v.name))return;E=!0;let O=P.endsAt??null;o({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{Xe as a,Qe as b,ze as c,Ye as d,Ze as e};
@@ -1,23 +0,0 @@
1
- import{a as bt,c as Ae,d as vt,e as Pe}from"./chunk-OEITGJY2.js";import{A as ht,B as gt,C as mt,D as yt,b as Xe,d as Qe,e as W,j as Ze,k as et,m as nt,n as rt,o as ot,p as st,q as it,r as at,t as lt,u as ne,v as ct,w as dt,x as ut,y as ft,z as pt}from"./chunk-EPG5XWHE.js";import{a as qe}from"./chunk-3JWYIKHM.js";import{a as wt}from"./chunk-GQTWIDJ6.js";import{l as tt,m as te}from"./chunk-KXKTXZKG.js";import{a as _t,c as Y,e as Te}from"./chunk-KKCUIOL4.js";import{a as Ve}from"./chunk-4NMMWAKD.js";import{b as Je,d as Le}from"./chunk-GX243AIV.js";import{e as ze,j as ee,n as Ye,o as Ce}from"./chunk-6K7NOPD5.js";import{c as L}from"./chunk-YSFSRI3D.js";L();import{Counter as F,Gauge as re,Histogram as oe,Registry as an,collectDefaultMetrics as ln}from"@prometheus-io/client";import{createServer as cn}from"http";var eo=9464,St="/metrics",se="(other)",dn="(none)",un=64,fn=128,pn=["/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",lt,dt,ze],hn=new Set(pn);function gn(t){return hn.has(t)?t:se}function mn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var ie=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?dn:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,se):(this.admitted.add(e),e):se}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ae=class{registry=new an;modelLabel=new ie(un);orgLabel=new ie(fn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new re({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 F({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 oe({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 oe({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 F({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 F({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 F({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 ut)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new re({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"},ft()),this.ledgerQueue.set({measure:"oldest_age_seconds"},pt()/1e3)}}),this.labelCardinality=new re({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 F({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 re({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 oe({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 oe({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 F({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 F({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&&ln({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=gn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?se:e.method,status_class:mn(e.status),stream:u,model:i,org:s}),this.duration.observe({lane:n,stream:u,model:i,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:i}),e.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function kt(t){return cn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==St){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${St}
2
- `);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
3
- `);return}n.end()})})}L();import{createHash as Rt}from"crypto";import{createServer as yn}from"http";var so=9465,wn="x-urun-key-id",bn="x-urun-key-fingerprint",vn="urun-ratelimit-bucket:",_n="urun-ratelimit-tier:",Et="anonymous",Sn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function kn(t){return Rt("sha256").update(`${vn}${t}`).digest("hex")}function En(t){return Rt("sha256").update(`${_n}${t}`).digest("hex")}function Rn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Sn.test(n)?n:null}function Lt(){return yn((t,e)=>{let n=Rn(t.headers.authorization);e.setHeader(wn,n===null?Et:kn(n)),e.setHeader(bn,n===null?Et:En(n)),e.writeHead(200),e.end()})}L();import{createClientToken as Ln,ClientTokenError as Cn}from"@urun-sh/core";import{createPublicKey as An,verify as Pn}from"crypto";var Ct="urun-session-gateway",Tn="machine",Nn=3e5;function Un(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var P=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},q=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}},D=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function de(t){let e=(t??"").trim();if(e==="")throw new P("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new P("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var In=60,On=6e4,xn=4096;function $n(t){return t===401||t===403}var le=class{constructor(e){this.opts=e;this.mint=e.mint??Ln,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new P("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<On)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:In});r=i.orgId,o={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Cn&&$n(i.status)?(this.cache.delete(e),new P("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new D("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!r)throw new D("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=xn){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function At(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var ce=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<Nn)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(s){throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${s instanceof Error?s.message:String(s)}`)}if(!o.ok)throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let i;try{let s=await o.json();if(!Array.isArray(s.keys))throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);i=s.keys}catch(s){throw s instanceof D?s:new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return i})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new P("malformed machine token");let i,s;try{i=At(n),s=At(r)}catch{throw new P("malformed machine token")}if(i.alg!=="RS256")throw new P(`machine token alg must be RS256 (got ${JSON.stringify(i.alg??null)})`);let a=typeof i.kid=="string"?i.kid:"",u=typeof s.iss=="string"?s.iss:"";if(u===""||!this.opts.issuers.includes(u))throw new P(`machine token issuer is not one this endpoint accepts (${JSON.stringify(u)})`);if(s.aud!==Ct)throw new P(`machine token audience must be ${Ct} (got ${JSON.stringify(s.aud??null)})`);if(s.token_use!==Tn)throw new P(`bearer is a ${JSON.stringify(String(s.token_use??""))} token, not a machine token`);let c=typeof s.org_id=="string"?s.org_id:"";if(c==="")throw new P("machine token carries no org_id \u2014 no tenancy to route by");if((typeof s.exp=="number"?s.exp:0)<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");let h=f=>f.kty==="RSA"&&f.n!==void 0&&f.e!==void 0,l=await this.jwksKeys(!1),m=a===""?void 0:l.find(f=>f.kid===a&&h(f));if(m===void 0&&(l=await this.jwksKeys(!0),m=a===""?void 0:l.find(f=>f.kid===a&&h(f))),m===void 0)throw new P(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let E=Buffer.from(`${n}.${r}`,"ascii"),w=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),R=!1;try{let f=An({key:m,format:"jwk"});R=Pn("RSA-SHA256",E,f,w)}catch{R=!1}if(!R)throw new P("machine token signature failed verification");return{apiKey:e,orgId:c,credential:"machine"}}};function Ne(t,e,n){return n!==null&&Un(t)?n.verify(t):e.resolve(t)}L();var Dn=8080,Ue="serve",ho="0.0.0.0";function Hn(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function go(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Dn: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=tt(te(Hn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),i=o?te(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let u=s?{catalogUrl:te(s,"URUN_CATALOG_URL"),anonKey:a}:null,c=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!c!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let h=c?{keyId:d,key:c}:void 0,l={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()},m=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],E=m.filter((y,_)=>Object.values(l)[_]==="");if(E.length!==0&&E.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${E.join(", ")}, which would half-configure the lane plane`);let w=E.length===0?l:void 0,R={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},f=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=f.filter((y,_)=>Object.values(R)[_]==="");if(g.length!==0&&g.length!==f.length)throw new Error(`${f.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let S=g.length===0?R:void 0,k={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},v=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],N=v.filter((y,_)=>Object.values(k)[_]==="");if(N.length!==0&&N.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${N.join(", ")}, which would half-configure the machine-identity rung`);let $=k.issuers.split(",").map(y=>y.trim()).filter(y=>y!=="");if($.length===0&&N.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 p=Number(k.tokenTtlS);if(N.length===0&&(!Number.isFinite(p)||p<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(k.tokenTtlS)}`);let b=N.length===0?{jwksBaseUrl:k.jwksBaseUrl,issuers:$,tokenTtlS:p}:void 0;return{port:n,baseUrl:r,apiUrl:i,catalog:u,ledgerSigning:h,lane:w,pooler:S,machine:b}}L();import{createHash as Vn,randomUUID as Ut}from"crypto";L();import{request as Mn}from"http";var Fn="/pooler/v1/inference",G=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterSeconds=i;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Wn=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Gn=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},Tt=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Kn=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Tt(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new G(t.status,e,n,t.retryAfterSeconds)};async function Bn(t,e,n,r,o){let i=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Fn}`),s=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Wn(e),firstMessage:Gn(e)}});return new Promise((a,u)=>{let c=Mn({hostname:i.hostname,port:i.port===""?void 0:Number(i.port),path:`${i.pathname}${i.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(s))}},d=>{let h=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(h)?h:void 0,body:d})});c.on("error",d=>u(new G(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),c.end(s)})}var Pt=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*jn(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
4
-
5
- `);if(o===-1)break;let i=e.slice(0,o);e=e.slice(o+2);let s=Pt(i);s!==null&&(yield s)}let n=Pt(e);n!==null&&(yield n)}async function Nt(t,e,n,r){let o=Je(e,n,r),i=o.model??"";if(i==="")throw new G(400,"missing_model","the pooler submit requires a model");let s=await Bn(t,o,n,i,e.stream===!0);if(s.status>=400)throw await Kn(s);let a=e.stream===!0?Le(n,jn(s)):await Jn(s,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Jn(t,e){let n=await Tt(t.body),r=null;try{let i=JSON.parse(n);i!==null&&typeof i=="object"&&(r=i)}catch{r=null}if(r===null)throw new G(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Le(e,(async function*(){yield o})())}var zn=512;function Ie(t){return`urun-inference-proxy-${Vn("sha256").update(t).digest("hex").slice(0,32)}`}var ue=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),i=this.opts.pooler;if(i===void 0)return o;let s=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,u)=>{if(s!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)try{return await o.createResponse(a,u)}catch(h){if(!(h instanceof W))throw h}let c=`px_${Ut()}`;return Nt(i,a,c,c)}})}build(e){if(this.opts.build){let i=this.opts.build(e);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,e,i.router),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ue,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken: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:bt(process.env,process.env.HOSTNAME)??void 0},r=Ae(n),o=n.decisionPool?vt(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Pe(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=zn;){let o=this.tenants.entries().next();if(o.done)break;let[i,s]=o.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];r.decision&&o.push(r.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},It=512,Yn=1024,fe=class extends Error{constructor(){super(`conversation capacity reached (${It} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function qn(t){return{sessionStartOptions:e=>{if(e.startsWith(Ce))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Ce)||t.set(e,n)}}}function Xn(t,e,n,r){let o=Ae({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ue,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken: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",...qn(r)});return{clients:Pe(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var pe=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Ie(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,r):Xn(this.opts,e,r,o);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n);return i.attachments=1,r.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=It;){let e=this.byCaller.keys().next();if(e.done)throw new fe;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[i,s]of r)if(!(s.attachments>0)){r.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new fe;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,Ut())),n),i={createResponse:(s,a)=>o().backhaul.clients.createResponse(s,a),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),releaseSessionHandle:s=>o().backhaul.clients.releaseSessionHandle?.(s),createResponseOn:(s,a,u)=>o().backhaul.clients.createResponseOn(s,a,u),onSessionEnd:(s,a)=>o().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(s,a)},i.openVideo=async s=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(s)},i.openVideoOut=async s=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(s)},i.supportsAudio=async s=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(s)},i.supportsSpeech=async s=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(s)},i.speechVoices=async s=>{let a=o().backhaul.clients.speechVoices;if(a===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 a(s)},i.speechSessionHandle=async s=>{let a=o().backhaul.clients.speechSessionHandle;if(a===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 a(s)},i.openAudioOn=async(s,a,u)=>{let c=o().backhaul.clients.openAudioOn;if(c===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 c(s,a,u)},i.openTurnsOn=(s,a)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(s,a)},i.evictSpeechSession=async s=>{let a=o().backhaul.clients.evictSpeechSession;if(a===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 a(s)},i.supportsTranscription=async s=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(s)},i.transcriptStreamFor=async s=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===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 a(s)},i.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===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 s()},{clients:i,bindResumeHandle:s=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=Yn;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),u=a===void 0?void 0:this.byCaller.get(a.apiKey),c=a===void 0||u===void 0?void 0:u.get(a.conversationId);if(a===void 0||c===void 0||a.apiKey!==e.apiKey)throw new ee("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=c,c.attachments+=1,c.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};L();var Qn="/inference-ledger",Zn=1e4,he=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},$e=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},U=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},De=class extends P{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},He=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},er=[["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",Oe],["output_minutes",Oe],["cost_nano_usd",Oe],["price_version",t=>t===null||typeof t=="string"]];function tr(t){for(let[e,n]of er){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function nr(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"}:tr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Oe(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function xe(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function rr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Ot(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 or(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&&Ot(t.started_at,n.started_at)&&Ot(t.completed_at,n.completed_at)&&xe(t.prompt_tokens,n.prompt_tokens)&&xe(t.completion_tokens,n.completion_tokens)&&xe(t.output_units,n.output_units)&&rr(t.output_minutes,n.output_minutes)}function sr(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(`
6
- `)}async function ir(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(sr(t)));return{signature:Array.from(new Uint8Array(o),s=>s.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function ar(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new U(`${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 U(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new U(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new U(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let i=c=>{if(!(c in n))throw new U(`${e} answered a row with no ${c} field: ${JSON.stringify(t)}`);let d=n[c];if(d===null)return null;if(typeof d!="string")throw new U(`${e} answered a non-string ${c}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new U(`${e} answered a BLANK ${c} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},s=i("price_version"),a=i("unpriced_reason"),u=o!=null;if(u&&(s===null||a!==null))throw new U(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!u&&(s!==null||a===null))throw new U(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:a}}var ge=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Qn}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await ir(n,this.opts.signing)}):JSON.stringify(n)}catch(c){throw new U(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${c instanceof Error?c.message:String(c)}`)}let i;try{i=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Zn)})}catch(c){throw new U(`the uRun ledger surface at ${r} could not be reached: ${c instanceof Error?c.message:String(c)}`)}if(i.status===409){let c=await i.text().catch(()=>""),d=nr(c);throw d.status==="found"&&or(n,d.row)?new $e(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new he(`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 he(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${c.slice(0,400)}`)}if(i.status===401||i.status===403)throw await i.text().catch(()=>{}),new De("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(!i.ok){let c=await i.text().catch(h=>`<body unreadable: ${h instanceof Error?h.message:String(h)}>`),d;try{let h=JSON.parse(c);if(h!==null&&typeof h=="object"&&"error"in h){let l=h.error;l!==null&&typeof l=="object"&&"code"in l&&(d=l.code)}}catch{}throw d==="ledger_signature_invalid"?new He(`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: `+c.slice(0,400)):new U(`the uRun ledger surface at ${r} answered HTTP ${i.status}: ${c.slice(0,400)}`)}let s;try{s=await i.json()}catch(c){throw new U(`the uRun ledger surface at ${r} answered a body that is not JSON: ${c instanceof Error?c.message:String(c)}`)}let a=s?.recorded;if(a===void 0)throw new U(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=ar(a,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new U(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};L();import{createServer as Mr}from"http";L();import{createWebsocketDocConnector as gr}from"@urun-sh/core/internal";import mr from"ws";L();import*as K from"yjs";import{SessionDocumentImpl as lr}from"@urun-sh/core/internal";var cr=3e4;function dr(t){return(e,n,r)=>{let o=t(e);K.applyUpdate(n,K.encodeStateAsUpdate(o));let i=a=>K.applyUpdate(o,a),s=a=>K.applyUpdate(n,a);return n.on("update",i),o.on("update",s),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",i),o.off("update",s)}}}}function Me(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?dr(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,i=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let h=r.get(d);return h||(h=new lr(d,e,n),r.set(d,h)),h},s=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let h=s.get(d);if(!h){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);h=t.streamEndpoint(d),s.set(d,h)}return h},u=d=>{let h="llm-resp:";if(!d.startsWith(h))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${h}<rid>)`);async function*l(){let m=a(d);try{yield*m.messages()}finally{s.delete(d),await m.close()}}return{messages:()=>l(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return i(d)},stream:u,streamEndpoint:a,async end(){},async whenLive(d){let h=i("llm");if(h.synced===!0)return;let l=d?.timeout??t.whenLiveTimeoutMs??cr;await new Promise((m,E)=>{let w=setTimeout(()=>{R(),E(new Error(`lane ${e} llm doc never synced within ${l}ms`))},l),R=h.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",f),m()}),f=()=>{clearTimeout(w),R(),E(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",f,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,h]of s)s.delete(d),h.close()}}}L();import me,{WebSocketServer as ur}from"ws";import{ENVELOPE_KIND as Mt,STREAM_END as fr,StreamFragmentReassembler as pr}from"@urun-sh/core";var xt="/stream/";function $t(t){if(!t.startsWith(xt))return null;let e=t.slice(xt.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 be(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function ye(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>Mt.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var we=class{reassembler=new pr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===fr&&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})}}},We=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let i=this.chan(e,n),s=[...i.peers].filter(a=>a!==r);if(s.length===0){let a=i.pending;(a.list.length>=Dt||a.bytes+o.byteLength>Ht)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Dt} frames / ${Ht} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of s)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let i=o.pending;if(i.list.length===0)return;let s=i.list.filter(a=>a.producer!==r);i.list=i.list.filter(a=>a.producer===r),i.bytes=i.list.reduce((a,u)=>a+u.envelope.byteLength,0);for(let{envelope:a}of s)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,i=this.channels.get(o);if(i){for(let s of[...i.peers])s===r&&i.peers.delete(s);i.peers.size===0&&i.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let i of o?.peers??[])i.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")}}},Dt=256,Ht=8*1024*1024,H=new We;function Ft(t,e){let n=new we,r={send(o){H.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{ye(o)}catch(i){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(i)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),H.detach(t,e,r)}};return H.attach(t,e,r),r}function hr(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function Wt(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new me(r,be(e)),i=new we;return o.addEventListener("message",s=>{let a=new Uint8Array(s.data);try{ye(a)}catch(u){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(u)}`);return}i.push(i.feed(a))}),o.addEventListener("close",()=>{i.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{i.finish(new Error(`lane stream ${r} socket error`))}),{send(s){if(ye(s),o.readyState!==me.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(s,{binary:!0})},deliver(s){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>i.iterate(),async close(){i.finish();try{o.close(1e3)}catch{}}}}function Fe(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
7
- `;t.end(`HTTP/1.1 ${e} ${r}\r
8
- Connection: close\r
9
- Content-Type: text/plain; charset=utf-8\r
10
- Content-Length: ${Buffer.byteLength(o)}\r
11
- \r
12
- ${o}`)}function Gt(t,e){let n=new ur({noServer:!0,handleProtocols:(u,c)=>{let d=$t(new URL(c.url??"/","http://localhost").pathname);if(!d)return!1;let h=be(d.name);return u.has(h)?h:!1}}),r=new Map,o=new Set,i=!1,s=(u,c,d,h)=>{let l={client:d,upstream:h,laneId:u,name:c};o.add(l);let m=E=>{if(o.delete(l)){console.warn(`[lane-stream] ${u}/${c}: host-affinity pump torn down (${E})`);for(let w of[d,h])try{(w.readyState===me.OPEN||w.readyState===me.CONNECTING)&&w.close(1001,"lane stream pump closed")}catch{}}};d.on("message",E=>{try{h.send(E,{binary:!0})}catch(w){m(`upstream send failed: ${String(w)}`)}}),h.on("message",E=>{try{d.send(E,{binary:!0})}catch(w){m(`client send failed: ${String(w)}`)}}),d.on("close",()=>m("client socket closed")),d.on("error",()=>m("client socket error")),h.on("close",()=>m("host socket closed")),h.on("error",()=>m("host socket error"))},a=(u,c,d)=>{let h;try{h=new URL(u.url??"/","http://localhost")}catch{Fe(c,400,"malformed upgrade URL");return}c.on("error",()=>c.destroy());let l=$t(h.pathname);l&&(i||c.destroyed||(async()=>{let m=h.searchParams.get("token")??"",E=null;try{E=m===""?null:await e.verifyToken(m,l.laneId,l.name)}catch{E=null}if(E===null){Fe(c,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let w=await e.hostOf(l.laneId).catch(()=>null);if(w&&w!==e.selfAddress)try{let R=await e.podToPodDial(l.laneId,l.name,w);n.handleUpgrade(u,c,d,f=>{s(l.laneId,l.name,f,R)});return}catch(R){console.warn(`[lane-stream] ${l.laneId}/${l.name}: host dial to ${w} failed (${String(R)}) \u2014 falling back to the local relay`)}}n.handleUpgrade(u,c,d,w=>{let R=hr(w);r.set(w,R),H.attach(l.laneId,l.name,R),w.on("message",g=>{let S=new Uint8Array(g);try{ye(S)}catch(k){console.warn(`[lane-stream] ${l.laneId}/${l.name}: dropped malformed envelope: ${String(k)}`);return}H.deliver(l.laneId,l.name,R,S),S[1]===Mt.END&&H.detach(l.laneId,l.name,R)});let f=()=>{r.delete(w),H.detach(l.laneId,l.name,R)};w.on("close",f),w.on("error",f)})})().catch(()=>{c.destroyed||Fe(c,500,"lane stream upgrade failed")}))};return t.on("upgrade",a),{async close(){i=!0,t.off("upgrade",a),H.clear();for(let u of r.values())u.close(1001,"lane stream host shutting down");r.clear();for(let u of o)for(let c of[u.client,u.upstream])try{c.close(1001,"lane stream host shutting down")}catch{}o.clear()}}}function yr(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Qe(`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??""}`}function Kt(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,i=new Map,s=(l,m,E,w,R)=>{let f=E?v=>Ft(l,v):v=>Wt(l,v,{hostUrl:`ws://${w}/stream/${l}`,token:()=>Y(l,t.tokenSecret,void 0,void 0,R)}),g=E?Me({laneId:l,roomDoc:v=>t.roomDoc(l,v),streamEndpoint:f}):Me({laneId:l,streamEndpoint:f,connector:gr({serverUrl:`ws://${w}/doc`,sessionId:l,token:()=>Y(l,t.tokenSecret,void 0,void 0,R),WebSocketPolyfill:mr})}),S=E?a(l):wt(g,`lane:${l}`,{armOnFirstSync:!0}),k={session:g,responses:new Ve(g,{sessionTag:null}),gone:S,goneWatch:S,laneId:l,pool:m,inFlight:0,laneSession:g,self:E,host:w??""};return n.set(l,k),S.onGone(()=>u(k)),k},a=l=>{let m=null,E=!1,w=new Set,R=g=>{if(!m){m=g;for(let S of[...w])S(g);w.clear()}},f=t.hostedSignal?.(l,g=>{if(g){E=!0;return}E&&R(new ee(`the lane ${l} 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:()=>m,onGone(g){return m?(g(m),()=>{}):(w.add(g),()=>w.delete(g))},dispose(){f?.(),w.clear()}}},u=l=>{c(l)&&(n.delete(l.laneId),r.delete(l.laneId),l.goneWatch?.dispose(),H.forgetLane(l.laneId))},c=l=>{let m=l.laneId;return typeof m=="string"&&n.get(m)===l},d=(l,m)=>{throw t.metrics?.observeLane503Fast(m??""),i.set(l,e()),new W(l)},h=async(l,m)=>{let E=yr(m);o.add(E);let w=e();try{let R=await t.laneWarmWaitMsFor?.(l,m)??t.laneColdWakeDefaultMs??0,f=await t.plane.pick({pool:E,model:l,holdMs:R});t.metrics?.observeLaneReady(l??"",f.length);let S=f.map(v=>({laneId:v.laneId,self:v.host===t.selfAddress,host:v.host})).sort((v,N)=>v.self!==N.self?v.self?-1:1:(r.get(v.laneId)??0)-(r.get(N.laneId)??0))[0];S||d(E,l);let k=n.get(S.laneId);return k?.goneWatch?.gone()&&(u(k),k=void 0),k&&(k.pool!==E||k.self!==S.self||k.host!==S.host)&&(u(k),k=void 0),k||(k=s(S.laneId,E,S.self,S.host,m.sharedOrgId??void 0)),k.inFlight+=1,r.set(S.laneId,(r.get(S.laneId)??0)+1),{app:E,entry:k,identity:{kind:"catalog",model_id:m.modelId??l??"",variant:m.variant??""}}}finally{t.metrics?.observeLanePick(l??"",e()-w)}};return{sessionFor(l,m){return h(l,m)},release(l){c(l)&&(l.inFlight=Math.max(0,l.inFlight-1),r.set(l.laneId,l.inFlight))},owns(l){return c(l)},entryFor(l){return n.get(l)??null},evict(l){c(l)&&(l.gone.dispose(),n.delete(l.laneId),r.set(l.laneId,0),l.laneSession.destroy())},async status(){let l=[...new Set([...o,...[...n.values()].map(w=>w.pool)])].sort(),m=await t.plane.status().catch(()=>[]),E=new Map(wr(m));return Promise.all(l.map(async w=>{let R=E.get(w)??{pool:w,lanes:[],lastDemandAt:null};return{pool:w,lanes:R.lanes,lastDemandAt:R.lastDemandAt,local:[...n.values()].filter(f=>f.pool===w).map(f=>({laneId:f.laneId,inFlight:f.inFlight,self:f.self,host:f.host})),lastRefusalAt:i.get(w)??null}}))},async close(){for(let l of n.values())l.gone.dispose(),l.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(l=>({pool:l.pool,laneId:l.laneId,inFlight:l.inFlight}))}}}function wr(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}L();import{request as br}from"http";var vr="/pooler/v1/lanes/pick",_r="/pooler/v1/lanes/status",Sr=1e4;function Bt(t,e,n,r,o){return new Promise((i,s)=>{let a=new URL(n,t.baseUrl),u=r===void 0?void 0:Buffer.from(JSON.stringify(r)),c=br({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...u===void 0?{}:{"content-type":"application/json","content-length":String(u.byteLength)}},timeout:o},d=>{let h=[];d.on("data",l=>h.push(l)),d.on("end",()=>{let l=Buffer.concat(h).toString("utf8"),m=null;try{m=l===""?null:JSON.parse(l)}catch{m=null}i({status:d.statusCode??0,json:m})}),d.on("error",s)});c.on("timeout",()=>{c.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),c.on("error",s),c.end(u)})}function jt(t,e,n){if(t===503)return new W(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function Jt(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await Bt(t,"POST",vr,{pool:e,model:n,hold_ms:r},r+Sr);if(o.status!==200)throw jt(o.status,o.json,e);return(o.json?.lanes??[]).filter(s=>typeof s.lane_id=="string"&&s.lane_id!==""&&typeof s.host=="string"&&s.host!=="").map(s=>({laneId:s.lane_id,host:s.host}))},async status(){let e=await Bt(t,"GET",_r,void 0,5e3);if(e.status!==200)throw jt(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}L();import{WebSocketServer as Or}from"ws";L();import*as zt from"yjs";import*as J from"y-protocols/sync";import*as M from"y-protocols/awareness";import*as A from"lib0/encoding";import*as V from"lib0/decoding";import*as Yt from"lib0/map";import Er from"lodash.debounce";L();var Vt=()=>{};var Rr=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Lr=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Cr=0,Ar=1;var Pr=process.env.GC!=="false"&&process.env.GC!=="0",Tr=process.env.YPERSISTENCE,ve=null;if(typeof Tr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var j=new Map,_e=0,Ke=1,Nr=(t,e,n)=>{let r=A.createEncoder();A.writeVarUint(r,_e),J.writeUpdate(r,t);let o=A.toUint8Array(r);n.conns.forEach((i,s)=>X(n,s,o))},Ge=class extends zt.Doc{constructor(e){super({gc:Pr}),this.name=e,this.conns=new Map,this.awareness=new M.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:i},s)=>{let a=r.concat(o,i);if(s!==null){let d=this.conns.get(s);d!==void 0&&(r.forEach(h=>{d.add(h)}),i.forEach(h=>{d.delete(h)}))}let u=A.createEncoder();A.writeVarUint(u,Ke),A.writeVarUint8Array(u,M.encodeAwarenessUpdate(this.awareness,a));let c=A.toUint8Array(u);this.conns.forEach((d,h)=>{X(this,h,c)})};this.awareness.on("update",n),this.on("update",Nr),!1}},Be=(t,e=!0)=>Yt.setIfUndefined(j,t,()=>{let n=new Ge(t);return n.gc=e,ve!==null&&ve.bindState(t,n),j.set(t,n),n}),Ur=(t,e,n)=>{try{let r=A.createEncoder(),o=V.createDecoder(n);switch(V.readVarUint(o)){case _e:A.writeVarUint(r,_e),J.readSyncMessage(o,r,e,t),A.length(r)>1&&X(e,t,A.toUint8Array(r));break;case Ke:{M.applyAwarenessUpdate(e.awareness,V.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},B=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),M.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&ve!==null&&(ve.writeState(t.name,t).then(()=>{t.destroy()}),j.delete(t.name))}e.close()},X=(t,e,n)=>{e.readyState!==Cr&&e.readyState!==Ar&&B(t,e);try{e.send(n,r=>{r!=null&&B(t,e)})}catch{B(t,e)}},Ir=3e4,qt=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=Be(n,r);o.conns.set(t,new Set),t.on("message",a=>Ur(t,o,new Uint8Array(a)));let i=!0,s=setInterval(()=>{if(!i)o.conns.has(t)&&B(o,t),clearInterval(s);else if(o.conns.has(t)){i=!1;try{t.ping()}catch{B(o,t),clearInterval(s)}}},Ir);t.on("close",()=>{B(o,t),clearInterval(s)}),t.on("pong",()=>{i=!0});{let a=A.createEncoder();A.writeVarUint(a,_e),J.writeSyncStep1(a,o),X(o,t,A.toUint8Array(a));let u=o.awareness.getStates();if(u.size>0){let c=A.createEncoder();A.writeVarUint(c,Ke),A.writeVarUint8Array(c,M.encodeAwarenessUpdate(o.awareness,Array.from(u.keys()))),X(o,t,A.toUint8Array(c))}}};var je="/doc/",Qt=30,xr=1e4,Xt="llm";function $r(t){if(!t.startsWith(je))return null;let e=t.slice(je.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 Q(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
13
- `;t.end(`HTTP/1.1 ${e} ${r}\r
14
- Connection: close\r
15
- Content-Type: text/plain; charset=utf-8\r
16
- Content-Length: ${Buffer.byteLength(o)}\r
17
- \r
18
- ${o}`)}function Zt(t,e){let n=new Or({noServer:!0}),r=new Set,o=new Map,i=new Map,s=f=>o.get(`${f}/${Xt}`)??0,a=f=>i.get(f)??0,u=new Map,c=new Map,d=new Set,h=new Set,l=!1,m=(f,g,S)=>{let k=s(f)>0,v=a(f),N=v>0,$=`${f}/${g}`,p=o.get($)??0;S>0?o.set($,S):o.delete($);let b=v+S-p;b>0?i.set(f,b):i.delete(f);let y=s(f)>0,_=b>0;if(k!==y){y?E(f):w(f);for(let C of u.get(f)??[])C(y)}N&&!_&&queueMicrotask(()=>{let C=`${f}/`;for(let[T,x]of[...j.entries()])!T.startsWith(C)||x.conns.size>0||(j.delete(T),x.destroy())})},E=f=>{if(!e.hostRegistry||c.has(f))return;let g=()=>{e.hostRegistry?.setHost(f,e.selfAddress).catch(()=>{})};g();let S=setInterval(g,xr);S.unref?.(),c.set(f,S)},w=f=>{let g=c.get(f);g&&(clearInterval(g),c.delete(f)),e.hostRegistry&&e.hostRegistry.delHost(f,e.selfAddress).catch(()=>{})},R=(f,g,S)=>{let k;try{k=new URL(f.url??"/","http://localhost")}catch{Q(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>h.delete(g));let v=$r(k.pathname);if(!v){if(k.pathname.startsWith(je)){Q(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}h.add(g);return}d.add(g);let N=!1;(async()=>{let $=k.searchParams.get("token")??"",p=null;try{p=$===""?null:await e.verifyToken($,v.laneId,v.docName)}catch{p=null}if(p===null){Q(g,401,"invalid or missing lane doc token");return}let b=p;if(b.tenant!==void 0&&e.laneTenantOf){let y=null;try{y=await e.laneTenantOf(v.laneId)}catch{y=null}if(y==null||y==="")e.onLaneTenantMissing?.();else if(b.tenant!==y){Q(g,403,"lane doc token org does not match the lane record");return}}l||g.destroyed||(N=!0,n.handleUpgrade(f,g,S,y=>{d.delete(g),r.add(y),y.on("close",()=>r.delete(y));let _=b.scope===_t||b.scope===void 0&&typeof b.app=="string"&&typeof b.fn=="string"&&b.aud==="sfu";if(_){let T=`${v.laneId}/${v.docName}`,x=(o.get(T)??0)+1;m(v.laneId,v.docName,x),x>1&&v.docName===Xt&&e.hostRegistry?.setHost(v.laneId,e.selfAddress).catch(()=>{})}y.on("close",()=>{if(!_)return;let T=`${v.laneId}/${v.docName}`;m(v.laneId,v.docName,Math.max(0,(o.get(T)??1)-1))}),qt(y,f,{docName:`${v.laneId}/${v.docName}`,gc:!0})}))})().catch(()=>{!N&&!g.destroyed&&Q(g,500,"lane doc upgrade failed")}).finally(()=>d.delete(g))};return t.on("upgrade",R),{async close(){l=!0,t.off("upgrade",R);for(let g of[...c.keys()])w(g);await new Promise(g=>{if(r.size===0&&d.size===0){g();return}let S=r.size+d.size,k=()=>{S-=1,S<=0&&g()};for(let v of r)v.once("close",k);for(let v of d)v.once("close",k);for(let v of r)v.close(1001,"lane doc host shutting down");for(let v of d)v.destroy()}),o.clear(),i.clear(),u.clear()},roomDoc(f,g){return Be(`${f}/${g}`,!0)},isHosted(f){return s(f)>0},onHostedChange(f,g){let S=u.get(f);return S||(S=new Set,u.set(f,S)),S.add(g),g(s(f)>0),()=>{S.delete(g)}}}}import Fr from"ws";L();var Dr="urun:catalog:v1";function en(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,i=null,s=async()=>{let u=await t.redis.hgetall(Dr),c=[];for(let d of Object.values(u))try{c.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
19
- `)}return r=c,o=n(),c},a=()=>r===null||n()-o>=e;return{rows(){return a()?(i||(i=s().finally(()=>{i=null})),i):Promise.resolve(r)},close(){r=null,i=null}}}import Wr from"ioredis";L();var Se="/inference-usage",tn=25e3;var Hr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function nn(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Hr.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 ke=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Se}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(tn)})}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) could not be reached within ${tn}ms: ${nn(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new P("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} (${a})`)}let i;try{i=await o.json()}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} with a body that is not JSON: ${nn(s)}`)}return ct(i,this.opts.onRejectedRow)}};var Gr=5e3,Kr=1e3,Br=1500,jr=3e3,Jr="/api/client-tokens";function Ee(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function rn(t,e,n,r){Ee(t,e,{error:{message:n,type:r}})}async function Vr(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Jr}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(jr)});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 Ks(t){let e=t.resolver??new le({gatewayUrl:t.baseUrl}),n=t.machine?new ce({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new ae(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,i=null,s=(()=>{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 p=new Wr(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),b=en({redis:p});return{registry:Kt({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Jt({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(_,C)=>o?.onHostedChange(_,C)??(()=>()=>{}),roomDoc:(_,C)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(_,C)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(_,C)=>b.rows().then(T=>{let x=Ye(T,C);return x?.warm_wait_s!==void 0?x.warm_wait_s*1e3:void 0})}),catalog:b,redis:p}})(),a=t.registry??new ue({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry,pooler:t.pooler}),u=t.probeControlPlane??(()=>Vr(t.baseUrl)),c=async()=>{let p=null;for(let _ of a.decisionPools()){p=_;break}if(!p)return null;let b=p.stats();if(b.some(_=>_.draining))return{ok:!1,detail:"decision pool draining"};if(b.every(_=>_.attached===0&&_.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let y=await p.pingReady(Br);return{ok:y,detail:y?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new ke({apiUrl:t.apiUrl}),h=t.ledgerClient??new ge({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),l=process.env.URUN_SHARED_ORG_ID?.trim(),m=process.env.URUN_SHARED_ORG_API_KEY?.trim();l&&m&&(async()=>{try{await a.decisionWarmerFor({orgId:l,apiKey:m})?.warmFor(mt)}catch(p){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(p instanceof Error?p.message:p)}
20
- `)}})();let E=async p=>Ne(de(p.headers.authorization),e,n),w=async p=>{let b=await E(p);if(b.billingAudience==="platform"&&b.creditsAdmissionOk===!1){let y=b.creditsRefusalReason;throw new q(y==="spend_cap_reached"||y==="insufficient_credits"?y:void 0)}return b},R=p=>p instanceof P?{status:p.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:p instanceof q?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...p.code!==void 0?{code:p.code}:{}}:p instanceof D?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:p.detail}:null,f=yt({clients:async p=>a.clientsFor(await w(p)),usage:{authorize:p=>de(p.headers.authorization),lookup:(p,b)=>d.lookup(p,b)},statusOf:R,...t.requestLog?{requestLog:t.requestLog}:{},observe:p=>r.observe(p),ledger:{write:(p,b)=>h.write(de(p.headers.authorization),b),observe:p=>r.observeLedger(p),...t.ledgerLog?{report:t.ledgerLog}:{}}}),g=null,S=null,k=Mr((p,b)=>{let y=new URL(p.url??"/","http://localhost");(async()=>{if(p.method==="GET"&&y.pathname==="/healthz"){Ee(b,200,{ok:!0});return}if(p.method==="GET"&&y.pathname==="/readyz"){let T=Date.now();if((!g||T-g.at>=Gr)&&(g={at:T,...await u()}),!S||T-S.at>=Kr){let z=await c();S=z===null?{at:T,ok:!0,detail:null}:{at:T,ok:z.ok,detail:z.detail}}let x=(g?.ready??!1)&&S.ok,Z=S.detail===null?g?.detail??"control plane not yet probed":`${g?.detail??"control plane not yet probed"}; ${S.detail}`;Ee(b,x?200:503,{ok:x,control_plane:Z});return}if(p.method==="GET"&&y.pathname==="/lanez"){Ee(b,200,{pools:s?await s.registry.status():null});return}let _=y.pathname==="/v1"||y.pathname.startsWith("/v1/"),C=y.pathname.startsWith("/partners/");if(!_&&!C){rn(b,404,`no route for ${p.method} ${y.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}f(p,b)})().catch(_=>{if(!b.headersSent){rn(b,500,String(_ instanceof Error?_.message:_),"proxy_error");return}b.end()})}),v=t.conversations??new pe({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry}),N=[Xe(k,{authenticate:async p=>{let b=await Ne(p,e,n),y=v.connectionFor(b);return{clients:y.clients,scope:Ie(b.apiKey),onBindResumeHandle:y.bindResumeHandle,clientsForResume:y.clientsForResume,release:y.release}}}),et(k,{clients:async p=>a.clientsFor(await w(p)),statusOf:R}).close,rt(k,{resolver:{resolve:async(p,b)=>{let y=await w(p),_=v.connectionFor(y),C;try{C=await at(ot(_.clients,t.realtimeCompanions),st(p),b,it(p))}catch(x){throw _.release().catch(()=>{}),x}let T=C.release;return{...C,release:async()=>{await T?.(),await _.release()}}}}})];if(t.lane&&s){let p=t.lane,b=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=Zt(k,{verifyToken:(_,C)=>Te(_,C,p.tokenSecret,void 0,b),selfAddress:p.selfAddress,laneTenantOf:_=>s.redis.get(`lane_tenant:${_}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:b,hostRegistry:{setHost:(_,C)=>s.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:${_}`,C,String(Qt)),delHost:_=>s.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${_}`,p.selfAddress)}}),i=Gt(k,{verifyToken:(_,C)=>Te(_,C,p.tokenSecret,void 0,b),selfAddress:p.selfAddress,hostOf:async _=>{let C=await s.redis.get(`lane_hosts:${_}`);return C&&C.trim()!==""?C.trim():null},podToPodDial:(_,C,T)=>new Promise((x,Z)=>{(async()=>{let z=await s.redis.get(`lane_tenant:${_}`),on=Y(_,p.tokenSecret,void 0,void 0,z||void 0),sn=`ws://${T}/stream/${encodeURIComponent(_)}/${encodeURIComponent(C)}?token=${encodeURIComponent(on)}`,Re=new Fr(sn,be(C));Re.once("open",()=>x(Re)),Re.once("error",Z)})().catch(Z)})});let y=s;N.push(async()=>{await o.close(),await i.close(),await y.registry.close(),y.redis.quit().catch(()=>{})})}k.on("upgrade",(p,b)=>{let y=new URL(p.url??"/","http://localhost");y.pathname===qe||y.pathname===Ze||y.pathname===nt||o!==null&&y.pathname.startsWith("/doc/")||i!==null&&y.pathname.startsWith("/stream/")||b.destroyed||(b.write(`HTTP/1.1 404 Not Found\r
21
- Connection: close\r
22
- \r
23
- no WS route for ${y.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),b.destroy())});let $=async()=>{for(let p of N)await p();await v.detachAll()};return{server:k,metricsServer:kt(r),metrics:r,edgeIdentityServer:Lt(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:$}}async function Bs(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ht()||gt(),await e()}export{eo as a,St as b,se as c,dn as d,un as e,fn as f,gn as g,mn as h,ie as i,ae as j,kt as k,so as l,wn as m,bn as n,vn as o,_n as p,Et as q,kn as r,En as s,Rn as t,Lt as u,P as v,D as w,de as x,On as y,xn as z,le as A,Dn as B,Ue as C,ho as D,go as E,zn as F,Ie as G,ue as H,It as I,Yn as J,fe as K,pe as L,Qn as M,Zn as N,he as O,U as P,ar as Q,ge as R,Gr as S,jr as T,Ks as U,Bs as V};