@urun-sh/openai 0.6.35 → 0.6.36

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.
Files changed (46) hide show
  1. package/dist/{ResponsesClient-_OZERUjH.d.cts → ResponsesClient-6QsC7NPJ.d.cts} +4 -1
  2. package/dist/{ResponsesClient-CSSrOYD8.d.ts → ResponsesClient-gfg7qUoE.d.ts} +4 -1
  3. package/dist/chunk-4NMMWAKD.js +1 -0
  4. package/dist/chunk-EPG5XWHE.js +64 -0
  5. package/dist/{chunk-ETX6IX25.js → chunk-GX243AIV.js} +1 -1
  6. package/dist/chunk-KKCUIOL4.js +1 -0
  7. package/dist/{chunk-ITPXS7D4.js → chunk-KXKTXZKG.js} +1 -1
  8. package/dist/chunk-OEITGJY2.js +2 -0
  9. package/dist/chunk-T6RD7TSR.js +23 -0
  10. package/dist/{composite-DGytPb8F.d.cts → composite-C6Gw4HfK.d.cts} +4 -4
  11. package/dist/gemini-live.cjs +1 -1
  12. package/dist/gemini-live.d.cts +10 -1
  13. package/dist/gemini-live.d.ts +3 -1
  14. package/dist/gemini-live.js +1 -1
  15. package/dist/hosted/bin.cjs +57 -47
  16. package/dist/hosted/bin.js +1 -1
  17. package/dist/hosted/index.cjs +53 -43
  18. package/dist/hosted/index.d.cts +2 -2
  19. package/dist/hosted/index.d.ts +2 -2
  20. package/dist/hosted/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.cts +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/pi-extension/index.cjs +4 -4
  26. package/dist/pi-extension/index.d.cts +1 -1
  27. package/dist/pi-extension/index.d.ts +1 -1
  28. package/dist/pi-extension/index.js +1 -1
  29. package/dist/pi-extension/standalone.cjs +51 -51
  30. package/dist/pooler/bin.cjs +20 -20
  31. package/dist/pooler/bin.js +24 -24
  32. package/dist/proxy/cli.cjs +58 -54
  33. package/dist/proxy/cli.js +1 -1
  34. package/dist/proxy/conformance-probe.cjs +1 -1
  35. package/dist/proxy/conformance-probe.js +1 -1
  36. package/dist/proxy/index.cjs +33 -29
  37. package/dist/proxy/index.d.cts +2 -2
  38. package/dist/proxy/index.d.ts +2 -2
  39. package/dist/proxy/index.js +1 -1
  40. package/package.json +2 -2
  41. package/dist/chunk-5VMB5HKE.js +0 -17
  42. package/dist/chunk-EV4DZCHN.js +0 -1
  43. package/dist/chunk-LOPBORFM.js +0 -60
  44. package/dist/chunk-PAYCMH5F.js +0 -1
  45. package/dist/chunk-UO6N5FH7.js +0 -2
  46. /package/dist/{composite-D4oZXeX4.d.ts → composite-DAZrZyLN.d.ts} +0 -0
@@ -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-DGytPb8F.cjs';
3
- export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-DGytPb8F.cjs';
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';
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';
@@ -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-D4oZXeX4.js';
3
- export { D as DialObserver, a as DialReport, g as ProxyIdentity, h as ProxyVideoOutLane, S as SessionGoneError, U as UnknownModelError } from '../composite-D4oZXeX4.js';
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';
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';
@@ -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-LOPBORFM.js";import{a as o,h as t}from"../chunk-3JWYIKHM.js";import"../chunk-6M5JK4YC.js";import"../chunk-ITPXS7D4.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-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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/openai",
3
- "version": "0.6.35",
3
+ "version": "0.6.36",
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.35"
73
+ "@urun-sh/core": "^0.6.36"
74
74
  },
