@urun-sh/openai 0.6.32 → 0.6.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{g as m}from"./chunk-OOCRI7ZM.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var f="0.6.32";var y=4141,R=f,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(p=>p==="-m"||p==="--model"||p.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),u=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...u]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?g(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let u=(e.URUN_GATEWAY_URL??"").trim(),p=u?g(u):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:p}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function g(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
1
+ import{g as m}from"./chunk-OOCRI7ZM.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var f="0.6.33";var y=4141,R=f,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(p=>p==="-m"||p==="--model"||p.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),u=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...u]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?g(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let u=(e.URUN_GATEWAY_URL??"").trim(),p=u?g(u):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:p}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function g(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of l)n[i]=a[i]}}var j=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&j.has(t)}function re(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function oe(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
3
3
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ie(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
4
4
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
@@ -0,0 +1,17 @@
1
+ import{a as st,c as we,d as it,e as be}from"./chunk-7D2HMQFC.js";import{A as et,B as tt,C as nt,D as rt,b as $e,d as Me,e as q,j as He,k as Fe,m as We,n as Ke,o as je,p as Be,q as Ve,r as ze,t as Ye,u as Q,v as Je,w as qe,x as Xe,y as Qe,z as Ze}from"./chunk-GR3UAW6P.js";import{a as De}from"./chunk-3JWYIKHM.js";import{a as at,b as lt,c as ct}from"./chunk-PAYCMH5F.js";import{a as ot}from"./chunk-L6HTHDVV.js";import{l as Ge,m as X}from"./chunk-NL3UBLXV.js";import{a as Ie}from"./chunk-GL7EWL3V.js";import{b as Ne,d as me}from"./chunk-NN6TQQUG.js";import{d as Ue,i as J,m as xe,n as ye}from"./chunk-OOCRI7ZM.js";import{c as S}from"./chunk-YSFSRI3D.js";S();import{Counter as M,Gauge as Z,Histogram as ee,Registry as Dt,collectDefaultMetrics as $t}from"@prometheus-io/client";import{createServer as Mt}from"http";var vr=9464,dt="/metrics",te="(other)",Ht="(none)",Ft=64,Gt=128,Wt=["/v1/responses","/v1/chat/completions","/v1/systemone","/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",Ye,qe,Ue],Kt=new Set(Wt);function jt(e){return Kt.has(e)?e:te}function Bt(e){return e===null?"none":e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":e>=200?"2xx":"1xx"}var ne=class{constructor(t){this.max=t}max;admitted=new Set;overflows=0;of(t,n=!0){return t===null||t===""?Ht:this.admitted.has(t)?t:n?this.admitted.size>=this.max?(this.overflows+=1,te):(this.admitted.add(t),t):te}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},re=class{registry=new Dt;modelLabel=new ne(Ft);orgLabel=new ne(Gt);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(t={}){this.buildInfo=new Z({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 M({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 ee({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 ee({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 M({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 M({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 M({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 Xe)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new Z({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"},Qe()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Ze()/1e3)}}),this.labelCardinality=new Z({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 M({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 Z({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 ee({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 ee({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 M({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 M({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]}),t.defaultMetrics!==!1&&$t({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(t){this.ledgerWrites.inc({outcome:t.outcome,reason:t.reason})}observeLaneReady(t,n){this.lanesReady.set({model:this.modelLabel.of(t)},n)}observeLanePick(t,n){this.lanePickMs.observe({model:this.modelLabel.of(t)},n)}observeLaneFirstEvent(t,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(t)},n)}observeLane503Fast(t){this.lane503Fast.inc({model:this.modelLabel.of(t)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(t){let n=jt(t.path),r=t.status!==null&&!(t.status>=400&&t.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(t.model,r),i=this.orgLabel.of(t.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 d=t.stream===!0?"true":"false";this.requests.inc({lane:n,method:t.method===""?te:t.method,status_class:Bt(t.status),stream:d,model:s,org:i}),this.duration.observe({lane:n,stream:d,model:s,org:i},t.duration_ms/1e3),t.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},t.ttft_ms/1e3),t.stream_error&&this.streamErrors.inc({lane:n,model:s}),t.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function ut(e){return Mt((t,n)=>{(async()=>{let r=(t.url??"/").split("?")[0];if(t.method!=="GET"||r!==dt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${t.method} ${r} \u2014 this port serves only GET ${dt}
2
+ `);return}let o=await e.scrape();n.writeHead(200,{"content-type":e.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()})})}S();import{createHash as ft}from"crypto";import{createServer as Vt}from"http";var Cr=9465,zt="x-urun-key-id",Yt="x-urun-key-fingerprint",Jt="urun-ratelimit-bucket:",qt="urun-ratelimit-tier:",pt="anonymous",Xt=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Qt(e){return ft("sha256").update(`${Jt}${e}`).digest("hex")}function Zt(e){return ft("sha256").update(`${qt}${e}`).digest("hex")}function en(e){let t=/^Bearer[ \t]+(\S.*)$/i.exec((e??"").trim());if(!t)return null;let n=t[1].trim();return Xt.test(n)?n:null}function gt(){return Vt((e,t)=>{let n=en(e.headers.authorization);t.setHeader(zt,n===null?pt:Qt(n)),t.setHeader(Yt,n===null?pt:Zt(n)),t.writeHead(200),t.end()})}S();import{createClientToken as tn,ClientTokenError as nn}from"@urun-sh/core";var U=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},V=class extends Error{status=402;code;constructor(t){super(t==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":t==="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=t}},H=class extends Error{detail;constructor(t,n){super(t),this.name="ControlPlaneUnavailableError",this.detail=n}};function se(e){let t=(e??"").trim();if(t==="")throw new U("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(t);if(!n)throw new U("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var rn=60,on=6e4,sn=4096;function an(e){return e===401||e===403}var oe=class{constructor(t){this.opts=t;this.mint=t.mint??tn,this.now=t.now??Date.now}opts;cache=new Map;mint;now;async resolve(t){if(t==="")throw new U("empty Authorization bearer token");let n=this.cache.get(t);if(n&&this.now()-n.at<on)return{apiKey:t,orgId:n.orgId,...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 s=await this.mint(t,{baseUrl:this.opts.gatewayUrl,expiresIn:rn});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof nn&&an(s.status)?(this.cache.delete(t),new U("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new H("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}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new H("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>=sn){let s=this.cache.keys().next();s.done||this.cache.delete(s.value)}return this.cache.set(t,{orgId:r,at:this.now(),...o}),{apiKey:t,orgId:r,...o}}clear(){this.cache.clear()}};S();var ln=8080,_e="serve",Ir="0.0.0.0";function cn(e,t,n){let r=(e[t]??"").trim();if(!r)throw new Error(`${t} is not set \u2014 ${n}`);return r}function Ur(e=process.env){let t=(e.PORT??"").trim(),n=t===""?ln:Number(t);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(t)}`);let r=Ge(X(cn(e,"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=(e.URUN_API_URL??"").trim(),s=o?X(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(e.URUN_CATALOG_URL??"").trim(),a=(e.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let d=i?{catalogUrl:X(i,"URUN_CATALOG_URL"),anonKey:a}:null,l=(e.URUN_LEDGER_SIGNING_KEY??"").trim(),u=(e.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!l!=!!u)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=l?{keyId:u,key:l}:void 0,c={docHostUrl:(e.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(e.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(e.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(e.URUN_LANE_SELF_ADDRESS??"").trim()},m=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],k=m.filter((E,w)=>Object.values(c)[w]==="");if(k.length!==0&&k.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${k.join(", ")}, which would half-configure the lane plane`);let C=k.length===0?c:void 0,A={baseUrl:(e.URUN_POOLER_URL??"").trim(),token:(e.URUN_POOLER_TOKEN??"").trim(),region:(e.URUN_POOLER_REGION??"").trim()},f=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=f.filter((E,w)=>Object.values(A)[w]==="");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 _=g.length===0?A:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:d,ledgerSigning:h,lane:C,pooler:_}}S();import{createHash as wn,randomUUID as wt}from"crypto";S();import{request as dn}from"http";var un="/pooler/v1/inference",F=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},pn=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let t=e.messages?.find(n=>n.role==="system"||n.role==="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content)},fn=e=>{let t=e.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let n=e.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)}},mt=e=>new Promise((t,n)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>t(Buffer.concat(r).toString("utf8"))),e.on("error",n)}),gn=async e=>{let t="pooler_error",n=`the pooler refused the request (HTTP ${e.status})`;try{let r=JSON.parse(await mt(e.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"&&(t=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new F(e.status,t,n,e.retryAfterSeconds)};async function hn(e,t,n,r,o){let s=new URL(`${e.baseUrl.replace(/\/+$/,"")}${un}`),i=JSON.stringify({region:e.region,model:r,request_id:n,streaming:o,payload:t,affinity:{systemPrompt:pn(t),firstMessage:fn(t)}});return new Promise((a,d)=>{let l=dn({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},u=>{let h=Number(u.headers["retry-after"]??"");a({status:u.statusCode??0,retryAfterSeconds:Number.isFinite(h)?h:void 0,body:u})});l.on("error",u=>d(new F(502,"pooler_unreachable",`the pooler channel failed: ${u.message}`))),l.end(i)})}var ht=e=>{if(!e.startsWith("data: "))return null;let t=e.slice(6).trim();if(t===""||t==="[DONE]")return null;let n;try{n=JSON.parse(t)}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*mn(e){let t="";for await(let r of e.body)for(t+=String(r);;){let o=t.indexOf(`
4
+
5
+ `);if(o===-1)break;let s=t.slice(0,o);t=t.slice(o+2);let i=ht(s);i!==null&&(yield i)}let n=ht(t);n!==null&&(yield n)}async function yt(e,t,n,r){let o=Ne(t,n,r),s=o.model??"";if(s==="")throw new F(400,"missing_model","the pooler submit requires a model");let i=await hn(e,o,n,s,t.stream===!0);if(i.status>=400)throw await gn(i);let a=t.stream===!0?me(n,mn(i)):await yn(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function yn(e,t){let n=await mt(e.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new F(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return me(t,(async function*(){yield o})())}var bn=512;function ve(e){return`urun-inference-proxy-${wn("sha256").update(e).digest("hex").slice(0,32)}`}var ie=class{constructor(t){this.opts=t}opts;tenants=new Map;label(t,n){let r=Object.assign(Object.create(t),{tenant:n.orgId}),o=this.opts.pooler;return o===void 0?r:Object.assign(Object.create(r),{createResponse:(s,i)=>{let a=`px_${wt()}`;return yt(o,s,a,a)}})}build(t){if(this.opts.build){let s=this.opts.build(t);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,t),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:t.orgId,defaultApp:null,fnName:_e,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:t.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:st(process.env,process.env.HOSTNAME)??void 0},r=we(n),o=n.decisionPool?it(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(be(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),t),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let t=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);t.unref(),this.decisionReaper=t}decisionReaper=null;clientsFor(t){let n=this.tenants.get(t.apiKey);if(n)return this.tenants.delete(t.apiKey),this.tenants.set(t.apiKey,n),n.clients;for(;this.tenants.size>=bn;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(t);return this.tenants.set(t.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let t of this.tenants.values())t.decision&&(yield t.decision)}decisionWarmerFor(t){return this.clientsFor(t),this.tenants.get(t.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let t=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(t.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},bt=512,_n=1024,ae=class extends Error{constructor(){super(`conversation capacity reached (${bt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function vn(e){return{sessionStartOptions:t=>{if(t.startsWith(ye))return;let n=e.get(t);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(t,n)=>{t.startsWith(ye)||e.set(t,n)}}}function Sn(e,t,n,r){let o=we({baseUrl:e.baseUrl,orgId:t.orgId,defaultApp:null,fnName:_e,sharedOnlyListing:!0,apiUrl:e.apiUrl,auth:{lane:"api-key",apiKey:t.apiKey,gatewayUrl:e.baseUrl},catalog:e.catalogRows?null:e.catalog,catalogRows:e.catalogRows,lanes:e.lanes,subject:n.subject,release:"detach",...vn(r)});return{clients:be(o,void 0,void 0,void 0,void 0,e.lanes),release:async()=>{await o.closeAll()}}}var le=class{constructor(t){this.opts=t}opts;byCaller=new Map;byHandle=new Map;build(t,n){let r={id:n,subject:`${ve(t.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(t,r):Sn(this.opts,t,r,o);return{id:n,backhaul:s,attachments:0,nativeRefs:o}}attachEntry(t,n){let r=this.byCaller.get(t.apiKey);r===void 0&&(r=new Map,this.byCaller.set(t.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let s=this.build(t,n);return s.attachments=1,r.set(n,s),s}get conversationCount(){let t=0;for(let n of this.byCaller.values())t+=n.size;return t}evictOverflow(){for(;this.conversationCount>=bt;){let t=this.byCaller.keys().next();if(t.done)throw new ae;let n=t.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new ae;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(t,n){for(let[r,o]of this.byHandle)o.apiKey===t&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(t){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(t,wt())),n),s={createResponse:(i,a)=>o().backhaul.clients.createResponse(i,a),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),createResponseOn:(i,a,d)=>o().backhaul.clients.createResponseOn(i,a,d),onSessionEnd:(i,a)=>o().backhaul.clients.onSessionEnd(i,a)};return s.openAudio=async(i,a)=>{let d=o().backhaul.clients.openAudio;if(d===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return d(i,a)},s.openVideo=async i=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(i)},s.openVideoOut=async i=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(i)},s.supportsAudio=async i=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(i)},s.supportsSpeech=async i=>{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(i)},s.speechVoices=async i=>{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(i)},s.speechSessionHandle=async i=>{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(i)},s.openAudioOn=async(i,a,d)=>{let l=o().backhaul.clients.openAudioOn;if(l===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 l(i,a,d)},s.openTurnsOn=(i,a)=>{let d=o().backhaul.clients.openTurnsOn;if(d===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 d(i,a)},s.evictSpeechSession=async i=>{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(i)},s.supportsTranscription=async i=>{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(i)},s.transcriptStreamFor=async i=>{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(i)},s.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:s,bindResumeHandle:i=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=_n;){let d=this.byHandle.keys().next();if(d.done)break;this.byHandle.delete(d.value)}this.byHandle.set(i,{apiKey:t.apiKey,conversationId:a.id})},clientsForResume:async i=>{let a=this.byHandle.get(i),d=a===void 0?void 0:this.byCaller.get(a.apiKey),l=a===void 0||d===void 0?void 0:d.get(a.conversationId);if(a===void 0||l===void 0||a.apiKey!==t.apiKey)throw new J("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=l,l.attachments+=1,l.backhaul.clients},release:async()=>{if(r)return;r=!0;let i=n;n=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let t=[];for(let r of this.byCaller.values())for(let o of r.values())t.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(t.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("; ")}`)}};S();var Rn="/inference-ledger",En=1e4,ce=class extends Error{ledgerFailureReason;constructor(t,n="duplicate"){super(t),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Ee=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},P=class extends Error{ledgerFailureReason="surface";constructor(t){super(t),this.name="LedgerSurfaceError"}},ke=class extends U{ledgerFailureReason="auth";constructor(t){super(t),this.name="LedgerAuthError"}},Ce=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(t){super(t),this.name="LedgerSignatureError"}},kn=[["inference_id",e=>typeof e=="string"&&/[^\s]/.test(e)],["model_id",e=>typeof e=="string"&&/[^\s]/.test(e)],["variant",e=>e===null||typeof e=="string"],["task",e=>typeof e=="string"&&/[^\s]/.test(e)],["http_status",e=>typeof e=="number"&&Number.isInteger(e)],["started_at",e=>typeof e=="string"&&!Number.isNaN(Date.parse(e))],["completed_at",e=>typeof e=="string"&&!Number.isNaN(Date.parse(e))],["prompt_tokens",e=>e===null||typeof e=="number"&&Number.isInteger(e)],["completion_tokens",e=>e===null||typeof e=="number"&&Number.isInteger(e)],["output_units",Se],["output_minutes",Se],["cost_nano_usd",Se],["price_version",e=>e===null||typeof e=="string"]];function Cn(e){for(let[t,n]of kn){if(!(t in e))return`${t} (absent)`;if(!n(e[t]))return`${t} (${JSON.stringify(e[t])})`}return null}function Ln(e){let t;try{t=JSON.parse(e)}catch{return{status:"unavailable"}}if(t===null||typeof t!="object"||Array.isArray(t))return{status:"unavailable"};let n=t.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=t.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Cn(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Se(e){return e===null?!0:typeof e=="number"?Number.isFinite(e):typeof e!="string"?!1:/[^\s]/.test(e)&&Number.isFinite(Number(e))}function Re(e,t){return e===null?t===null:t===null?!1:Number(t)===e}function An(e,t){return e===null?t===null:t===null?!1:Number(e.toFixed(9))===Number(t)}function _t(e,t){if(typeof t!="string")return!1;let n=Date.parse(e),r=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Pn(e,t){let n=t;return n.inference_id===e.inference_id&&n.model_id===e.model_id&&(n.variant??null)===e.variant&&n.task===e.task&&n.http_status===e.http_status&&_t(e.started_at,n.started_at)&&_t(e.completed_at,n.completed_at)&&Re(e.prompt_tokens,n.prompt_tokens)&&Re(e.completion_tokens,n.completion_tokens)&&Re(e.output_units,n.output_units)&&An(e.output_minutes,n.output_minutes)}function On(e){let t=r=>String(r??null),n="session_seconds"in e?e.session_seconds:null;return["urun-ledger-write-v2",e.inference_id,e.model_id,t(e.variant),e.identity_kind,e.task,t(e.prompt_tokens),t(e.completion_tokens),t(e.output_units),t(e.output_minutes),t(e.output_seconds),t(n),e.started_at,e.completed_at].join(`
6
+ `)}async function Tn(e,t){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(t.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(On(e)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:t.keyId}}function Nn(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new P(`${t} answered a "recorded" that is not an object: ${JSON.stringify(e)}`);let n=e,r=n.inference_id;if(typeof r!="string"||r==="")throw new P(`${t} answered a row with no inference_id: ${JSON.stringify(e)}`);if(!("cost_nano_usd"in n))throw new P(`${t} answered a row with no cost_nano_usd field: ${JSON.stringify(e)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new P(`${t} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=l=>{if(!(l in n))throw new P(`${t} answered a row with no ${l} field: ${JSON.stringify(e)}`);let u=n[l];if(u===null)return null;if(typeof u!="string")throw new P(`${t} answered a non-string ${l}: ${JSON.stringify(u)}`);if(!/[^\s]/.test(u))throw new P(`${t} answered a BLANK ${l} (${JSON.stringify(u)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return u},i=s("price_version"),a=s("unpriced_reason"),d=o!=null;if(d&&(i===null||a!==null))throw new P(`${t} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!d&&(i!==null||a===null))throw new P(`${t} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var de=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async write(t,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Rn}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Tn(n,this.opts.signing)}):JSON.stringify(n)}catch(l){throw new P(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${l instanceof Error?l.message:String(l)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:o,signal:AbortSignal.timeout(En)})}catch(l){throw new P(`the uRun ledger surface at ${r} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(s.status===409){let l=await s.text().catch(()=>""),u=Ln(l);throw u.status==="found"&&Pn(n,u.row)?new Ee(u.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.`):u.status==="not_in_this_org"?new ce(`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 ce(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${u.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). ${l.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new ke("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let l=await s.text().catch(h=>`<body unreadable: ${h instanceof Error?h.message:String(h)}>`),u;try{let h=JSON.parse(l);if(h!==null&&typeof h=="object"&&"error"in h){let c=h.error;c!==null&&typeof c=="object"&&"code"in c&&(u=c.code)}}catch{}throw u==="ledger_signature_invalid"?new Ce(`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: `+l.slice(0,400)):new P(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${l.slice(0,400)}`)}let i;try{i=await s.json()}catch(l){throw new P(`the uRun ledger surface at ${r} answered a body that is not JSON: ${l instanceof Error?l.message:String(l)}`)}let a=i?.recorded;if(a===void 0)throw new P(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let d=Nn(a,`the uRun ledger surface at ${r}`);if(d.inference_id!==n.inference_id)throw new P(`the uRun ledger surface at ${r} answered for inference_id ${d.inference_id} when asked about ${n.inference_id}`);return d}};S();import{createServer as ar}from"http";S();import{createWebsocketDocConnector as $n}from"@urun-sh/core/internal";import Mn from"ws";S();import*as G from"yjs";import{SessionDocumentImpl as In}from"@urun-sh/core/internal";var Un=3e4;function xn(e){return(t,n,r)=>{let o=e(t);G.applyUpdate(n,G.encodeStateAsUpdate(o));let s=a=>G.applyUpdate(o,a),i=a=>G.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}async function*Dn(e,t){let n=[],r=!1,o=null,s="",i=d=>{if(!("responses"in d)||typeof d.responses!="object"||d.responses===null)return null;let l=d.responses;if(!(t in l))return null;let u=l[t];if(u===null||typeof u!="object"||!("error"in u))return{body:u,error:null};let h=u.error;return h===null?{body:u,error:null}:{body:u,error:h}},a=d=>{let l={};for(let[h,c]of Object.entries(d)){let m=c;l[h]=typeof m?.toJSON=="function"?m.toJSON():c}if("tokens"in l&&typeof l.tokens=="object"&&l.tokens!==null){let h=l.tokens[t];typeof h=="string"&&h.length>s.length&&(n.push({t:"delta",delta:h.slice(s.length)}),s=h)}let u=i(l);if(u!==null){u.error!==null?n.push({t:"error",body:u.error}):n.push({t:"response",body:u.body}),r=!0,o?.(),o=null;return}if("progress"in l&&typeof l.progress=="object"&&l.progress!==null){let h=l.progress[t];if(typeof h=="object"&&h!==null&&"state"in h&&h.state==="error"){let m="error"in h&&typeof h.error=="string"?h.error:"lane request failed";n.push({t:"error",body:{message:m}}),r=!0,o?.(),o=null;return}}o?.(),o=null};if(a(e.get()??{}),!r){let d=e.on("change",a);try{for(;!r;){if(n.length>0){yield n.shift();continue}await new Promise(l=>{o=l})}}finally{d()}}for(;n.length>0;)yield n.shift()}function Le(e){let{laneId:t}=e,n=e.connector??(e.roomDoc?xn(e.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${t} is destroyed \u2014 the doc host shut down or the lane was evicted`);let l=r.get(d);return l||(l=new In(d,t,n),r.set(d,l)),l},i=d=>{let l="llm-resp:";if(!d.startsWith(l))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${l}<rid>)`);let u=d.slice(l.length);return{messages:()=>Dn(s("llm"),u),attach:async()=>{throw new Error("lane session carries no media track \u2014 the doc mirror IS the reply lane")},detach:async()=>{},track:null}};return{id:t,sessionId:t,consumerId:e.consumerId??`lane-${t}`,doc(d){return s(d)},stream:i,async end(){},async whenLive(d){let l=s("llm");if(l.synced===!0)return;let u=d?.timeout??e.whenLiveTimeoutMs??Un;await new Promise((h,c)=>{let m=setTimeout(()=>{k(),c(new Error(`lane ${t} llm doc never synced within ${u}ms`))},u),k=l.onSynced(()=>{clearTimeout(m),d?.signal?.removeEventListener("abort",C),h()}),C=()=>{clearTimeout(m),k(),c(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",C,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear()}}}function Hn(e){let t=(e.gpuSpec??"").split(":")[0];if(typeof e.appId!="string"||e.appId==="")throw new Me(`the shared lane target (app slug "${e.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`${t}.${e.appId}.${e.fnName??""}`}function vt(e){let t=e.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(c,m,k,C,A)=>{let f=k?Le({laneId:c,roomDoc:E=>e.roomDoc(c,E)}):Le({laneId:c,connector:$n({serverUrl:`ws://${C}/doc`,sessionId:c,token:()=>lt(c,e.tokenSecret,void 0,void 0,A),WebSocketPolyfill:Mn})}),g=k?a(c):ot(f,`lane:${c}`,{armOnFirstSync:!0}),_={session:f,responses:new Ie(f),gone:g,goneWatch:g,laneId:c,pool:m,inFlight:0,laneSession:f,self:k,host:C??""};return n.set(c,_),g.onGone(()=>d(_)),_},a=c=>{let m=null,k=!1,C=new Set,A=g=>{if(!m){m=g;for(let _ of[...C])_(g);C.clear()}},f=e.hostedSignal?.(c,g=>{if(g){k=!0;return}k&&A(new J(`the lane ${c} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>m,onGone(g){return m?(g(m),()=>{}):(C.add(g),()=>C.delete(g))},dispose(){f?.(),C.clear()}}},d=c=>{l(c)&&(n.delete(c.laneId),r.delete(c.laneId),c.goneWatch?.dispose())},l=c=>{let m=c.laneId;return typeof m=="string"&&n.get(m)===c},u=(c,m)=>{throw e.metrics?.observeLane503Fast(m??""),s.set(c,t()),new q(c)},h=async(c,m)=>{let k=Hn(m);o.add(k);let C=t();try{let A=await e.laneWarmWaitMsFor?.(c,m)??e.laneColdWakeDefaultMs??0,f=await e.plane.pick({pool:k,model:c,holdMs:A});e.metrics?.observeLaneReady(c??"",f.length);let _=f.map(w=>({laneId:w.laneId,self:w.host===e.selfAddress,host:w.host})).sort((w,p)=>w.self!==p.self?w.self?-1:1:(r.get(w.laneId)??0)-(r.get(p.laneId)??0))[0];_||u(k,c);let E=n.get(_.laneId);return E?.goneWatch?.gone()&&(d(E),E=void 0),E&&(E.pool!==k||E.self!==_.self||E.host!==_.host)&&(d(E),E=void 0),E||(E=i(_.laneId,k,_.self,_.host,m.sharedOrgId??void 0)),E.inFlight+=1,r.set(_.laneId,(r.get(_.laneId)??0)+1),{app:k,entry:E,identity:{kind:"catalog",model_id:m.modelId??c??"",variant:m.variant??""}}}finally{e.metrics?.observeLanePick(c??"",t()-C)}};return{sessionFor(c,m){return h(c,m)},release(c){l(c)&&(c.inFlight=Math.max(0,c.inFlight-1),r.set(c.laneId,c.inFlight))},owns(c){return l(c)},entryFor(c){return n.get(c)??null},evict(c){l(c)&&(c.gone.dispose(),n.delete(c.laneId),r.set(c.laneId,0),c.laneSession.destroy())},async status(){let c=[...new Set([...o,...[...n.values()].map(C=>C.pool)])].sort(),m=await e.plane.status().catch(()=>[]),k=new Map(Fn(m));return Promise.all(c.map(async C=>{let A=k.get(C)??{pool:C,lanes:[],lastDemandAt:null};return{pool:C,lanes:A.lanes,lastDemandAt:A.lastDemandAt,local:[...n.values()].filter(f=>f.pool===C).map(f=>({laneId:f.laneId,inFlight:f.inFlight,self:f.self,host:f.host})),lastRefusalAt:s.get(C)??null}}))},async close(){for(let c of n.values())c.gone.dispose(),c.laneSession.destroy();n.clear(),r.clear(),await e.plane.close()},stats(){return[...n.values()].map(c=>({pool:c.pool,laneId:c.laneId,inFlight:c.inFlight}))}}}function Fn(e){return new Map(e.map(t=>[t.pool,{lanes:t.lanes,lastDemandAt:t.lastDemandAt}]))}S();import{request as Gn}from"http";var Wn="/pooler/v1/lanes/pick",Kn="/pooler/v1/lanes/status",jn=1e4;function St(e,t,n,r,o){return new Promise((s,i)=>{let a=new URL(n,e.baseUrl),d=r===void 0?void 0:Buffer.from(JSON.stringify(r)),l=Gn({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:t,headers:{authorization:`Bearer ${e.token}`,...d===void 0?{}:{"content-type":"application/json","content-length":String(d.byteLength)}},timeout:o},u=>{let h=[];u.on("data",c=>h.push(c)),u.on("end",()=>{let c=Buffer.concat(h).toString("utf8"),m=null;try{m=c===""?null:JSON.parse(c)}catch{m=null}s({status:u.statusCode??0,json:m})}),u.on("error",i)});l.on("timeout",()=>{l.destroy(new Error(`pooler lane surface timed out after ${o}ms (${t} ${n})`))}),l.on("error",i),l.end(d)})}function Rt(e,t,n){if(e===503)return new q(n);let r=t!==null&&typeof t=="object"&&typeof t.error=="object"?JSON.stringify(t.error):`status ${e}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function Et(e){return{async pick({pool:t,model:n,holdMs:r=0}){let o=await St(e,"POST",Wn,{pool:t,model:n,hold_ms:r},r+jn);if(o.status!==200)throw Rt(o.status,o.json,t);return(o.json?.lanes??[]).filter(i=>typeof i.lane_id=="string"&&i.lane_id!==""&&typeof i.host=="string"&&i.host!=="").map(i=>({laneId:i.lane_id,host:i.host}))},async status(){let t=await St(e,"GET",Kn,void 0,5e3);if(t.status!==200)throw Rt(t.status,t.json,"");let n=t.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}S();import{WebSocketServer as nr}from"ws";S();import*as Ct from"yjs";import*as j from"y-protocols/sync";import*as D from"y-protocols/awareness";import*as L from"lib0/encoding";import*as B from"lib0/decoding";import*as Lt from"lib0/map";import Vn from"lodash.debounce";S();var kt=()=>{};var zn=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Yn=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Jn=0,qn=1;var Xn=process.env.GC!=="false"&&process.env.GC!=="0",Qn=process.env.YPERSISTENCE,ue=null;if(typeof Qn=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var K=new Map,pe=0,Pe=1,Zn=(e,t,n)=>{let r=L.createEncoder();L.writeVarUint(r,pe),j.writeUpdate(r,e);let o=L.toUint8Array(r);n.conns.forEach((s,i)=>z(n,i,o))},Ae=class extends Ct.Doc{constructor(t){super({gc:Xn}),this.name=t,this.conns=new Map,this.awareness=new D.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let u=this.conns.get(i);u!==void 0&&(r.forEach(h=>{u.add(h)}),s.forEach(h=>{u.delete(h)}))}let d=L.createEncoder();L.writeVarUint(d,Pe),L.writeVarUint8Array(d,D.encodeAwarenessUpdate(this.awareness,a));let l=L.toUint8Array(d);this.conns.forEach((u,h)=>{z(this,h,l)})};this.awareness.on("update",n),this.on("update",Zn),!1}},Oe=(e,t=!0)=>Lt.setIfUndefined(K,e,()=>{let n=new Ae(e);return n.gc=t,ue!==null&&ue.bindState(e,n),K.set(e,n),n}),er=(e,t,n)=>{try{let r=L.createEncoder(),o=B.createDecoder(n);switch(B.readVarUint(o)){case pe:L.writeVarUint(r,pe),j.readSyncMessage(o,r,t,e),L.length(r)>1&&z(t,e,L.toUint8Array(r));break;case Pe:{D.applyAwarenessUpdate(t.awareness,B.readVarUint8Array(o),e);break}}}catch(r){console.error(r),t.emit("error",[r])}},W=(e,t)=>{if(e.conns.has(t)){let n=e.conns.get(t);e.conns.delete(t),D.removeAwarenessStates(e.awareness,Array.from(n),null),e.conns.size===0&&ue!==null&&(ue.writeState(e.name,e).then(()=>{e.destroy()}),K.delete(e.name))}t.close()},z=(e,t,n)=>{t.readyState!==Jn&&t.readyState!==qn&&W(e,t);try{t.send(n,r=>{r!=null&&W(e,t)})}catch{W(e,t)}},tr=3e4,At=(e,t,{docName:n=t.url.slice(1).split("?")[0],gc:r=!0}={})=>{e.binaryType="arraybuffer";let o=Oe(n,r);o.conns.set(e,new Set),e.on("message",a=>er(e,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(e)&&W(o,e),clearInterval(i);else if(o.conns.has(e)){s=!1;try{e.ping()}catch{W(o,e),clearInterval(i)}}},tr);e.on("close",()=>{W(o,e),clearInterval(i)}),e.on("pong",()=>{s=!0});{let a=L.createEncoder();L.writeVarUint(a,pe),j.writeSyncStep1(a,o),z(o,e,L.toUint8Array(a));let d=o.awareness.getStates();if(d.size>0){let l=L.createEncoder();L.writeVarUint(l,Pe),L.writeVarUint8Array(l,D.encodeAwarenessUpdate(o.awareness,Array.from(d.keys()))),z(o,e,L.toUint8Array(l))}}};var Te="/doc/",Ot=30,rr=1e4,Pt="llm";function or(e){if(!e.startsWith(Te))return null;let t=e.slice(Te.length),n=t.indexOf("/");return n<=0||n===t.length-1||t.includes("/",n+1)?null:{laneId:t.slice(0,n),docName:t.slice(n+1)}}function Y(e,t,n){let r=t===401?"Unauthorized":t===403?"Forbidden":t===404?"Not Found":"Internal Server Error",o=`${n}\r
7
+ `;e.end(`HTTP/1.1 ${t} ${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 Tt(e,t){let n=new nr({noServer:!0}),r=new Set,o=new Map,s=new Map,i=f=>o.get(`${f}/${Pt}`)??0,a=f=>s.get(f)??0,d=new Map,l=new Map,u=new Set,h=new Set,c=!1,m=(f,g,_)=>{let E=i(f)>0,w=a(f),p=w>0,y=`${f}/${g}`,v=o.get(y)??0;_>0?o.set(y,_):o.delete(y);let b=w+_-v;b>0?s.set(f,b):s.delete(f);let R=i(f)>0,N=b>0;if(E!==R){R?k(f):C(f);for(let I of d.get(f)??[])I(R)}p&&!N&&queueMicrotask(()=>{let I=`${f}/`;for(let[$,x]of[...K.entries()])!$.startsWith(I)||x.conns.size>0||(K.delete($),x.destroy())})},k=f=>{if(!t.hostRegistry||l.has(f))return;let g=()=>{t.hostRegistry?.setHost(f,t.selfAddress).catch(()=>{})};g();let _=setInterval(g,rr);_.unref?.(),l.set(f,_)},C=f=>{let g=l.get(f);g&&(clearInterval(g),l.delete(f)),t.hostRegistry&&t.hostRegistry.delHost(f,t.selfAddress).catch(()=>{})},A=(f,g,_)=>{let E;try{E=new URL(f.url??"/","http://localhost")}catch{Y(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>h.delete(g));let w=or(E.pathname);if(!w){if(E.pathname.startsWith(Te)){Y(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}h.add(g);return}u.add(g);let p=!1;(async()=>{let y=E.searchParams.get("token")??"",v=null;try{v=y===""?null:await t.verifyToken(y,w.laneId,w.docName)}catch{v=null}if(v===null){Y(g,401,"invalid or missing lane doc token");return}let b=v;if(b.tenant!==void 0&&t.laneTenantOf){let R=null;try{R=await t.laneTenantOf(w.laneId)}catch{R=null}if(R==null||R==="")t.onLaneTenantMissing?.();else if(b.tenant!==R){Y(g,403,"lane doc token org does not match the lane record");return}}c||g.destroyed||(p=!0,n.handleUpgrade(f,g,_,R=>{u.delete(g),r.add(R),R.on("close",()=>r.delete(R));let N=b.scope===at||b.scope===void 0&&typeof b.app=="string"&&typeof b.fn=="string"&&b.aud==="sfu";if(N){let $=`${w.laneId}/${w.docName}`,x=(o.get($)??0)+1;m(w.laneId,w.docName,x),x>1&&w.docName===Pt&&t.hostRegistry?.setHost(w.laneId,t.selfAddress).catch(()=>{})}R.on("close",()=>{if(!N)return;let $=`${w.laneId}/${w.docName}`;m(w.laneId,w.docName,Math.max(0,(o.get($)??1)-1))}),At(R,f,{docName:`${w.laneId}/${w.docName}`,gc:!0})}))})().catch(()=>{!p&&!g.destroyed&&Y(g,500,"lane doc upgrade failed")}).finally(()=>u.delete(g))};return e.on("upgrade",A),{async close(){c=!0,e.off("upgrade",A);for(let g of[...l.keys()])C(g);await new Promise(g=>{if(r.size===0&&u.size===0){g();return}let _=r.size+u.size,E=()=>{_-=1,_<=0&&g()};for(let w of r)w.once("close",E);for(let w of u)w.once("close",E);for(let w of r)w.close(1001,"lane doc host shutting down");for(let w of u)w.destroy()}),o.clear(),s.clear(),d.clear()},roomDoc(f,g){return Oe(`${f}/${g}`,!0)},isHosted(f){return i(f)>0},onHostedChange(f,g){let _=d.get(f);return _||(_=new Set,d.set(f,_)),_.add(g),g(i(f)>0),()=>{_.delete(g)}}}}S();var sr="urun:catalog:v1";function Nt(e){let t=e.refreshMs??5e3,n=e.now??Date.now,r=null,o=0,s=null,i=async()=>{let d=await e.redis.hgetall(sr),l=[];for(let u of Object.values(d))try{l.push(JSON.parse(u))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
13
+ `)}return r=l,o=n(),l},a=()=>r===null||n()-o>=t;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}import lr from"ioredis";S();var fe="/inference-usage",It=25e3;var ir=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ut(e){if(!(e instanceof Error))return`a ${typeof e}`;let t=ir.has(e.name)?e.name:"Error",n=e.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${t} (${n})`:t}var ge=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async lookup(t,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${fe}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(It)})}catch(i){throw new Q(`the uRun usage surface (POST ${fe}) could not be reached within ${It}ms: ${Ut(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new U("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new Q(`the uRun usage surface (POST ${fe}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new Q(`the uRun usage surface (POST ${fe}) answered HTTP ${o.status} with a body that is not JSON: ${Ut(i)}`)}return Je(s,this.opts.onRejectedRow)}};var cr=5e3,dr=1e3,ur=1500,pr=3e3,fr="/api/client-tokens";function he(e,t,n){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))}function xt(e,t,n,r){he(e,t,{error:{message:n,type:r}})}async function gr(e,t=fetch){let n=`${e.replace(/\/+$/,"")}${fr}`;try{let r=await t(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(pr)});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 ts(e){let t=e.resolver??new oe({gatewayUrl:e.baseUrl}),n=new re(e.defaultMetrics===void 0?{}:{defaultMetrics:e.defaultMetrics}),r=null,o=(()=>{if(!e.lane)return null;if(!e.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 lr(e.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),y=Nt({redis:p});return{registry:vt({selfAddress:e.lane.selfAddress,tokenSecret:e.lane.tokenSecret,plane:Et({baseUrl:e.pooler.baseUrl,token:e.pooler.token}),hostedSignal:(b,R)=>r?.onHostedChange(b,R)??(()=>()=>{}),roomDoc:(b,R)=>{if(!r)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return r.roomDoc(b,R)},metrics:n,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(b,R)=>y.rows().then(N=>{let I=xe(N,R);return I?.warm_wait_s!==void 0?I.warm_wait_s*1e3:void 0})}),catalog:y,redis:p}})(),s=e.registry??new ie({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:o?null:e.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry,pooler:e.pooler}),i=e.probeControlPlane??(()=>gr(e.baseUrl)),a=async()=>{let p=null;for(let b of s.decisionPools()){p=b;break}if(!p)return null;let y=p.stats();if(y.some(b=>b.draining))return{ok:!1,detail:"decision pool draining"};if(y.every(b=>b.attached===0&&b.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let v=await p.pingReady(ur);return{ok:v,detail:v?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=e.usageClient??new ge({apiUrl:e.apiUrl}),l=e.ledgerClient??new de({apiUrl:e.apiUrl,...e.ledgerSigning?{signing:e.ledgerSigning}:{}}),u=process.env.URUN_SHARED_ORG_ID?.trim(),h=process.env.URUN_SHARED_ORG_API_KEY?.trim();u&&h&&(async()=>{try{await s.decisionWarmerFor({orgId:u,apiKey:h})?.warmFor(nt)}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)}
14
+ `)}})();let c=async p=>t.resolve(se(p.headers.authorization)),m=async p=>{let y=await c(p);if(y.billingAudience==="platform"&&y.creditsAdmissionOk===!1){let v=y.creditsRefusalReason;throw new V(v==="spend_cap_reached"||v==="insufficient_credits"?v:void 0)}return y},k=p=>p instanceof U?{status:p.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:p instanceof V?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...p.code!==void 0?{code:p.code}:{}}:p instanceof H?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:p.detail}:null,C=rt({clients:async p=>s.clientsFor(await m(p)),usage:{authorize:p=>se(p.headers.authorization),lookup:(p,y)=>d.lookup(p,y)},statusOf:k,...e.requestLog?{requestLog:e.requestLog}:{},observe:p=>n.observe(p),ledger:{write:(p,y)=>l.write(se(p.headers.authorization),y),observe:p=>n.observeLedger(p),...e.ledgerLog?{report:e.ledgerLog}:{}}}),A=null,f=null,g=ar((p,y)=>{let v=new URL(p.url??"/","http://localhost");(async()=>{if(p.method==="GET"&&v.pathname==="/healthz"){he(y,200,{ok:!0});return}if(p.method==="GET"&&v.pathname==="/readyz"){let N=Date.now();if((!A||N-A.at>=cr)&&(A={at:N,...await i()}),!f||N-f.at>=dr){let x=await a();f=x===null?{at:N,ok:!0,detail:null}:{at:N,ok:x.ok,detail:x.detail}}let I=(A?.ready??!1)&&f.ok,$=f.detail===null?A?.detail??"control plane not yet probed":`${A?.detail??"control plane not yet probed"}; ${f.detail}`;he(y,I?200:503,{ok:I,control_plane:$});return}if(p.method==="GET"&&v.pathname==="/lanez"){he(y,200,{pools:o?await o.registry.status():null});return}let b=v.pathname==="/v1"||v.pathname.startsWith("/v1/"),R=v.pathname.startsWith("/partners/");if(!b&&!R){xt(y,404,`no route for ${p.method} ${v.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}C(p,y)})().catch(b=>{if(!y.headersSent){xt(y,500,String(b instanceof Error?b.message:b),"proxy_error");return}y.end()})}),_=e.conversations??new le({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:o?null:e.catalog,catalogRows:o?()=>o.catalog.rows():void 0,lanes:o?.registry}),E=[$e(g,{authenticate:async p=>{let y=await t.resolve(p),v=_.connectionFor(y);return{clients:v.clients,scope:ve(y.apiKey),onBindResumeHandle:v.bindResumeHandle,clientsForResume:v.clientsForResume,release:v.release}}}),Fe(g,{clients:async p=>s.clientsFor(await m(p)),statusOf:k}).close,Ke(g,{resolver:{resolve:async(p,y)=>{let v=await m(p),b=_.connectionFor(v),R;try{R=await ze(je(b.clients,e.realtimeCompanions),Be(p),y,Ve(p))}catch(I){throw b.release().catch(()=>{}),I}let N=R.release;return{...R,release:async()=>{await N?.(),await b.release()}}}}})];if(e.lane&&o){let p=e.lane,y=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;r=Tt(g,{verifyToken:(b,R)=>ct(b,R,p.tokenSecret,void 0,y),selfAddress:p.selfAddress,laneTenantOf:b=>o.redis.get(`lane_tenant:${b}`),onLaneTenantMissing:()=>n.observeLaneDocTenantMissing(),previousTokenSecret:y,hostRegistry:{setHost:(b,R)=>o.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:${b}`,R,String(Ot)),delHost:b=>o.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${b}`,p.selfAddress)}});let v=o;E.push(async()=>{await r.close(),await v.registry.close(),v.redis.quit().catch(()=>{})})}g.on("upgrade",(p,y)=>{let v=new URL(p.url??"/","http://localhost");v.pathname===De||v.pathname===He||v.pathname===We||r!==null&&v.pathname.startsWith("/doc/")||y.destroyed||(y.write(`HTTP/1.1 404 Not Found\r
15
+ Connection: close\r
16
+ \r
17
+ no WS route for ${v.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let w=async()=>{for(let p of E)await p();await _.detachAll()};return{server:g,metricsServer:ut(n),metrics:n,edgeIdentityServer:gt(),registry:s,closeAll:()=>s.closeAll(),closeWebSockets:w}}async function ns(e,t,n){n&&await n();let r=new Promise(o=>e.close(()=>o()));e.closeAllConnections(),await r,await et()||tt(),await t()}export{vr as a,dt as b,te as c,Ht as d,Ft as e,Gt as f,jt as g,Bt as h,ne as i,re as j,ut as k,Cr as l,zt as m,Yt as n,Jt as o,qt as p,pt as q,Qt as r,Zt as s,en as t,gt as u,U as v,H as w,se as x,on as y,sn as z,oe as A,ln as B,_e as C,Ir as D,Ur as E,bn as F,ve as G,ie as H,bt as I,_n as J,ae as K,le as L,Rn as M,En as N,ce as O,P,Nn as Q,de as R,cr as S,pr as T,ts as U,ns as V};
@@ -2657,6 +2657,9 @@ interface ProxyHandlerOptions {
2657
2657
  openaiType: string;
2658
2658
  anthropicType: string;
2659
2659
  operatorDetail?: string;
2660
+ /** The machine-readable `error.code` for envelopes that carry one (the
2661
+ * Anthropic envelope never does). Absent = the body carries no code. */
2662
+ code?: string;
2660
2663
  } | null;
2661
2664
  /**
2662
2665
  * Where the per-request structured log line goes — ONE newline-terminated
@@ -640,6 +640,8 @@ interface ProxyHandlerOptions {
640
640
  openaiType: string;
641
641
  anthropicType: string;
642
642
  operatorDetail?: string;
643
+
644
+ code?: string;
643
645
  } | null;
644
646
 
645
647
  requestLog?: (line: string) => void;