75
75
  "dependencies": {
76
76
  "@prometheus-io/client": "^0.16.1",
@@ -1,17 +0,0 @@
1
- import{a as lt,c as _e,d as ct,e as ve}from"./chunk-UO6N5FH7.js";import{A as rt,B as ot,C as st,D as it,b as Fe,d as Ge,e as q,j as je,k as We,m as Be,n as Je,o as Ve,p as ze,q as Ye,r as qe,t as Xe,u as Q,v as Qe,w as Ze,x as et,y as tt,z as nt}from"./chunk-LOPBORFM.js";import{a as He}from"./chunk-3JWYIKHM.js";import{a as dt,b as ut,c as ft}from"./chunk-PAYCMH5F.js";import{a as at}from"./chunk-GQTWIDJ6.js";import{l as Ke,m as X}from"./chunk-ITPXS7D4.js";import{a as $e}from"./chunk-EV4DZCHN.js";import{b as xe,d as we}from"./chunk-ETX6IX25.js";import{e as De,j as Y,n as Me,o as be}from"./chunk-6K7NOPD5.js";import{c as E}from"./chunk-YSFSRI3D.js";E();import{Counter as H,Gauge as Z,Histogram as ee,Registry as Gt,collectDefaultMetrics as jt}from"@prometheus-io/client";import{createServer as Wt}from"http";var Pr=9464,pt="/metrics",te="(other)",Kt="(none)",Bt=64,Jt=128,Vt=["/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",Xe,Ze,De],zt=new Set(Vt);function Yt(e){return zt.has(e)?e:te}function qt(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===""?Kt: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 Gt;modelLabel=new ne(Bt);orgLabel=new ne(Jt);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 H({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 H({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 H({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 H({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of et)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new 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"},tt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},nt()/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 H({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 H({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 H({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&&jt({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=Yt(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:qt(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 gt(e){return Wt((t,n)=>{(async()=>{let r=(t.url??"/").split("?")[0];if(t.method!=="GET"||r!==pt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${t.method} ${r} \u2014 this port serves only GET ${pt}
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()})})}E();import{createHash as mt}from"crypto";import{createServer as Xt}from"http";var $r=9465,Qt="x-urun-key-id",Zt="x-urun-key-fingerprint",en="urun-ratelimit-bucket:",tn="urun-ratelimit-tier:",ht="anonymous",nn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function rn(e){return mt("sha256").update(`${en}${e}`).digest("hex")}function on(e){return mt("sha256").update(`${tn}${e}`).digest("hex")}function sn(e){let t=/^Bearer[ \t]+(\S.*)$/i.exec((e??"").trim());if(!t)return null;let n=t[1].trim();return nn.test(n)?n:null}function yt(){return Xt((e,t)=>{let n=sn(e.headers.authorization);t.setHeader(Qt,n===null?ht:rn(n)),t.setHeader(Zt,n===null?ht:on(n)),t.writeHead(200),t.end()})}E();import{createClientToken as an,ClientTokenError as ln}from"@urun-sh/core";import{createPublicKey as cn,verify as dn}from"crypto";var wt="urun-session-gateway",un="machine",fn=3e5;function pn(e){let t=e.split(".");return t.length===3&&t[0]!==""&&t[1]!==""&&t[2]!==""}var N=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},J=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}},$=class extends Error{detail;constructor(t,n){super(t),this.name="ControlPlaneUnavailableError",this.detail=n}};function ie(e){let t=(e??"").trim();if(t==="")throw new N("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 N("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var gn=60,hn=6e4,mn=4096;function yn(e){return e===401||e===403}var oe=class{constructor(t){this.opts=t;this.mint=t.mint??an,this.now=t.now??Date.now}opts;cache=new Map;mint;now;async resolve(t){if(t==="")throw new N("empty Authorization bearer token");let n=this.cache.get(t);if(n&&this.now()-n.at<hn)return{apiKey:t,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 s=await this.mint(t,{baseUrl:this.opts.gatewayUrl,expiresIn:gn});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 ln&&yn(s.status)?(this.cache.delete(t),new N("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new $("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 $("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>=mn){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,credential:"api-key",...o}}clear(){this.cache.clear()}};function bt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}var se=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch,this.now=t.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(t){if(!t&&this.jwks!==null&&this.now()-this.jwks.at<fn)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(i){throw new $("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}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new $("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 s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new $("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`);s=i.keys}catch(i){throw i instanceof $?i:new $("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 s})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(t){let[n,r,o]=t.split(".");if(n===void 0||r===void 0||o===void 0)throw new N("malformed machine token");let s,i;try{s=bt(n),i=bt(r)}catch{throw new N("malformed machine token")}if(s.alg!=="RS256")throw new N(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",d=typeof i.iss=="string"?i.iss:"";if(d===""||!this.opts.issuers.includes(d))throw new N(`machine token issuer is not one this endpoint accepts (${JSON.stringify(d)})`);if(i.aud!==wt)throw new N(`machine token audience must be ${wt} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==un)throw new N(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let c=typeof i.org_id=="string"?i.org_id:"";if(c==="")throw new N("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new N("machine token is expired \u2014 re-mint and retry");let y=u=>u.kty==="RSA"&&u.n!==void 0&&u.e!==void 0,l=await this.jwksKeys(!1),m=a===""?void 0:l.find(u=>u.kid===a&&y(u));if(m===void 0&&(l=await this.jwksKeys(!0),m=a===""?void 0:l.find(u=>u.kid===a&&y(u))),m===void 0)throw new N(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let k=Buffer.from(`${n}.${r}`,"ascii"),S=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),C=!1;try{let u=cn({key:m,format:"jwk"});C=dn("RSA-SHA256",k,u,S)}catch{C=!1}if(!C)throw new N("machine token signature failed verification");return{apiKey:t,orgId:c,credential:"machine"}}};function Se(e,t,n){return n!==null&&pn(e)?n.verify(e):t.resolve(e)}E();var wn=8080,ke="serve",Kr="0.0.0.0";function bn(e,t,n){let r=(e[t]??"").trim();if(!r)throw new Error(`${t} is not set \u2014 ${n}`);return r}function Br(e=process.env){let t=(e.PORT??"").trim(),n=t===""?wn: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=Ke(X(bn(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,c=(e.URUN_LEDGER_SIGNING_KEY??"").trim(),f=(e.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!c!=!!f)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let y=c?{keyId:f,key:c}:void 0,l={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((h,A)=>Object.values(l)[A]==="");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 S=k.length===0?l:void 0,C={baseUrl:(e.URUN_POOLER_URL??"").trim(),token:(e.URUN_POOLER_TOKEN??"").trim(),region:(e.URUN_POOLER_REGION??"").trim()},u=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=u.filter((h,A)=>Object.values(C)[A]==="");if(g.length!==0&&g.length!==u.length)throw new Error(`${u.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let _=g.length===0?C:void 0,R={jwksBaseUrl:(e.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(e.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(e.URUN_MACHINE_TOKEN_TTL_S??"").trim()},v=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],P=v.filter((h,A)=>Object.values(R)[A]==="");if(P.length!==0&&P.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${P.join(", ")}, which would half-configure the machine-identity rung`);let p=R.issuers.split(",").map(h=>h.trim()).filter(h=>h!=="");if(p.length===0&&P.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 w=Number(R.tokenTtlS);if(P.length===0&&(!Number.isFinite(w)||w<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(R.tokenTtlS)}`);let b=P.length===0?{jwksBaseUrl:R.jwksBaseUrl,issuers:p,tokenTtlS:w}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:d,ledgerSigning:y,lane:S,pooler:_,machine:b}}E();import{createHash as Ln,randomUUID as kt}from"crypto";E();import{request as _n}from"http";var vn="/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},Sn=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)},kn=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)}},vt=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)}),Rn=async e=>{let t="pooler_error",n=`the pooler refused the request (HTTP ${e.status})`;try{let r=JSON.parse(await vt(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 En(e,t,n,r,o){let s=new URL(`${e.baseUrl.replace(/\/+$/,"")}${vn}`),i=JSON.stringify({region:e.region,model:r,request_id:n,streaming:o,payload:t,affinity:{systemPrompt:Sn(t),firstMessage:kn(t)}});return new Promise((a,d)=>{let c=_n({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))}},f=>{let y=Number(f.headers["retry-after"]??"");a({status:f.statusCode??0,retryAfterSeconds:Number.isFinite(y)?y:void 0,body:f})});c.on("error",f=>d(new F(502,"pooler_unreachable",`the pooler channel failed: ${f.message}`))),c.end(i)})}var _t=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*Cn(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=_t(s);i!==null&&(yield i)}let n=_t(t);n!==null&&(yield n)}async function St(e,t,n,r){let o=xe(t,n,r),s=o.model??"";if(s==="")throw new F(400,"missing_model","the pooler submit requires a model");let i=await En(e,o,n,s,t.stream===!0);if(i.status>=400)throw await Rn(i);let a=t.stream===!0?we(n,Cn(i)):await An(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function An(e,t){let n=await vt(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 we(t,(async function*(){yield o})())}var Nn=512;function Re(e){return`urun-inference-proxy-${Ln("sha256").update(e).digest("hex").slice(0,32)}`}var ae=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_${kt()}`;return St(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:ke,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:t.credential==="machine"?{lane:"machine",machineToken:t.apiKey,gatewayUrl:this.opts.baseUrl}:{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:lt(process.env,process.env.HOSTNAME)??void 0},r=_e(n),o=n.decisionPool?ct(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(ve(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>=Nn;){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("; ")}`)}},Rt=512,Tn=1024,le=class extends Error{constructor(){super(`conversation capacity reached (${Rt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Pn(e){return{sessionStartOptions:t=>{if(t.startsWith(be))return;let n=e.get(t);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(t,n)=>{t.startsWith(be)||e.set(t,n)}}}function On(e,t,n,r){let o=_e({baseUrl:e.baseUrl,orgId:t.orgId,defaultApp:null,fnName:ke,sharedOnlyListing:!0,apiUrl:e.apiUrl,auth:t.credential==="machine"?{lane:"machine",machineToken:t.apiKey,gatewayUrl:e.baseUrl}:{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",...Pn(r)});return{clients:ve(o,void 0,void 0,void 0,void 0,e.lanes),release:async()=>{await o.closeAll()}}}var ce=class{constructor(t){this.opts=t}opts;byCaller=new Map;byHandle=new Map;build(t,n){let r={id:n,subject:`${Re(t.apiKey)}:live:${n}`},o=new Map,s=this.opts.build?this.opts.build(t,r):On(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>=Rt;){let t=this.byCaller.keys().next();if(t.done)throw new le;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 le;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,kt())),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 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(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>=Tn;){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),c=a===void 0||d===void 0?void 0:d.get(a.conversationId);if(a===void 0||c===void 0||a.apiKey!==t.apiKey)throw new Y("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 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("; ")}`)}};E();var Un="/inference-ledger",In=1e4,de=class extends Error{ledgerFailureReason;constructor(t,n="duplicate"){super(t),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Ae=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},T=class extends Error{ledgerFailureReason="surface";constructor(t){super(t),this.name="LedgerSurfaceError"}},Le=class extends N{ledgerFailureReason="auth";constructor(t){super(t),this.name="LedgerAuthError"}},Ne=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(t){super(t),this.name="LedgerSignatureError"}},xn=[["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",Ee],["output_minutes",Ee],["cost_nano_usd",Ee],["price_version",e=>e===null||typeof e=="string"]];function $n(e){for(let[t,n]of xn){if(!(t in e))return`${t} (absent)`;if(!n(e[t]))return`${t} (${JSON.stringify(e[t])})`}return null}function Dn(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"}:$n(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ee(e){return e===null?!0:typeof e=="number"?Number.isFinite(e):typeof e!="string"?!1:/[^\s]/.test(e)&&Number.isFinite(Number(e))}function Ce(e,t){return e===null?t===null:t===null?!1:Number(t)===e}function Mn(e,t){return e===null?t===null:t===null?!1:Number(e.toFixed(9))===Number(t)}function Et(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 Hn(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&&Et(e.started_at,n.started_at)&&Et(e.completed_at,n.completed_at)&&Ce(e.prompt_tokens,n.prompt_tokens)&&Ce(e.completion_tokens,n.completion_tokens)&&Ce(e.output_units,n.output_units)&&Mn(e.output_minutes,n.output_minutes)}function Fn(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 Gn(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(Fn(e)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:t.keyId}}function jn(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new T(`${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 T(`${t} answered a row with no inference_id: ${JSON.stringify(e)}`);if(!("cost_nano_usd"in n))throw new T(`${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 T(`${t} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=c=>{if(!(c in n))throw new T(`${t} answered a row with no ${c} field: ${JSON.stringify(e)}`);let f=n[c];if(f===null)return null;if(typeof f!="string")throw new T(`${t} answered a non-string ${c}: ${JSON.stringify(f)}`);if(!/[^\s]/.test(f))throw new T(`${t} answered a BLANK ${c} (${JSON.stringify(f)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return f},i=s("price_version"),a=s("unpriced_reason"),d=o!=null;if(d&&(i===null||a!==null))throw new T(`${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 T(`${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 ue=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async write(t,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Un}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Gn(n,this.opts.signing)}):JSON.stringify(n)}catch(c){throw new T(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${c instanceof Error?c.message:String(c)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:o,signal:AbortSignal.timeout(In)})}catch(c){throw new T(`the uRun ledger surface at ${r} could not be reached: ${c instanceof Error?c.message:String(c)}`)}if(s.status===409){let c=await s.text().catch(()=>""),f=Dn(c);throw f.status==="found"&&Hn(n,f.row)?new Ae(f.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):f.status==="not_in_this_org"?new de(`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 de(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${f.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${c.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new Le("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 c=await s.text().catch(y=>`<body unreadable: ${y instanceof Error?y.message:String(y)}>`),f;try{let y=JSON.parse(c);if(y!==null&&typeof y=="object"&&"error"in y){let l=y.error;l!==null&&typeof l=="object"&&"code"in l&&(f=l.code)}}catch{}throw f==="ledger_signature_invalid"?new Ne(`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 T(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${c.slice(0,400)}`)}let i;try{i=await s.json()}catch(c){throw new T(`the uRun ledger surface at ${r} answered a body that is not JSON: ${c instanceof Error?c.message:String(c)}`)}let a=i?.recorded;if(a===void 0)throw new T(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let d=jn(a,`the uRun ledger surface at ${r}`);if(d.inference_id!==n.inference_id)throw new T(`the uRun ledger surface at ${r} answered for inference_id ${d.inference_id} when asked about ${n.inference_id}`);return d}};E();import{createServer as yr}from"http";E();import{createWebsocketDocConnector as Vn}from"@urun-sh/core/internal";import zn from"ws";E();import*as G from"yjs";import{SessionDocumentImpl as Wn}from"@urun-sh/core/internal";var Kn=3e4;function Bn(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*Jn(e,t){let n=[],r=!1,o=null,s="",i=0,a=c=>{if(!("responses"in c)||typeof c.responses!="object"||c.responses===null)return null;let f=c.responses;if(!(t in f))return null;let y=f[t];if(y===null||typeof y!="object"||!("error"in y))return{body:y,error:null};let l=y.error;return l===null?{body:y,error:null}:{body:y,error:l}},d=c=>{let f={};for(let[l,m]of Object.entries(c)){let k=m;f[l]=typeof k?.toJSON=="function"?k.toJSON():m}if("tokens"in f&&typeof f.tokens=="object"&&f.tokens!==null){let l=f.tokens[t];if(typeof l=="string"&&l.length>s.length)n.push({t:"delta",delta:l.slice(s.length)}),s=l;else if(l!==null&&typeof l=="object"){let m=l,k=Object.keys(m).map(S=>Number(S)).filter(S=>Number.isFinite(S)&&S>i).sort((S,C)=>S-C);for(let S of k){let C=m[String(S)];typeof C=="string"&&C.length>0&&(n.push({t:"delta",delta:C}),i=S)}}}let y=a(f);if(y!==null){y.error!==null?n.push({t:"error",body:y.error}):n.push({t:"response",body:y.body}),r=!0,o?.(),o=null;return}if("progress"in f&&typeof f.progress=="object"&&f.progress!==null){let l=f.progress[t];if(typeof l=="object"&&l!==null&&"state"in l&&l.state==="error"){let k="error"in l&&typeof l.error=="string"?l.error:"lane request failed";n.push({t:"error",body:{message:k}}),r=!0,o?.(),o=null;return}}o?.(),o=null};if(d(e.get()??{}),!r){let c=e.on("change",d);try{for(;!r;){if(n.length>0){yield n.shift();continue}await new Promise(f=>{o=f})}}finally{c()}}for(;n.length>0;)yield n.shift()}function Te(e){let{laneId:t}=e,n=e.connector??(e.roomDoc?Bn(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 c=r.get(d);return c||(c=new Wn(d,t,n),r.set(d,c)),c},i=d=>{let c="llm-resp:";if(!d.startsWith(c))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${c}<rid>)`);let f=d.slice(c.length);return{messages:()=>Jn(s("llm"),f),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 c=s("llm");if(c.synced===!0)return;let f=d?.timeout??e.whenLiveTimeoutMs??Kn;await new Promise((y,l)=>{let m=setTimeout(()=>{k(),l(new Error(`lane ${t} llm doc never synced within ${f}ms`))},f),k=c.onSynced(()=>{clearTimeout(m),d?.signal?.removeEventListener("abort",S),y()}),S=()=>{clearTimeout(m),k(),l(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",S,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear()}}}function Yn(e){let t=(e.gpuSpec??"").split(":")[0];if(typeof e.appId!="string"||e.appId==="")throw new Ge(`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 Ct(e){let t=e.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=(l,m,k,S,C)=>{let u=k?Te({laneId:l,roomDoc:R=>e.roomDoc(l,R)}):Te({laneId:l,connector:Vn({serverUrl:`ws://${S}/doc`,sessionId:l,token:()=>ut(l,e.tokenSecret,void 0,void 0,C),WebSocketPolyfill:zn})}),g=k?a(l):at(u,`lane:${l}`,{armOnFirstSync:!0}),_={session:u,responses:new $e(u),gone:g,goneWatch:g,laneId:l,pool:m,inFlight:0,laneSession:u,self:k,host:S??""};return n.set(l,_),g.onGone(()=>d(_)),_},a=l=>{let m=null,k=!1,S=new Set,C=g=>{if(!m){m=g;for(let _ of[...S])_(g);S.clear()}},u=e.hostedSignal?.(l,g=>{if(g){k=!0;return}k&&C(new Y(`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),()=>{}):(S.add(g),()=>S.delete(g))},dispose(){u?.(),S.clear()}}},d=l=>{c(l)&&(n.delete(l.laneId),r.delete(l.laneId),l.goneWatch?.dispose())},c=l=>{let m=l.laneId;return typeof m=="string"&&n.get(m)===l},f=(l,m)=>{throw e.metrics?.observeLane503Fast(m??""),s.set(l,t()),new q(l)},y=async(l,m)=>{let k=Yn(m);o.add(k);let S=t();try{let C=await e.laneWarmWaitMsFor?.(l,m)??e.laneColdWakeDefaultMs??0,u=await e.plane.pick({pool:k,model:l,holdMs:C});e.metrics?.observeLaneReady(l??"",u.length);let _=u.map(v=>({laneId:v.laneId,self:v.host===e.selfAddress,host:v.host})).sort((v,P)=>v.self!==P.self?v.self?-1:1:(r.get(v.laneId)??0)-(r.get(P.laneId)??0))[0];_||f(k,l);let R=n.get(_.laneId);return R?.goneWatch?.gone()&&(d(R),R=void 0),R&&(R.pool!==k||R.self!==_.self||R.host!==_.host)&&(d(R),R=void 0),R||(R=i(_.laneId,k,_.self,_.host,m.sharedOrgId??void 0)),R.inFlight+=1,r.set(_.laneId,(r.get(_.laneId)??0)+1),{app:k,entry:R,identity:{kind:"catalog",model_id:m.modelId??l??"",variant:m.variant??""}}}finally{e.metrics?.observeLanePick(l??"",t()-S)}};return{sessionFor(l,m){return y(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(S=>S.pool)])].sort(),m=await e.plane.status().catch(()=>[]),k=new Map(qn(m));return Promise.all(l.map(async S=>{let C=k.get(S)??{pool:S,lanes:[],lastDemandAt:null};return{pool:S,lanes:C.lanes,lastDemandAt:C.lastDemandAt,local:[...n.values()].filter(u=>u.pool===S).map(u=>({laneId:u.laneId,inFlight:u.inFlight,self:u.self,host:u.host})),lastRefusalAt:s.get(S)??null}}))},async close(){for(let l of n.values())l.gone.dispose(),l.laneSession.destroy();n.clear(),r.clear(),await e.plane.close()},stats(){return[...n.values()].map(l=>({pool:l.pool,laneId:l.laneId,inFlight:l.inFlight}))}}}function qn(e){return new Map(e.map(t=>[t.pool,{lanes:t.lanes,lastDemandAt:t.lastDemandAt}]))}E();import{request as Xn}from"http";var Qn="/pooler/v1/lanes/pick",Zn="/pooler/v1/lanes/status",er=1e4;function At(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)),c=Xn({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},f=>{let y=[];f.on("data",l=>y.push(l)),f.on("end",()=>{let l=Buffer.concat(y).toString("utf8"),m=null;try{m=l===""?null:JSON.parse(l)}catch{m=null}s({status:f.statusCode??0,json:m})}),f.on("error",i)});c.on("timeout",()=>{c.destroy(new Error(`pooler lane surface timed out after ${o}ms (${t} ${n})`))}),c.on("error",i),c.end(d)})}function Lt(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 Nt(e){return{async pick({pool:t,model:n,holdMs:r=0}){let o=await At(e,"POST",Qn,{pool:t,model:n,hold_ms:r},r+er);if(o.status!==200)throw Lt(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 At(e,"GET",Zn,void 0,5e3);if(t.status!==200)throw Lt(t.status,t.json,"");let n=t.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}E();import{WebSocketServer as fr}from"ws";E();import*as Pt from"yjs";import*as K 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 Ot from"lib0/map";import nr from"lodash.debounce";E();var Tt=()=>{};var rr=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,or=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,sr=0,ir=1;var ar=process.env.GC!=="false"&&process.env.GC!=="0",lr=process.env.YPERSISTENCE,fe=null;if(typeof lr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var W=new Map,pe=0,Oe=1,cr=(e,t,n)=>{let r=L.createEncoder();L.writeVarUint(r,pe),K.writeUpdate(r,e);let o=L.toUint8Array(r);n.conns.forEach((s,i)=>V(n,i,o))},Pe=class extends Pt.Doc{constructor(t){super({gc:ar}),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 f=this.conns.get(i);f!==void 0&&(r.forEach(y=>{f.add(y)}),s.forEach(y=>{f.delete(y)}))}let d=L.createEncoder();L.writeVarUint(d,Oe),L.writeVarUint8Array(d,D.encodeAwarenessUpdate(this.awareness,a));let c=L.toUint8Array(d);this.conns.forEach((f,y)=>{V(this,y,c)})};this.awareness.on("update",n),this.on("update",cr),!1}},Ue=(e,t=!0)=>Ot.setIfUndefined(W,e,()=>{let n=new Pe(e);return n.gc=t,fe!==null&&fe.bindState(e,n),W.set(e,n),n}),dr=(e,t,n)=>{try{let r=L.createEncoder(),o=B.createDecoder(n);switch(B.readVarUint(o)){case pe:L.writeVarUint(r,pe),K.readSyncMessage(o,r,t,e),L.length(r)>1&&V(t,e,L.toUint8Array(r));break;case Oe:{D.applyAwarenessUpdate(t.awareness,B.readVarUint8Array(o),e);break}}}catch(r){console.error(r),t.emit("error",[r])}},j=(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&&fe!==null&&(fe.writeState(e.name,e).then(()=>{e.destroy()}),W.delete(e.name))}t.close()},V=(e,t,n)=>{t.readyState!==sr&&t.readyState!==ir&&j(e,t);try{t.send(n,r=>{r!=null&&j(e,t)})}catch{j(e,t)}},ur=3e4,Ut=(e,t,{docName:n=t.url.slice(1).split("?")[0],gc:r=!0}={})=>{e.binaryType="arraybuffer";let o=Ue(n,r);o.conns.set(e,new Set),e.on("message",a=>dr(e,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(e)&&j(o,e),clearInterval(i);else if(o.conns.has(e)){s=!1;try{e.ping()}catch{j(o,e),clearInterval(i)}}},ur);e.on("close",()=>{j(o,e),clearInterval(i)}),e.on("pong",()=>{s=!0});{let a=L.createEncoder();L.writeVarUint(a,pe),K.writeSyncStep1(a,o),V(o,e,L.toUint8Array(a));let d=o.awareness.getStates();if(d.size>0){let c=L.createEncoder();L.writeVarUint(c,Oe),L.writeVarUint8Array(c,D.encodeAwarenessUpdate(o.awareness,Array.from(d.keys()))),V(o,e,L.toUint8Array(c))}}};var Ie="/doc/",xt=30,pr=1e4,It="llm";function gr(e){if(!e.startsWith(Ie))return null;let t=e.slice(Ie.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 z(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 $t(e,t){let n=new fr({noServer:!0}),r=new Set,o=new Map,s=new Map,i=u=>o.get(`${u}/${It}`)??0,a=u=>s.get(u)??0,d=new Map,c=new Map,f=new Set,y=new Set,l=!1,m=(u,g,_)=>{let R=i(u)>0,v=a(u),P=v>0,p=`${u}/${g}`,w=o.get(p)??0;_>0?o.set(p,_):o.delete(p);let b=v+_-w;b>0?s.set(u,b):s.delete(u);let h=i(u)>0,A=b>0;if(R!==h){h?k(u):S(u);for(let I of d.get(u)??[])I(h)}P&&!A&&queueMicrotask(()=>{let I=`${u}/`;for(let[x,M]of[...W.entries()])!x.startsWith(I)||M.conns.size>0||(W.delete(x),M.destroy())})},k=u=>{if(!t.hostRegistry||c.has(u))return;let g=()=>{t.hostRegistry?.setHost(u,t.selfAddress).catch(()=>{})};g();let _=setInterval(g,pr);_.unref?.(),c.set(u,_)},S=u=>{let g=c.get(u);g&&(clearInterval(g),c.delete(u)),t.hostRegistry&&t.hostRegistry.delHost(u,t.selfAddress).catch(()=>{})},C=(u,g,_)=>{let R;try{R=new URL(u.url??"/","http://localhost")}catch{z(g,400,"malformed upgrade URL");return}g.on("error",()=>g.destroy()),g.on("close",()=>y.delete(g));let v=gr(R.pathname);if(!v){if(R.pathname.startsWith(Ie)){z(g,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}y.add(g);return}f.add(g);let P=!1;(async()=>{let p=R.searchParams.get("token")??"",w=null;try{w=p===""?null:await t.verifyToken(p,v.laneId,v.docName)}catch{w=null}if(w===null){z(g,401,"invalid or missing lane doc token");return}let b=w;if(b.tenant!==void 0&&t.laneTenantOf){let h=null;try{h=await t.laneTenantOf(v.laneId)}catch{h=null}if(h==null||h==="")t.onLaneTenantMissing?.();else if(b.tenant!==h){z(g,403,"lane doc token org does not match the lane record");return}}l||g.destroyed||(P=!0,n.handleUpgrade(u,g,_,h=>{f.delete(g),r.add(h),h.on("close",()=>r.delete(h));let A=b.scope===dt||b.scope===void 0&&typeof b.app=="string"&&typeof b.fn=="string"&&b.aud==="sfu";if(A){let x=`${v.laneId}/${v.docName}`,M=(o.get(x)??0)+1;m(v.laneId,v.docName,M),M>1&&v.docName===It&&t.hostRegistry?.setHost(v.laneId,t.selfAddress).catch(()=>{})}h.on("close",()=>{if(!A)return;let x=`${v.laneId}/${v.docName}`;m(v.laneId,v.docName,Math.max(0,(o.get(x)??1)-1))}),Ut(h,u,{docName:`${v.laneId}/${v.docName}`,gc:!0})}))})().catch(()=>{!P&&!g.destroyed&&z(g,500,"lane doc upgrade failed")}).finally(()=>f.delete(g))};return e.on("upgrade",C),{async close(){l=!0,e.off("upgrade",C);for(let g of[...c.keys()])S(g);await new Promise(g=>{if(r.size===0&&f.size===0){g();return}let _=r.size+f.size,R=()=>{_-=1,_<=0&&g()};for(let v of r)v.once("close",R);for(let v of f)v.once("close",R);for(let v of r)v.close(1001,"lane doc host shutting down");for(let v of f)v.destroy()}),o.clear(),s.clear(),d.clear()},roomDoc(u,g){return Ue(`${u}/${g}`,!0)},isHosted(u){return i(u)>0},onHostedChange(u,g){let _=d.get(u);return _||(_=new Set,d.set(u,_)),_.add(g),g(i(u)>0),()=>{_.delete(g)}}}}E();var hr="urun:catalog:v1";function Dt(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(hr),c=[];for(let f of Object.values(d))try{c.push(JSON.parse(f))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
13
- `)}return r=c,o=n(),c},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 wr from"ioredis";E();var ge="/inference-usage",Mt=25e3;var mr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function Ht(e){if(!(e instanceof Error))return`a ${typeof e}`;let t=mr.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 he=class{constructor(t){this.opts=t;this.fetchImpl=t.fetchImpl??fetch}opts;fetchImpl;async lookup(t,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ge}`,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(Mt)})}catch(i){throw new Q(`the uRun usage surface (POST ${ge}) could not be reached within ${Mt}ms: ${Ht(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new N("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 ${ge}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new Q(`the uRun usage surface (POST ${ge}) answered HTTP ${o.status} with a body that is not JSON: ${Ht(i)}`)}return Qe(s,this.opts.onRejectedRow)}};var br=5e3,_r=1e3,vr=1500,Sr=3e3,kr="/api/client-tokens";function me(e,t,n){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))}function Ft(e,t,n,r){me(e,t,{error:{message:n,type:r}})}async function Rr(e,t=fetch){let n=`${e.replace(/\/+$/,"")}${kr}`;try{let r=await t(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Sr)});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 fs(e){let t=e.resolver??new oe({gatewayUrl:e.baseUrl}),n=e.machine?new se({jwksBaseUrl:e.machine.jwksBaseUrl,issuers:e.machine.issuers}):null,r=new re(e.defaultMetrics===void 0?{}:{defaultMetrics:e.defaultMetrics}),o=null,s=(()=>{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 wr(e.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),w=Dt({redis:p});return{registry:Ct({selfAddress:e.lane.selfAddress,tokenSecret:e.lane.tokenSecret,plane:Nt({baseUrl:e.pooler.baseUrl,token:e.pooler.token}),hostedSignal:(h,A)=>o?.onHostedChange(h,A)??(()=>()=>{}),roomDoc:(h,A)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(h,A)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(h,A)=>w.rows().then(I=>{let x=Me(I,A);return x?.warm_wait_s!==void 0?x.warm_wait_s*1e3:void 0})}),catalog:w,redis:p}})(),i=e.registry??new ae({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:s?null:e.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry,pooler:e.pooler}),a=e.probeControlPlane??(()=>Rr(e.baseUrl)),d=async()=>{let p=null;for(let h of i.decisionPools()){p=h;break}if(!p)return null;let w=p.stats();if(w.some(h=>h.draining))return{ok:!1,detail:"decision pool draining"};if(w.every(h=>h.attached===0&&h.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let b=await p.pingReady(vr);return{ok:b,detail:b?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=e.usageClient??new he({apiUrl:e.apiUrl}),f=e.ledgerClient??new ue({apiUrl:e.apiUrl,...e.ledgerSigning?{signing:e.ledgerSigning}:{}}),y=process.env.URUN_SHARED_ORG_ID?.trim(),l=process.env.URUN_SHARED_ORG_API_KEY?.trim();y&&l&&(async()=>{try{await i.decisionWarmerFor({orgId:y,apiKey:l})?.warmFor(st)}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 m=async p=>Se(ie(p.headers.authorization),t,n),k=async p=>{let w=await m(p);if(w.billingAudience==="platform"&&w.creditsAdmissionOk===!1){let b=w.creditsRefusalReason;throw new J(b==="spend_cap_reached"||b==="insufficient_credits"?b:void 0)}return w},S=p=>p instanceof N?{status:p.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:p instanceof J?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...p.code!==void 0?{code:p.code}:{}}:p instanceof $?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:p.detail}:null,C=it({clients:async p=>i.clientsFor(await k(p)),usage:{authorize:p=>ie(p.headers.authorization),lookup:(p,w)=>c.lookup(p,w)},statusOf:S,...e.requestLog?{requestLog:e.requestLog}:{},observe:p=>r.observe(p),ledger:{write:(p,w)=>f.write(ie(p.headers.authorization),w),observe:p=>r.observeLedger(p),...e.ledgerLog?{report:e.ledgerLog}:{}}}),u=null,g=null,_=yr((p,w)=>{let b=new URL(p.url??"/","http://localhost");(async()=>{if(p.method==="GET"&&b.pathname==="/healthz"){me(w,200,{ok:!0});return}if(p.method==="GET"&&b.pathname==="/readyz"){let I=Date.now();if((!u||I-u.at>=br)&&(u={at:I,...await a()}),!g||I-g.at>=_r){let ye=await d();g=ye===null?{at:I,ok:!0,detail:null}:{at:I,ok:ye.ok,detail:ye.detail}}let x=(u?.ready??!1)&&g.ok,M=g.detail===null?u?.detail??"control plane not yet probed":`${u?.detail??"control plane not yet probed"}; ${g.detail}`;me(w,x?200:503,{ok:x,control_plane:M});return}if(p.method==="GET"&&b.pathname==="/lanez"){me(w,200,{pools:s?await s.registry.status():null});return}let h=b.pathname==="/v1"||b.pathname.startsWith("/v1/"),A=b.pathname.startsWith("/partners/");if(!h&&!A){Ft(w,404,`no route for ${p.method} ${b.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,w)})().catch(h=>{if(!w.headersSent){Ft(w,500,String(h instanceof Error?h.message:h),"proxy_error");return}w.end()})}),R=e.conversations??new ce({baseUrl:e.baseUrl,apiUrl:e.apiUrl,catalog:s?null:e.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry}),v=[Fe(_,{authenticate:async p=>{let w=await Se(p,t,n),b=R.connectionFor(w);return{clients:b.clients,scope:Re(w.apiKey),onBindResumeHandle:b.bindResumeHandle,clientsForResume:b.clientsForResume,release:b.release}}}),We(_,{clients:async p=>i.clientsFor(await k(p)),statusOf:S}).close,Je(_,{resolver:{resolve:async(p,w)=>{let b=await k(p),h=R.connectionFor(b),A;try{A=await qe(Ve(h.clients,e.realtimeCompanions),ze(p),w,Ye(p))}catch(x){throw h.release().catch(()=>{}),x}let I=A.release;return{...A,release:async()=>{await I?.(),await h.release()}}}}})];if(e.lane&&s){let p=e.lane,w=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=$t(_,{verifyToken:(h,A)=>ft(h,A,p.tokenSecret,void 0,w),selfAddress:p.selfAddress,laneTenantOf:h=>s.redis.get(`lane_tenant:${h}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:w,hostRegistry:{setHost:(h,A)=>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:${h}`,A,String(xt)),delHost:h=>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:${h}`,p.selfAddress)}});let b=s;v.push(async()=>{await o.close(),await b.registry.close(),b.redis.quit().catch(()=>{})})}_.on("upgrade",(p,w)=>{let b=new URL(p.url??"/","http://localhost");b.pathname===He||b.pathname===je||b.pathname===Be||o!==null&&b.pathname.startsWith("/doc/")||w.destroyed||(w.write(`HTTP/1.1 404 Not Found\r
15
- Connection: close\r
16
- \r
17
- no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),w.destroy())});let P=async()=>{for(let p of v)await p();await R.detachAll()};return{server:_,metricsServer:gt(r),metrics:r,edgeIdentityServer:yt(),registry:i,closeAll:()=>i.closeAll(),closeWebSockets:P}}async function ps(e,t,n){n&&await n();let r=new Promise(o=>e.close(()=>o()));e.closeAllConnections(),await r,await rt()||ot(),await t()}export{Pr as a,pt as b,te as c,Kt as d,Bt as e,Jt as f,Yt as g,qt as h,ne as i,re as j,gt as k,$r as l,Qt as m,Zt as n,en as o,tn as p,ht as q,rn as r,on as s,sn as t,yt as u,N as v,$ as w,ie as x,hn as y,mn as z,oe as A,wn as B,ke as C,Kr as D,Br as E,Nn as F,Re as G,ae as H,Rt as I,Tn as J,le as K,ce as L,Un as M,In as N,de as O,T as P,jn as Q,ue as R,br as S,Sr as T,fs as U,ps as V};
@@ -1 +0,0 @@
1
- import{f as r}from"./chunk-ETX6IX25.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(n){this.transport=new r(n)}responses={create:async n=>{let t=a(),i=await this.transport.sendResponses(n,t);return Object.assign((async function*(){yield*i})(),{requestId:t})}}};export{o as a};