@urun-sh/openai 0.6.41 → 0.6.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ResponsesClient-gfg7qUoE.d.ts → ResponsesClient-2EsjJUz1.d.ts} +1 -1
- package/dist/{ResponsesClient-6QsC7NPJ.d.cts → ResponsesClient-BIcQ6p6Z.d.cts} +1 -1
- package/dist/{chunk-ILYHXVNZ.js → chunk-27HP3RMZ.js} +1 -1
- package/dist/chunk-2NKCALKY.js +22 -0
- package/dist/chunk-2RO722HS.js +2 -0
- package/dist/chunk-7DUSLXPG.js +1 -0
- package/dist/chunk-BFIKVTQB.js +1 -0
- package/dist/{chunk-4NMMWAKD.js → chunk-FF3RWDFM.js} +1 -1
- package/dist/chunk-GDH2D3S6.js +1 -0
- package/dist/chunk-J3KCHTSA.js +6 -0
- package/dist/{chunk-QTHFMDZY.js → chunk-JMSVHETI.js} +1 -1
- package/dist/{chunk-L4QBHSVY.js → chunk-MJSK6W3W.js} +1 -1
- package/dist/chunk-MOX5FG2R.js +1 -0
- package/dist/chunk-YRBUHHI3.js +2 -0
- package/dist/chunk-ZCF6EV4Y.js +65 -0
- package/dist/{composite-B-F2J0NK.d.cts → composite-BoS9-74g.d.cts} +320 -4
- package/dist/{composite-B--rGI5m.d.ts → composite-D4_XPSas.d.ts} +91 -4
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +4 -4
- package/dist/gemini-live.d.ts +4 -4
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +44 -43
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +43 -42
- package/dist/hosted/index.d.cts +54 -10
- package/dist/hosted/index.d.ts +11 -5
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.d.cts +2 -2
- package/dist/pi-extension/index.d.ts +2 -2
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +55 -55
- package/dist/pooler/bin.cjs +40 -41
- package/dist/pooler/bin.js +39 -40
- package/dist/proxy/cli.cjs +54 -53
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/conformance-probe.cjs +1 -1
- package/dist/proxy/conformance-probe.js +1 -1
- package/dist/proxy/index.cjs +33 -32
- package/dist/proxy/index.d.cts +37 -214
- package/dist/proxy/index.d.ts +17 -65
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-BqpmZ-vh.d.ts → translator-BemK1Of5.d.ts} +1 -1
- package/dist/{translator-Dox25ky9.d.cts → translator-PsmsZT62.d.cts} +1 -1
- package/dist/{types-CHPtJx6d.d.cts → types-CxWQ84Ew.d.cts} +5 -0
- package/dist/{types-CHPtJx6d.d.ts → types-CxWQ84Ew.d.ts} +2 -0
- package/dist/{video-out-DnCKUUO2.d.cts → video-out-DPLqpGbQ.d.cts} +17 -3
- package/dist/{video-out-REmiQMBJ.d.ts → video-out-DkMqKSOi.d.ts} +6 -2
- package/package.json +2 -2
- package/dist/chunk-7KRHHEKZ.js +0 -1
- package/dist/chunk-G7CSAISC.js +0 -1
- package/dist/chunk-GX243AIV.js +0 -1
- package/dist/chunk-HBKAN6PP.js +0 -2
- package/dist/chunk-HPUX2H65.js +0 -6
- package/dist/chunk-KKCUIOL4.js +0 -1
- package/dist/chunk-PAAFRUQZ.js +0 -64
- package/dist/chunk-VVQSFACF.js +0 -23
- package/dist/chunk-Z3QCHKJB.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as m}from"./chunk-
|
|
1
|
+
import{h as m}from"./chunk-J3KCHTSA.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import b from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.43";var y=4141,R=g,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(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}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?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}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 f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function 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=b.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,22 @@
|
|
|
1
|
+
import{a as Ut,c as He,d as Nt,e as De}from"./chunk-2RO722HS.js";import{A as Rt,B as Lt,C as It,D as At,E as Pt,F as Ot,G as Tt,b as lt,d as ct,e as dt,f as le,k as ut,l as ft,n as ht,o as gt,p as mt,q as yt,r as wt,s as bt,t as vt,v as St,w as de,x as _t,y as kt,z as Et}from"./chunk-ZCF6EV4Y.js";import{a as at}from"./chunk-JMSVHETI.js";import{a as $t,b as te,c as We}from"./chunk-GDH2D3S6.js";import{a as xt,e as Mt}from"./chunk-YRBUHHI3.js";import{a as Ct}from"./chunk-MJSK6W3W.js";import{l as pt,m as ce}from"./chunk-27HP3RMZ.js";import{a as ot}from"./chunk-FF3RWDFM.js";import{b as rt,d as xe}from"./chunk-BFIKVTQB.js";import{e as st,j as ie,n as it,o as ae,p as Me}from"./chunk-J3KCHTSA.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{Counter as J,Gauge as ue,Histogram as fe,Registry as Tn,collectDefaultMetrics as Cn}from"@prometheus-io/client";import{createServer as Un}from"http";var Bo=9464,Ht="/metrics",pe="(other)",Nn="(none)",$n=64,xn=128,Mn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",St,kt,st],Hn=new Set(Mn);function Dn(t){return Hn.has(t)?t:pe}function Wn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var he=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?Nn:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,pe):(this.admitted.add(e),e):pe}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ge=class{registry=new Tn;modelLabel=new he($n);orgLabel=new he(xn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ue({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new J({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new fe({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 fe({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new J({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new J({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new J({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Et)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ue({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},Rt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Lt()/1e3)}}),this.labelCardinality=new ue({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new J({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new ue({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 fe({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 fe({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new J({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new J({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&Cn({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=Dn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?pe:e.method,status_class:Wn(e.status),stream:l,model:s,org:i}),this.duration.observe({lane:n,stream:l,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Dt(t){return Un((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ht){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ht}
|
|
2
|
+
`);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
|
|
3
|
+
`);return}n.end()})})}A();import{createHash as Ft}from"crypto";import{createServer as Fn}from"http";var zo=9465,Bn="x-urun-key-id",Kn="x-urun-key-fingerprint",Gn="urun-ratelimit-bucket:",jn="urun-ratelimit-tier:",Wt="anonymous",Jn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function zn(t){return Ft("sha256").update(`${Gn}${t}`).digest("hex")}function qn(t){return Ft("sha256").update(`${jn}${t}`).digest("hex")}function Vn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Jn.test(n)?n:null}function Bt(){return Fn((t,e)=>{let n=Vn(t.headers.authorization);e.setHeader(Bn,n===null?Wt:zn(n)),e.setHeader(Kn,n===null?Wt:qn(n)),e.writeHead(200),e.end()})}A();import{createClientToken as Yn,ClientTokenError as Kt}from"@urun-sh/core";import{createPublicKey as Qn,verify as Xn}from"crypto";var Gt="urun-session-gateway",Zn="machine",er=3e5;function Jt(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var C=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},z=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},B=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function be(t){let e=(t??"").trim();if(e==="")throw new C("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new C("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var tr=60,nr=6e4,rr=4096;function or(t){return t===401||t===403}var re=class{constructor(e){this.opts=e;this.mint=e.mint??Yn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new C("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<nr)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let o,s;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:tr});o=i.orgId,s={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Kt&&i.status===402?(this.cache.delete(e),new z(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof Kt&&or(i.status)?(this.cache.delete(e),new C(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new B(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!o)throw new B(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=rr){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:o,at:this.now(),...s}),{apiKey:e,orgId:o,credential:n,...s}}clear(){this.cache.clear()}};function ne(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function jt(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var me=class{constructor(e,n,r,o){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=o}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof B?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<er)return r.keys;let o=this.inFlight.get(e);if(o!==void 0)return o;let s=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,s);let i=await s;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),o=n===""?void 0:r.find(s=>s.kid===n&&jt(s));return o===void 0&&(r=await this.keys(e,!0),o=n===""?void 0:r.find(s=>s.kid===n&&jt(s))),o}};function zt(t,e,n){try{let r=Qn({key:n,format:"jwk"});return Xn("RSA-SHA256",t,r,e)}catch{return!1}}var ye=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new me(e.fetchImpl??fetch,e.now??Date.now,n=>new B("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new C("malformed machine token");let s,i;try{s=ne(n),i=ne(r)}catch{throw new C("malformed machine token")}if(s.alg!=="RS256")throw new C(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new C(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==Gt)throw new C(`machine token audience must be ${Gt} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==Zn)throw new C(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let p=typeof i.org_id=="string"?i.org_id:"";if(p==="")throw new C("machine token carries no org_id \u2014 no tenancy to route by");let c=typeof i.exp=="number"?i.exp:0;if(c<=Math.floor(this.now()/1e3))throw new C("machine token is expired \u2014 re-mint and retry");let S=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(S===void 0)throw new C(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let P=Buffer.from(`${n}.${r}`,"ascii"),O=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!zt(P,O,S))throw new C("machine token signature failed verification");if(c<=Math.floor(this.now()/1e3))throw new C("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:p,credential:"machine"}}},sr="https://api.workos.com/sso/jwks/";function ir(t){return`${sr}${t.slice(t.lastIndexOf("/")+1)}`}var Fe=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new me(e.fetchImpl??fetch,this.now,n=>new B("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Jt(e))return!1;try{let n=ne(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new C("malformed user token");let s,i;try{s=ne(n),i=ne(r)}catch{throw new C("malformed user token")}if(s.alg!=="RS256")throw new C(`user token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new C(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let p=typeof i.org_id=="string"?i.org_id:"";if(p==="")throw new C("user token carries no org_id \u2014 no tenancy to route by");let c=typeof i.exp=="number"?i.exp:0;if(c<=Math.floor(this.now()/1e3))throw new C("user token is expired \u2014 re-authenticate and retry");let S=await this.cache.keyFor(ir(l),a);if(S===void 0)throw new C(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let P=Buffer.from(`${n}.${r}`,"ascii"),O=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!zt(P,O,S))throw new C("user token signature failed verification");if(c<=Math.floor(this.now()/1e3))throw new C("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:p,credential:"user"}}},we=class{verifier;bindings;constructor(e){this.verifier=new Fe({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new re({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new C("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Be(t,e,n,r){if(Jt(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}A();var ar=8080,Ke="serve",ts="0.0.0.0";function lr(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function ns(t=process.env){let e=(t.PORT??"").trim(),n=e===""?ar:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=pt(ce(lr(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?ce(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=i?{catalogUrl:ce(i,"URUN_CATALOG_URL"),anonKey:a}:null,p=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),c=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!p!=!!c)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 S=p?{keyId:c,key:p}:void 0,P={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},O=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],d=O.filter((u,y)=>Object.values(P)[y]==="");if(d.length!==0&&d.length!==O.length)throw new Error(`${O.join(", ")} must be set together (or all left unset) \u2014 missing: ${d.join(", ")}, which would half-configure the lane plane`);let w=d.length===0?P:void 0,v={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},g=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],b=g.filter((u,y)=>Object.values(v)[y]==="");if(b.length!==0&&b.length!==g.length)throw new Error(`${g.join(", ")} must be set together (or all left unset) \u2014 missing: ${b.join(", ")}, which would half-configure the pooler cutover`);let E=b.length===0?v:void 0,h={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},f=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],_=f.filter((u,y)=>Object.values(h)[y]==="");if(_.length!==0&&_.length!==f.length)throw new Error(`${f.join(", ")} must be set together (or all left unset) \u2014 missing: ${_.join(", ")}, which would half-configure the machine-identity rung`);let L=h.issuers.split(",").map(u=>u.trim()).filter(u=>u!=="");if(L.length===0&&_.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let m=Number(h.tokenTtlS);if(_.length===0&&(!Number.isFinite(m)||m<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(h.tokenTtlS)}`);let I=_.length===0?{jwksBaseUrl:h.jwksBaseUrl,issuers:L,tokenTtlS:m}:void 0,T=(t.URUN_WORKOS_ISSUERS??"").trim(),$=T.split(",").map(u=>u.trim()).filter(u=>u!=="");if(T!==""&&$.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let u of $){let y;try{y=new URL(u)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(u)}`)}if(y.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${u}) \u2014 the issuer is the user rung's trust root`)}return{port:n,baseUrl:r,apiUrl:s,catalog:l,ledgerSigning:S,lane:w,pooler:E,machine:I,...$.length>0?{userIssuers:$}:{}}}A();import{createHash as yr,randomUUID as Qt}from"crypto";A();import{request as cr}from"http";var dr="/pooler/v1/inference",q=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},ur=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},fr=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},Vt=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),pr=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Vt(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new q(t.status,e,n,t.retryAfterSeconds)};async function hr(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${dr}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:ur(e),firstMessage:fr(e)}});return new Promise((a,l)=>{let p=cr({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},c=>{let S=Number(c.headers["retry-after"]??"");a({status:c.statusCode??0,retryAfterSeconds:Number.isFinite(S)?S:void 0,body:c})});p.on("error",c=>l(new q(502,"pooler_unreachable",`the pooler channel failed: ${c.message}`))),p.end(i)})}var qt=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*gr(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
|
|
4
|
+
|
|
5
|
+
`);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=qt(s);i!==null&&(yield i)}let n=qt(e);n!==null&&(yield n)}async function Yt(t,e,n,r){let o=rt(e,n,r),s=o.model??"";if(s==="")throw new q(400,"missing_model","the pooler submit requires a model");let i=await hr(t,o,n,s,e.stream===!0);if(i.status>=400)throw await pr(i);let a=e.stream===!0?xe(n,gr(i)):await mr(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function mr(t,e){let n=await Vt(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new q(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return xe(e,(async function*(){yield o})())}var wr=512;function ve(t){return`urun-inference-proxy-${yr("sha256").update(t).digest("hex").slice(0,32)}`}var Se=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,l);let p=`px_${Qt()}`;return Yt(s,a,p,p)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ke,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:Ut(process.env,process.env.HOSTNAME)??void 0},r=He(n),o=n.decisionPool?Nt(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(De(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=wr;){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(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(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("; ")}`)}},Xt=512,br=1024,_e=class extends Error{constructor(){super(`conversation capacity reached (${Xt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function vr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(ae))return{concurrencyKey:e};if(n.startsWith(ae)||n.startsWith(Me))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(ae)||n.startsWith(Me)||t.set(n,r)}}}function Sr(t,e,n,r,o){let s=He({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ke,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...vr(r,o)});return{clients:De(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var ke=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${ve(e.apiKey)}:live`:`${ve(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):Sr(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Xt;){let e=this.byCaller.keys().next();if(e.done)throw new _e;let n=e.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 _e;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,Qt(),n)),r),i={createResponse:(a,l)=>s().backhaul.clients.createResponse(a,l),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=s().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=s().backhaul.clients.dedicatedSessionHandle;return l===void 0?s().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,l,p)=>s().backhaul.clients.createResponseOn(a,l,p),onSessionEnd:(a,l)=>s().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let p=s().backhaul.clients.openAudio;if(p===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return p(a,l)},i.openVideo=async a=>{let l=s().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=s().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=s().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=s().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=s().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(a)},i.speechSessionHandle=async a=>{let l=s().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(a)},i.openAudioOn=async(a,l,p)=>{let c=s().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(a,l,p)},i.openVideoOn=async(a,l)=>{let p=s().backhaul.clients.openVideoOn;if(p===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return p(a,l)},i.openTurnsOn=(a,l)=>{let p=s().backhaul.clients.openTurnsOn;if(p===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return p(a,l)},i.evictSpeechSession=async a=>{let l=s().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(a)},i.supportsTranscription=async a=>{let l=s().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=s().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=br;){let p=this.byHandle.keys().next();if(p.done)break;this.byHandle.delete(p.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),p=l===void 0?void 0:this.byCaller.get(l.apiKey),c=l===void 0||p===void 0?void 0:p.get(l.conversationId);if(l===void 0||c===void 0||l.apiKey!==e.apiKey)throw new ie("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=c,c.attachments+=1,c.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};A();var _r="/inference-ledger",kr=1e4,Ee=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Je=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},D=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},ze=class extends C{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},qe=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},Er=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",Ge],["output_minutes",Ge],["cost_nano_usd",Ge],["price_version",t=>t===null||typeof t=="string"]];function Rr(t){for(let[e,n]of Er){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Lr(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:Rr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ge(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function je(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function Ir(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Zt(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Ar(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&Zt(t.started_at,n.started_at)&&Zt(t.completed_at,n.completed_at)&&je(t.prompt_tokens,n.prompt_tokens)&&je(t.completion_tokens,n.completion_tokens)&&je(t.output_units,n.output_units)&&Ir(t.output_minutes,n.output_minutes)}function Pr(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
|
|
6
|
+
`)}async function Or(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(Pr(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Tr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new D(`${e} answered a "recorded" that is not an object: ${JSON.stringify(t)}`);let n=t,r=n.inference_id;if(typeof r!="string"||r==="")throw new D(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new D(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new D(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=p=>{if(!(p in n))throw new D(`${e} answered a row with no ${p} field: ${JSON.stringify(t)}`);let c=n[p];if(c===null)return null;if(typeof c!="string")throw new D(`${e} answered a non-string ${p}: ${JSON.stringify(c)}`);if(!/[^\s]/.test(c))throw new D(`${e} answered a BLANK ${p} (${JSON.stringify(c)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return c},i=s("price_version"),a=s("unpriced_reason"),l=o!=null;if(l&&(i===null||a!==null))throw new D(`${e} 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(!l&&(i!==null||a===null))throw new D(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var Re=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${_r}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Or(n,this.opts.signing)}):JSON.stringify(n)}catch(p){throw new D(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${p instanceof Error?p.message:String(p)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(kr)})}catch(p){throw new D(`the uRun ledger surface at ${r} could not be reached: ${p instanceof Error?p.message:String(p)}`)}if(s.status===409){let p=await s.text().catch(()=>""),c=Lr(p);throw c.status==="found"&&Ar(n,c.row)?new Je(c.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.`):c.status==="not_in_this_org"?new Ee(`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 Ee(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${c.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${p.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new ze("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let p=await s.text().catch(S=>`<body unreadable: ${S instanceof Error?S.message:String(S)}>`),c;try{let S=JSON.parse(p);if(S!==null&&typeof S=="object"&&"error"in S){let P=S.error;P!==null&&typeof P=="object"&&"code"in P&&(c=P.code)}}catch{}throw c==="ledger_signature_invalid"?new qe(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+p.slice(0,400)):new D(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${p.slice(0,400)}`)}let i;try{i=await s.json()}catch(p){throw new D(`the uRun ledger surface at ${r} answered a body that is not JSON: ${p instanceof Error?p.message:String(p)}`)}let a=i?.recorded;if(a===void 0)throw new D(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=Tr(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new D(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};A();import{createServer as Io}from"http";A();import{createCipheriv as Cr,createDecipheriv as Ur,hkdfSync as Nr,randomBytes as $r,randomUUID as nn}from"crypto";import{resolve4 as xr}from"dns/promises";A();var en="/realtime/openai.quic-relay";async function tn(t){let e=await fetch(`${t.sfuBase}${en}${t.query}`,{method:"POST",headers:{"content-type":"application/json",authorization:t.upstreamHeaders.authorization??""},body:"{}"});if(e.status!==201){let s=await e.text().catch(()=>"");throw new Error(`quic relay ${t.sfuBase}${en} -> ${e.status} ${s}`)}let n=await e.json(),r=new URL(t.sfuBase).host,o=n.url??`https://${r}:${n.wtPort??4443}/wt`;return{status:201,body:{callId:n.callId,url:o,token:n.token,certHashes:n.certHashes},location:`/v1/realtime/calls/${n.callId}`}}var Ve="/v1/realtime/calls",rn="/v1/realtime/client_secrets",Mr="session-server-ts-pods.urun.svc.cluster.local",on=8081,Hr="/realtime/openai.relay",Dr=262144,Wr=600;function sn(t){let e=t.secret===void 0?void 0:Buffer.from(Nr("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>jr(await xr(Mr))),r=(o,s,i,a)=>{o.writeHead(s,{"content-type":"application/json"}),o.end(JSON.stringify({error:{message:i,type:"invalid_request_error",...a?{code:a}:{}}}))};return async(o,s)=>{let i=new URL(o.url??"/","http://proxy");if(o.method!=="POST"||i.pathname!==Ve&&i.pathname!==rn)return!1;let a=await Br(o);if(a===null)return r(s,413,"request body too large"),!0;let l=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");if(l.startsWith("ek_")){let g=e===void 0?null:Gr(e,l.slice(3));if(g===null)return r(s,401,"invalid or expired client secret","invalid_api_key"),!0;o.headers.authorization=`Bearer ${g}`}try{await t.authorize(o)}catch(g){let b=typeof g=="object"&&g!==null&&"status"in g&&typeof g.status=="number"?g.status:401;return r(s,b,g instanceof Error?g.message:String(g)),!0}if(i.pathname===rn){if(e===void 0)return r(s,501,"client secrets are not configured on this proxy"),!0;let g=a.length===0?{}:JSON.parse(a.toString("utf8")),b=typeof g=="object"&&g!==null&&"session"in g?g.session:null,E=Math.floor(Date.now()/1e3)+Wr,h=(o.headers.authorization??"").replace(/^Bearer\s+/i,"");return s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({value:`ek_${Kr(e,h,E)}`,expires_at:E,session:b})),!0}if(i.searchParams.get("transport")==="quic"){let g=i.searchParams.get("model");if(g===null)return r(s,400,"model is required (?model=)"),!0;let b=`quic_${nn().replaceAll("-","")}`,E=new URLSearchParams(i.searchParams);E.set("model",g),E.set("call_id",b);let h="no media edge resolved";for(let f of await n())try{let _=await tn({sfuBase:`http://${f}:${on}`,query:`?${E}`,upstreamHeaders:{authorization:o.headers.authorization??""}});return s.writeHead(201,{"content-type":"application/json",location:`${Ve}/${_.body.callId}`}),s.end(JSON.stringify(_.body)),!0}catch(_){h=`${f}: ${String(_)}`}return r(s,502,`no media edge accepted the quic call (${h})`),!0}let{sdp:p,session:c}=await Fr(o.headers["content-type"]??"",a);if(p===void 0)return r(s,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)"),!0;let S=typeof c=="object"&&c!==null&&"model"in c&&typeof c.model=="string"?c.model:void 0,P=i.searchParams.get("model")??S;if(P===void 0)return r(s,400,"model is required (?model= or session.model)"),!0;let O=`rtc_${nn().replaceAll("-","")}`,d=new URLSearchParams(i.searchParams);d.set("model",P),d.set("call_id",O);let w=JSON.stringify({sdp:p,...c!==void 0?{session:c}:{}}),v="no media edge resolved";for(let g of await n()){let b;try{b=await fetch(`http://${g}:${on}${Hr}?${d}`,{method:"POST",headers:{"content-type":"application/json",authorization:o.headers.authorization??""},body:w,signal:AbortSignal.timeout(1e4)})}catch(h){v=`${g}: ${String(h)}`;continue}let E=await b.text();if(b.status===201)return s.writeHead(201,{"content-type":"application/sdp",location:`${Ve}/${O}`}),s.end(E),!0;if(b.status>=500||b.status===404||b.status===405||b.status===501){v=`${g}: ${b.status} ${E}`;continue}return r(s,b.status,E),!0}return r(s,503,`no media edge answered the offer (${v})`,"media_edge_unavailable"),!0}}async function Fr(t,e){if(t.startsWith("application/sdp"))return{sdp:e.toString("utf8")};if(!t.startsWith("multipart/form-data"))return{};let n=await new Response(new Uint8Array(e),{headers:{"content-type":t}}).formData(),r=n.get("sdp"),o=n.get("session");return{...typeof r=="string"?{sdp:r}:{},...typeof o=="string"?{session:JSON.parse(o)}:{}}}async function Br(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>Dr)return null;e.push(r)}return Buffer.concat(e)}function Kr(t,e,n){let r=$r(12),o=Cr("aes-256-gcm",t,r),s=Buffer.concat([o.update(JSON.stringify({b:e,e:n}),"utf8"),o.final()]);return Buffer.concat([r,o.getAuthTag(),s]).toString("base64url")}function Gr(t,e){try{let n=Buffer.from(e,"base64url"),r=Ur("aes-256-gcm",t,n.subarray(0,12));r.setAuthTag(n.subarray(12,28));let o=JSON.parse(Buffer.concat([r.update(n.subarray(28)),r.final()]).toString("utf8"));if(typeof o!="object"||o===null||!("b"in o)||!("e"in o))return null;let{b:s,e:i}=o;return typeof s!="string"||typeof i!="number"?null:i>Date.now()/1e3?s:null}catch{return null}}function jr(t){for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}A();import{SessionAllocationError as ro}from"@urun-sh/core";import{createWebsocketDocConnector as oo}from"@urun-sh/core/internal";import so from"ws";A();import{request as Jr}from"http";var zr="/pooler/v1/lanes/pick",qr="/pooler/v1/lanes/status",Vr=1e4,oe=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function an(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),p=Jr({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:o},c=>{let S=[];c.on("data",P=>S.push(P)),c.on("end",()=>{let P=Buffer.concat(S).toString("utf8"),O=null;try{O=P===""?null:JSON.parse(P)}catch{O=null}s({status:c.statusCode??0,json:O})}),c.on("error",i)});p.on("timeout",()=>{p.destroy(new oe(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),p.on("error",i),p.end(l)})}function ln(t,e,n){if(t===503)return new le(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function cn(t){return{async pick({pool:e,app:n,fn:r,sharedApp:o,model:s,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),xt),l=await an(t,"POST",zr,{pool:e,app:n,fn:r,model:s,hold_ms:a,...o?{shared_app:!0}:{}},a+Vr);if(l.status!==200)throw ln(l.status,l.json,e);return(l.json?.lanes??[]).filter(c=>typeof c.lane_id=="string"&&c.lane_id!==""&&typeof c.host=="string"&&c.host!=="").map(c=>({laneId:c.lane_id,host:c.host}))},async status(){let e=await an(t,"GET",qr,void 0,5e3);if(e.status!==200)throw ln(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}A();import*as V from"yjs";import{SessionDocumentImpl as Yr}from"@urun-sh/core/internal";var Qr=3e4;function Xr(t){return(e,n,r)=>{let o=t(e);V.applyUpdate(n,V.encodeStateAsUpdate(o));let s=a=>V.applyUpdate(o,a),i=a=>V.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)}}}}function Ye(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Xr(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=c=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let S=r.get(c);return S||(S=new Yr(c,e,n),r.set(c,S)),S},i=new Map,a=c=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let S=i.get(c);if(!S){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${c}"`);S=t.streamEndpoint(c),i.set(c,S)}return S},l=c=>{let S="llm-resp:";if(!c.startsWith(S))throw new Error(`lane session exposes no stream "${c}" \u2014 only the llm reply lanes (${S}<rid>)`);async function*P(){let O=a(c);try{yield*O.messages()}finally{i.delete(c),await O.close()}}return{messages:()=>P(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(c){return s(c)},stream:l,streamEndpoint:a,async end(){},async whenLive(c){let S=s("llm");if(S.synced===!0)return;let P=c?.timeout??t.whenLiveTimeoutMs??Qr;await new Promise((O,d)=>{let w=setTimeout(()=>{v(),d(new Error(`lane ${e} llm doc never synced within ${P}ms`))},P),v=S.onSynced(()=>{clearTimeout(w),c?.signal?.removeEventListener("abort",g),O()}),g=()=>{clearTimeout(w),v(),d(c?.signal?.reason instanceof Error?c.signal.reason:new Error("aborted"))};c?.signal?.addEventListener("abort",g,{once:!0})})},destroy(){o=!0;for(let c of r.values())c.dispose();r.clear();for(let[c,S]of i)i.delete(c),S.close()}}}A();import Le,{WebSocketServer as Zr}from"ws";import{ENVELOPE_KIND as pn,STREAM_END as eo,StreamFragmentReassembler as to}from"@urun-sh/core";var dn="/stream/";function un(t){if(!t.startsWith(dn))return null;let e=t.slice(dn.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Pe(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Ie(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>pn.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Ae=class{reassembler=new to;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===eo&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},Xe=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;a.bytes+o.byteLength>fn&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${fn} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},fn=8*1024*1024,F=new Xe;function hn(t,e){let n=new Ae,r={send(o){F.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Ie(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),F.detach(t,e,r)}};return F.attach(t,e,r),r}function no(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function gn(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new Le(r,Pe(e)),s=new Ae;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Ie(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Ie(i),o.readyState!==Le.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Qe(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
|
|
7
|
+
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
8
|
+
Connection: close\r
|
|
9
|
+
Content-Type: text/plain; charset=utf-8\r
|
|
10
|
+
Content-Length: ${Buffer.byteLength(o)}\r
|
|
11
|
+
\r
|
|
12
|
+
${o}`)}function mn(t,e){let n=e.heartbeatMs??3e4,r=e.streamLeaseMs??6e4,o=new Zr({noServer:!0,handleProtocols:(d,w)=>{let v=un(new URL(w.url??"/","http://localhost").pathname);if(!v)return!1;let g=Pe(v.name);return d.has(g)?g:!1}}),s=new Map,i=new Set,a=!1,l=new Map,p=(d,w,v)=>{r>0&&l.set(d,{at:Date.now(),label:w,reap:v})},c=d=>{let w=l.get(d);w&&(w.at=Date.now())},S=r>0?setInterval(()=>{let d=Date.now();for(let[w,v]of l)d-v.at<r||(l.delete(w),console.warn(`[lane-stream] ${v.label}: lease expired (no data for ${r} ms) \u2014 terminating`),v.reap())},Math.max(10,Math.floor(r/4))):void 0;S?.unref?.();let P=(d,w,v,g)=>{let b={client:v,upstream:g,laneId:d,name:w};i.add(b);let E=h=>{if(i.delete(b)){l.delete(v),console.warn(`[lane-stream] ${d}/${w}: host-affinity pump torn down (${h})`);for(let f of[v,g])try{(f.readyState===Le.OPEN||f.readyState===Le.CONNECTING)&&f.close(1001,"lane stream pump closed")}catch{}}};if(p(v,`${d}/${w} pump`,()=>{for(let h of[v,g])try{h.terminate()}catch{}E("lease expired")}),n>0){let h=(f,_)=>{let L=!0,m=()=>{L=!0};f.on("pong",m),f.on("message",m);let I=setInterval(()=>{if(!L){console.warn(`[lane-stream] ${d}/${w}: pong timeout on ${_} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${_} dial never sends a close)`),clearInterval(I);try{f.terminate()}catch{}E(`${_} pong timeout`);return}L=!1;try{f.ping()}catch{}},n);I.unref?.();let T=()=>clearInterval(I);f.once("close",T),f.once("error",T)};h(v,"client"),h(g,"host")}v.on("message",h=>{c(v);try{g.send(h,{binary:!0})}catch(f){E(`upstream send failed: ${String(f)}`)}}),g.on("message",h=>{c(v);try{v.send(h,{binary:!0})}catch(f){E(`client send failed: ${String(f)}`)}}),v.on("close",()=>E("client socket closed")),v.on("error",()=>E("client socket error")),g.on("close",()=>E("host socket closed")),g.on("error",()=>E("host socket error"))},O=(d,w,v)=>{let g;try{g=new URL(d.url??"/","http://localhost")}catch{Qe(w,400,"malformed upgrade URL");return}w.on("error",()=>w.destroy());let b=un(g.pathname);b&&(a||w.destroyed||(async()=>{let E=g.searchParams.get("token")??"",h=null;try{h=E===""?null:await e.verifyToken(E,b.laneId,b.name)}catch{h=null}if(h===null){Qe(w,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let f=await e.hostOf(b.laneId).catch(()=>null);if(f&&f!==e.selfAddress)try{let _=await e.podToPodDial(b.laneId,b.name,f);o.handleUpgrade(d,w,v,L=>{P(b.laneId,b.name,L,_)});return}catch(_){console.warn(`[lane-stream] ${b.laneId}/${b.name}: host dial to ${f} failed (${String(_)}) \u2014 falling back to the local relay`)}}o.handleUpgrade(d,w,v,f=>{let _=no(f,()=>c(f));if(s.set(f,_),F.attach(b.laneId,b.name,_),p(f,`${b.laneId}/${b.name}`,()=>f.terminate()),n>0){let m=!0,I=()=>{m=!0};f.on("pong",I),f.on("message",I);let T=setInterval(()=>{if(!m){console.warn(`[lane-stream] ${b.laneId}/${b.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(T),f.terminate();return}m=!1;try{f.ping()}catch{}},n);T.unref?.();let $=()=>clearInterval(T);f.once("close",$),f.once("error",$)}f.on("message",m=>{c(f);let I=new Uint8Array(m);try{Ie(I)}catch(T){console.warn(`[lane-stream] ${b.laneId}/${b.name}: dropped malformed envelope: ${String(T)}`);return}F.deliver(b.laneId,b.name,_,I),I[1]===pn.END&&F.detach(b.laneId,b.name,_)});let L=()=>{s.delete(f),l.delete(f),F.detach(b.laneId,b.name,_)};f.on("close",L),f.on("error",L)})})().catch(()=>{w.destroyed||Qe(w,500,"lane stream upgrade failed")}))};return t.on("upgrade",O),{async close(){a=!0,t.off("upgrade",O),clearInterval(S),l.clear(),F.clear();for(let d of s.values())d.close(1001,"lane stream host shutting down");s.clear();for(let d of i)for(let w of[d.client,d.upstream])try{w.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}function io(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new dt(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}var ao={"prod-usw2":["us-west1"]};function yn(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(d,w,v,g,b,E)=>{let h=v?m=>hn(d,m):m=>gn(d,m,{hostUrl:`ws://${g}/stream/${d}`,token:()=>te(d,t.tokenSecret,void 0,void 0,E)}),f=v?Ye({laneId:d,roomDoc:m=>t.roomDoc(d,m),streamEndpoint:h}):Ye({laneId:d,streamEndpoint:h,connector:oo({serverUrl:`ws://${g}/doc`,sessionId:d,token:()=>te(d,t.tokenSecret,void 0,void 0,E),WebSocketPolyfill:so})}),_=v?l(d):Ct(f,`lane:${d}`,{armOnFirstSync:!0}),L={session:f,responses:new ot(f,{sessionTag:null}),gone:_,goneWatch:_,laneId:d,pool:w,inFlight:0,laneSession:f,self:v,host:g??"",mintedRelease:b??"",retireWhenIdle:!1};return n.set(d,L),_.onGone(()=>p(L)),L},l=d=>{let w=null,v=!1,g=new Set,b=h=>{if(!w){w=h;for(let f of[...g])f(h);g.clear()}},E=t.hostedSignal?.(d,h=>{if(h){v=!0;return}v&&b(new ie(`the lane ${d} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>w,onGone(h){return w?(h(w),()=>{}):(g.add(h),()=>g.delete(h))},dispose(){E?.(),g.clear()}}},p=d=>{c(d)&&(n.delete(d.laneId),r.delete(d.laneId),d.goneWatch?.dispose(),F.forgetLane(d.laneId))},c=d=>{let w=d.laneId;return typeof w=="string"&&n.get(w)===d},S=d=>{c(d)&&(d.self&&!t.closeLane||(i.add(d.laneId),d.self&&t.closeLane?.(d.laneId),p(d)))},P=(d,w)=>{throw t.metrics?.observeLane503Fast(w??""),s.set(d,e()),new le(d)},O=async(d,w)=>{let v=io(w);o.add(v);let g=e();try{let b=await t.laneWarmWaitMsFor?.(d,w)??t.laneColdWakeDefaultMs??0,E;try{E=await t.plane.pick({pool:v,app:w.appSlug,fn:w.fnName??"",model:d,holdMs:b,...w.sharedApp?{sharedApp:!0}:{}})}catch(I){throw I instanceof oe?new ro(`lane pick hold expired for ${v}: ${I.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):I}t.metrics?.observeLaneReady(d??"",E.length);let h=await t.currentReleaseOf?.(w)??null,f=new Set(E.map(I=>I.laneId));for(let I of i)f.has(I)||i.delete(I);let L=E.filter(I=>{let T=n.get(I.laneId);return T!==void 0&&h!==null&&T.mintedRelease!==""&&T.mintedRelease!==h&&(T.retireWhenIdle=!0,T.inFlight===0)?(S(T),!1):!i.has(I.laneId)}).map(I=>({laneId:I.laneId,self:I.host===t.selfAddress,host:I.host,region:I.region})).sort((I,T)=>{let $=ao[t.seatRegion??""]??[],u=new Map($.map((k,U)=>[k,U])),y=$.length===0?0:(I.region!==void 0?u.get(I.region):void 0)??$.length,R=$.length===0?0:(T.region!==void 0?u.get(T.region):void 0)??$.length;return y!==R?y-R:I.self!==T.self?I.self?-1:1:(r.get(I.laneId)??0)-(r.get(T.laneId)??0)})[0];L||P(v,d);let m=n.get(L.laneId);return m?.goneWatch?.gone()&&(p(m),m=void 0),m&&(m.pool!==v||m.self!==L.self||m.host!==L.host)&&(p(m),m=void 0),m||(m=a(L.laneId,v,L.self,L.host,h,w.sharedOrgId??void 0)),m.inFlight+=1,r.set(L.laneId,(r.get(L.laneId)??0)+1),{app:v,entry:m,identity:{kind:"catalog",model_id:w.modelId??d??"",variant:w.variant??""}}}finally{t.metrics?.observeLanePick(d??"",e()-g)}};return{sessionFor(d,w){return O(d,w)},release(d){c(d)&&(d.inFlight=Math.max(0,d.inFlight-1),r.set(d.laneId,d.inFlight),d.inFlight===0&&d.retireWhenIdle&&S(d))},owns(d){return c(d)},entryFor(d){return n.get(d)??null},evict(d){c(d)&&(d.gone.dispose(),n.delete(d.laneId),r.set(d.laneId,0),d.laneSession.destroy())},async status(){let d=[...new Set([...o,...[...n.values()].map(g=>g.pool)])].sort(),w=await t.plane.status().catch(()=>[]),v=new Map(lo(w));return Promise.all(d.map(async g=>{let b=v.get(g)??{pool:g,lanes:[],lastDemandAt:null};return{pool:g,lanes:b.lanes,lastDemandAt:b.lastDemandAt,local:[...n.values()].filter(E=>E.pool===g).map(E=>({laneId:E.laneId,inFlight:E.inFlight,self:E.self,host:E.host})),lastRefusalAt:s.get(g)??null}}))},async close(){for(let d of n.values())d.gone.dispose(),d.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(d=>({pool:d.pool,laneId:d.laneId,inFlight:d.inFlight}))}}}function lo(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}A();var co="urun:node-scheduler:apps:v1";function uo(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function wn(t){return async e=>{let n=uo(e);if(n===null)return null;try{let r=await t.hget(co,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}A();import{WebSocketServer as ko}from"ws";A();import*as vn from"yjs";import*as X from"y-protocols/sync";import*as K from"y-protocols/awareness";import*as N from"lib0/encoding";import*as Z from"lib0/decoding";import*as Sn from"lib0/map";import po from"lodash.debounce";A();var bn=()=>{};var ho=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,go=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,mo=0,yo=1;var wo=process.env.GC!=="false"&&process.env.GC!=="0",bo=process.env.YPERSISTENCE,Oe=null;if(typeof bo=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var Q=new Map,Te=0,et=1,vo=(t,e,n)=>{let r=N.createEncoder();N.writeVarUint(r,Te),X.writeUpdate(r,t);let o=N.toUint8Array(r);n.conns.forEach((s,i)=>se(n,i,o))},Ze=class extends vn.Doc{constructor(e){super({gc:wo}),this.name=e,this.conns=new Map,this.awareness=new K.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 c=this.conns.get(i);c!==void 0&&(r.forEach(S=>{c.add(S)}),s.forEach(S=>{c.delete(S)}))}let l=N.createEncoder();N.writeVarUint(l,et),N.writeVarUint8Array(l,K.encodeAwarenessUpdate(this.awareness,a));let p=N.toUint8Array(l);this.conns.forEach((c,S)=>{se(this,S,p)})};this.awareness.on("update",n),this.on("update",vo),!1}},tt=(t,e=!0)=>Sn.setIfUndefined(Q,t,()=>{let n=new Ze(t);return n.gc=e,Oe!==null&&Oe.bindState(t,n),Q.set(t,n),n}),So=(t,e,n)=>{try{let r=N.createEncoder(),o=Z.createDecoder(n);switch(Z.readVarUint(o)){case Te:N.writeVarUint(r,Te),X.readSyncMessage(o,r,e,t),N.length(r)>1&&se(e,t,N.toUint8Array(r));break;case et:{K.applyAwarenessUpdate(e.awareness,Z.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},Y=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),K.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Oe!==null&&(Oe.writeState(t.name,t).then(()=>{t.destroy()}),Q.delete(t.name))}e.close()},se=(t,e,n)=>{e.readyState!==mo&&e.readyState!==yo&&Y(t,e);try{e.send(n,r=>{r!=null&&Y(t,e)})}catch{Y(t,e)}},_o=3e4,_n=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=tt(n,r);o.conns.set(t,new Set),t.on("message",a=>So(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&Y(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{Y(o,t),clearInterval(i)}}},_o);t.on("close",()=>{Y(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=N.createEncoder();N.writeVarUint(a,Te),X.writeSyncStep1(a,o),se(o,t,N.toUint8Array(a));let l=o.awareness.getStates();if(l.size>0){let p=N.createEncoder();N.writeVarUint(p,et),N.writeVarUint8Array(p,K.encodeAwarenessUpdate(o.awareness,Array.from(l.keys()))),se(o,t,N.toUint8Array(p))}}};var nt="/doc/",En=30,Eo=1e4,kn="llm";function Ro(t){if(!t.startsWith(nt))return null;let e=t.slice(nt.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function ee(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
|
|
13
|
+
`;t.end(`HTTP/1.1 ${e} ${r}\r
|
|
14
|
+
Connection: close\r
|
|
15
|
+
Content-Type: text/plain; charset=utf-8\r
|
|
16
|
+
Content-Length: ${Buffer.byteLength(o)}\r
|
|
17
|
+
\r
|
|
18
|
+
${o}`)}function Rn(t,e){let n=new ko({noServer:!0}),r=new Set,o=new Map,s=new Map,i=h=>o.get(`${h}/${kn}`)??0,a=h=>s.get(h)??0,l=new Map,p=new Map,c=new Set,S=new Set,P=new Map,O=new Map,d=4096,w=!1,v=(h,f,_)=>{let L=i(h)>0,m=a(h),I=m>0,T=`${h}/${f}`,$=o.get(T)??0;_>0?o.set(T,_):o.delete(T);let u=m+_-$;u>0?s.set(h,u):s.delete(h);let y=i(h)>0,R=u>0;if(L!==y){y?g(h):b(h);for(let k of l.get(h)??[])k(y)}I&&!R&&queueMicrotask(()=>{let k=`${h}/`;for(let[U,x]of[...Q.entries()])!U.startsWith(k)||x.conns.size>0||(Q.delete(U),x.destroy())})},g=h=>{if(!e.hostRegistry||p.has(h))return;let f=()=>{e.hostRegistry?.setHost(h,e.selfAddress).catch(()=>{})};f();let _=setInterval(f,Eo);_.unref?.(),p.set(h,_)},b=h=>{let f=p.get(h);f&&(clearInterval(f),p.delete(h)),e.hostRegistry&&e.hostRegistry.delHost(h,e.selfAddress).catch(()=>{})},E=(h,f,_)=>{let L;try{L=new URL(h.url??"/","http://localhost")}catch{ee(f,400,"malformed upgrade URL");return}f.on("error",()=>f.destroy()),f.on("close",()=>S.delete(f));let m=Ro(L.pathname);if(!m){if(L.pathname.startsWith(nt)){ee(f,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}S.add(f);return}c.add(f);let I=!1;(async()=>{if(O.has(m.laneId)){ee(f,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let T=L.searchParams.get("token")??"",$=null;try{$=T===""?null:await e.verifyToken(T,m.laneId,m.docName)}catch{$=null}if($===null){ee(f,401,"invalid or missing lane doc token");return}let u=$;if(u.tenant!==void 0&&e.laneTenantOf){let y=null;try{y=await e.laneTenantOf(m.laneId)}catch{y=null}if(y==null||y==="")e.onLaneTenantMissing?.();else if(u.tenant!==y){ee(f,403,"lane doc token org does not match the lane record");return}}w||f.destroyed||(I=!0,n.handleUpgrade(h,f,_,y=>{c.delete(f),r.add(y),y.on("close",()=>r.delete(y));let R=P.get(m.laneId);R||(R=new Set,P.set(m.laneId,R)),R.add(y),y.on("close",()=>{R.delete(y),R.size===0&&P.delete(m.laneId)});let k=u.scope===$t||u.scope===void 0&&typeof u.app=="string"&&typeof u.fn=="string"&&u.aud==="sfu";if(k){let x=`${m.laneId}/${m.docName}`,W=(o.get(x)??0)+1;v(m.laneId,m.docName,W),W>1&&m.docName===kn&&e.hostRegistry?.setHost(m.laneId,e.selfAddress).catch(()=>{})}y.on("close",()=>{if(!k)return;let x=`${m.laneId}/${m.docName}`;v(m.laneId,m.docName,Math.max(0,(o.get(x)??1)-1))}),_n(y,h,{docName:`${m.laneId}/${m.docName}`,gc:!0})}))})().catch(()=>{!I&&!f.destroyed&&ee(f,500,"lane doc upgrade failed")}).finally(()=>c.delete(f))};return t.on("upgrade",E),{async close(){w=!0,t.off("upgrade",E);for(let f of[...p.keys()])b(f);await new Promise(f=>{if(r.size===0&&c.size===0){f();return}let _=r.size+c.size,L=()=>{_-=1,_<=0&&f()};for(let m of r)m.once("close",L);for(let m of c)m.once("close",L);for(let m of r)m.close(1001,"lane doc host shutting down");for(let m of c)m.destroy()}),o.clear(),s.clear(),l.clear()},roomDoc(h,f){return tt(`${h}/${f}`,!0)},isHosted(h){return i(h)>0},onHostedChange(h,f){let _=l.get(h);return _||(_=new Set,l.set(h,_)),_.add(f),f(i(h)>0),()=>{_.delete(f)}},closeLane(h){if(O.set(h,!0),O.size>d){let f=O.keys().next().value;f!==void 0&&O.delete(f)}b(h);for(let f of P.get(h)??[])f.close(1001,`lane ${h} retired \u2014 the app's release moved`)}}}import Ao from"ws";import Po from"ioredis";A();var Ce="/inference-usage",Ln=25e3;var Lo=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function In(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Lo.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var Ue=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Ce}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(Ln)})}catch(i){throw new de(`the uRun usage surface (POST ${Ce}) could not be reached within ${Ln}ms: ${In(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new C("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 de(`the uRun usage surface (POST ${Ce}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new de(`the uRun usage surface (POST ${Ce}) answered HTTP ${o.status} with a body that is not JSON: ${In(i)}`)}return _t(s,this.opts.onRejectedRow)}};var Oo=5e3,To=1e3,Co=1500,Uo=3e3,No="/api/client-tokens";function Ne(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function An(t,e,n,r){Ne(t,e,{error:{message:n,type:r}})}async function $o(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${No}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Uo)});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 Bi(t){let e=t.resolver??new re({gatewayUrl:t.baseUrl}),n=t.machine?new ye({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=t.userIssuers?new we({issuers:t.userIssuers,gatewayUrl:t.baseUrl}):null,o=new ge(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),s=null,i=null,a=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let u=new Po(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),y=Mt({redis:u});return{registry:yn({selfAddress:t.lane.selfAddress,seatRegion:t.pooler.region,tokenSecret:t.lane.tokenSecret,plane:cn({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(k,U)=>s?.onHostedChange(k,U)??(()=>()=>{}),roomDoc:(k,U)=>{if(!s)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return s.roomDoc(k,U)},metrics:o,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(k,U)=>y.rows().then(x=>{let W=it(x,U);return W?.warm_wait_s!==void 0?W.warm_wait_s*1e3:void 0}),currentReleaseOf:wn(u),closeLane:k=>s?.closeLane(k)}),catalog:y,redis:u}})(),l=t.registry??new Se({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry,pooler:t.pooler}),p=t.probeControlPlane??(()=>$o(t.baseUrl)),c=async()=>{let u=null;for(let k of l.decisionPools()){u=k;break}if(!u)return null;let y=u.stats();if(y.some(k=>k.draining))return{ok:!1,detail:"decision pool draining"};if(y.every(k=>k.attached===0&&k.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let R=await u.pingReady(Co);return{ok:R,detail:R?"a decision slot answered its session ping":"no decision slot answered its session ping"}},S=t.usageClient??new Ue({apiUrl:t.apiUrl}),P=t.ledgerClient??new Re({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),O=process.env.URUN_SHARED_ORG_ID?.trim(),d=process.env.URUN_SHARED_ORG_API_KEY?.trim();O&&d&&(async()=>{try{await l.decisionWarmerFor({orgId:O,apiKey:d})?.warmFor(Ot)}catch(u){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(u instanceof Error?u.message:u)}
|
|
19
|
+
`)}})();let w=async u=>Be(be(u.headers.authorization),e,n,r),v=async u=>{let y=await w(u);if(y.billingAudience==="platform"&&y.creditsAdmissionOk===!1){let R=y.creditsRefusalReason;throw new z(R==="spend_cap_reached"||R==="insufficient_credits"?R:void 0)}return y},g=u=>u instanceof C?{status:u.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:u instanceof z?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...u.code!==void 0?{code:u.code}:{}}:u instanceof B?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:u.detail}:null,b={write:(u,y)=>P.write(be(u.headers.authorization),y),observe:u=>o.observeLedger(u),...t.ledgerLog?{report:t.ledgerLog}:{}},E=Tt({clients:async u=>l.clientsFor(await v(u)),usage:{authorize:u=>be(u.headers.authorization),lookup:(u,y)=>S.lookup(u,y)},statusOf:g,...t.requestLog?{requestLog:t.requestLog}:{},observe:u=>o.observe(u),ledger:b}),h=sn({authorize:async u=>{await v(u)},...t.lane?{secret:t.lane.tokenSecret}:{}}),f=null,_=null,L=Io((u,y)=>{let R=new URL(u.url??"/","http://localhost");(async()=>{if(u.method==="GET"&&R.pathname==="/healthz"){Ne(y,200,{ok:!0});return}if(u.method==="GET"&&R.pathname==="/readyz"){let x=Date.now();if((!f||x-f.at>=Oo)&&(f={at:x,...await p()}),!_||x-_.at>=To){let j=await c();_=j===null?{at:x,ok:!0,detail:null}:{at:x,ok:j.ok,detail:j.detail}}let W=(f?.ready??!1)&&_.ok,G=_.detail===null?f?.detail??"control plane not yet probed":`${f?.detail??"control plane not yet probed"}; ${_.detail}`;Ne(y,W?200:503,{ok:W,control_plane:G});return}if(u.method==="GET"&&R.pathname==="/lanez"){Ne(y,200,{pools:a?await a.registry.status():null});return}let k=R.pathname==="/v1"||R.pathname.startsWith("/v1/"),U=R.pathname.startsWith("/partners/");if(!k&&!U){An(y,404,`no route for ${u.method} ${R.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}await h(u,y)||E(u,y)})().catch(k=>{if(!y.headersSent){An(y,500,String(k instanceof Error?k.message:k),"proxy_error");return}y.end()})}),m=t.conversations??new ke({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:a?null:t.catalog,catalogRows:a?()=>a.catalog.rows():void 0,lanes:a?.registry}),I=new WeakMap,T=[lt(L,{authenticate:async u=>{let y=await Be(u,e,n,r),R=m.connectionFor(y);return{clients:R.clients,scope:ve(y.apiKey),onBindResumeHandle:R.bindResumeHandle,clientsForResume:R.clientsForResume,release:R.release}}}),ft(L,{clients:async u=>l.clientsFor(await v(u)),statusOf:g}).close,gt(L,{resolver:{resolve:async(u,y,R)=>{let k=await v(u),U=m.connectionFor(k,bt(u)),x;try{x=await vt(mt(U.clients,t.realtimeCompanions),yt(u),y,wt(u),R)}catch(j){throw U.release().catch(()=>{}),j}let W=x.release,G={...x,release:async()=>{await W?.(),await U.release()}};return I.set(G,k.orgId),G}},onSessionEnded:u=>{Pt({record:{event:"inference_request",ts:new Date().toISOString(),inference_id:ct(),method:"GET",path:"/v1/realtime",status:200,delivered:!0,stream_error:!1,model:u.binding.model??null,stream:null,org:I.get(u.binding)??null,duration_ms:u.connected_ms,ttft_ms:null,prompt_tokens:null,completion_tokens:null,output_units:null,output_minutes:null,output_seconds:null,session_seconds:u.connected_ms/1e3,session_id:u.binding.audioSession?.audio.sessionId??null,queue_ms:null,prefill_ms:null,decode_ms:null,total_ms:null,catalog:u.binding.catalog??{kind:"unresolved",reason:"the realtime binding carries no dial-time catalog identity (no billing-identity oracle wired, or the composite lane)"}},ledger:b,req:u.req})}})];if(t.lane&&a){let u=t.lane,y=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;s=Rn(L,{verifyToken:(k,U)=>We(k,U,u.tokenSecret,void 0,y),selfAddress:u.selfAddress,laneTenantOf:k=>a.redis.get(`lane_tenant:${k}`),onLaneTenantMissing:()=>o.observeLaneDocTenantMissing(),previousTokenSecret:y,hostRegistry:{setHost:(k,U)=>a.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${k}`,U,String(En)),delHost:k=>a.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${k}`,u.selfAddress)}}),i=mn(L,{verifyToken:(k,U)=>We(k,U,u.tokenSecret,void 0,y),selfAddress:u.selfAddress,hostOf:async k=>{let U=await a.redis.get(`lane_hosts:${k}`);return U&&U.trim()!==""?U.trim():null},podToPodDial:(k,U,x)=>new Promise((W,G)=>{(async()=>{let j=await a.redis.get(`lane_tenant:${k}`),Pn=te(k,u.tokenSecret,void 0,void 0,j||void 0),On=`ws://${x}/stream/${encodeURIComponent(k)}/${encodeURIComponent(U)}?token=${encodeURIComponent(Pn)}`,$e=new Ao(On,Pe(U));$e.once("open",()=>W($e)),$e.once("error",G)})().catch(G)})});let R=a;T.push(async()=>{await s.close(),await i.close(),await R.registry.close(),R.redis.quit().catch(()=>{})})}L.on("upgrade",(u,y)=>{let R=new URL(u.url??"/","http://localhost");R.pathname===at||R.pathname===ut||R.pathname===ht||s!==null&&R.pathname.startsWith("/doc/")||i!==null&&R.pathname.startsWith("/stream/")||y.destroyed||(y.write(`HTTP/1.1 404 Not Found\r
|
|
20
|
+
Connection: close\r
|
|
21
|
+
\r
|
|
22
|
+
no WS route for ${R.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let $=async()=>{for(let u of T)await u();await m.detachAll()};return{server:L,metricsServer:Dt(o),metrics:o,edgeIdentityServer:Bt(),registry:l,closeAll:()=>l.closeAll(),closeWebSockets:$}}async function Ki(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await It()||At(),await e()}export{Bo as a,Ht as b,pe as c,Nn as d,$n as e,xn as f,Dn as g,Wn as h,he as i,ge as j,Dt as k,zo as l,Bn as m,Kn as n,Gn as o,jn as p,Wt as q,zn as r,qn as s,Vn as t,Bt as u,C as v,B as w,be as x,nr as y,rr as z,re as A,ar as B,Ke as C,ts as D,ns as E,wr as F,ve as G,Se as H,Xt as I,br as J,_e as K,ke as L,_r as M,kr as N,Ee as O,D as P,Tr as Q,Re as R,Oo as S,Uo as T,Bi as U,Ki as V};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as Q}from"./chunk-CAR4AEQJ.js";import{g as re,h as U,i as ae,j as de}from"./chunk-ZCF6EV4Y.js";import{c as J,f as D,g as X,p as z}from"./chunk-MOX5FG2R.js";import{a as ce,b as C}from"./chunk-MJSK6W3W.js";import{a as M}from"./chunk-FF3RWDFM.js";import{b as Y,c as Z,d as ee,g as ne,j as _,k as N,l as x,m as oe,p as te,q as b,r as se,s as ie}from"./chunk-J3KCHTSA.js";import{c as O}from"./chunk-YSFSRI3D.js";O();import{App as j,createClientToken as me,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ie,DEFAULT_WHEN_LIVE_TIMEOUT_MS as ge,isWakingPhase as Le,SessionFailedError as B}from"@urun-sh/core";O();import{SessionFailedError as Se}from"@urun-sh/core";var V=2;function Pe(n){let s=n?.type;return s==="response.created"||s==="response.in_progress"}function Ee(n){let s=n?.type;return s==="response.completed"||s==="error"}function le(n){return async function(a,p){let u=await n.sessionFor(a.model);return(async function*(){for(let d=1;d<=V;d++){let{app:w,entry:g,identity:S}=d===1?u:await n.sessionFor(a.model);p?.({sessionId:n.sessionIdOf?.(g)??null,identity:S});let i=!1,l=!1;try{let f=await n.createStream(g,a);for await(let m of f){if(Ee(m)&&(i=!0),Pe(m)){if(d>1)continue}else l=!0;yield m}}catch(f){if(f instanceof Se&&(f.kind==="never-live"||f.kind==="create-failed")){try{n.onAdmissionVerdict?.(w,g,f)}catch{}throw f}if(d<V&&!l){await n.evict(w,g);continue}throw f}if(i)return;if(d<V&&!l){await n.evict(w,g);continue}return}})()}}import{randomUUID as we}from"crypto";O();import{encodeStreamEnvelope as pe}from"@urun-sh/core";var ve="audio";function ue(n){let s=n.streamEndpoint(ve);return{sessionId:n.id,appendInputAudio(a,p){let u=Buffer.from(a,"base64");if(u.byteLength!==0){if(p===void 0){s.send(pe(new Uint8Array(u)));return}s.send(pe({pcm16:a,capture_wall_ms:p}))}},onOutputAudio(){return()=>{}}}}O();import{encodeStreamEnvelope as Ae}from"@urun-sh/core";var Oe="rt-video-in";function fe(n){let s=n.streamEndpoint(Oe);return{sendInputFrame:async a=>{s.send(Ae(a))}}}var _e=0,ke=4,Te=4;function sn(n,s){let a=(d,w)=>{let g=(n[d]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${d} must be a positive integer (got ${JSON.stringify(n[d])})`);return S},p=(n.URUN_DECISION_POOL_MIN??"").trim();if(p==="0")return null;let u=p?Number.parseInt(p,10):_e;if(!Number.isInteger(u)||u<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(n.URUN_DECISION_POOL_MIN)})`);let c=a("URUN_DECISION_POOL_MAX",Math.max(u,ke));return{min:u,max:c,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",Te),replicaId:(n.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function rn(n){let s=(n.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return U;let a=Number.parseInt(s,10);if(!Number.isInteger(a)||a<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(n.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function W(n,s,a,p){let u=n[a];if(typeof u!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let c=p?u(void 0,p):u();if(typeof c.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return c}function ye(n,s,a,p){let{baseUrl:u,orgId:c,auth:d}=n,w=s.fnName??n.fnName,g=n.sessionStartOptions?.(a),S=p||g||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...g,...p}:void 0,i=y=>({session:y,responses:new M(y),gone:ce(y,a)});if(d.lane==="jwt"){let y=j(s.appSlug,{baseUrl:u,orgId:c,jwt:d.jwt});return i(W(y,s.appSlug,w,S))}if(d.lane==="machine"||d.lane==="user"){let y=d.lane==="machine"?d.machineToken:d.userToken,{gatewayUrl:F}=d,I=(typeof n.subject=="function"?n.subject():n.subject)??we(),L=j(s.appSlug,{baseUrl:u,orgId:c,getAccessToken:async()=>(await me(y,{baseUrl:F,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:I,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(L,s.appSlug,w,S))}let{apiKey:l,gatewayUrl:f}=d,m=(typeof n.subject=="function"?n.subject():n.subject)??we(),h=j(s.appSlug,{baseUrl:u,orgId:c,getAccessToken:async()=>(await me(l,{baseUrl:f,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:m,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(h,s.appSlug,w,S))}function he(n){let s=n.session.id;if(typeof s!="string"||s.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return s}function q(n){if(n.kind==="never-live")return!0;if(n.kind!=="create-failed")return!1;let s=n.status.error?.httpStatus,a=n.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Fe=new Set(["error","paused"]);function an(n){let{auth:s,catalog:a}=n,p=null,u=(d,w)=>{let g=ye(n,d,w);return n.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&n.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{p?.evict(w,g)}),g},c=new ie({sharedOnlyListing:n.sharedOnlyListing===!0,defaultApp:n.defaultApp,fnName:n.fnName,openSession:u,closeSession:async d=>{if(d.gone.dispose(),d.audioDispose?.(),n.release==="detach"){if(typeof d.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');d.session.detach();return}await d.session.end()},listApps:s.lane==="api-key"?()=>oe({apiUrl:n.apiUrl,apiKey:s.apiKey}):null,listCatalog:n.catalogRows??(a?()=>Q(a):null),listPrices:a?()=>ee(a):null,shared:n.catalogRows?async()=>{let d=await n.catalogRows();return Y(d)}:s.lane==="api-key"?()=>Z({apiUrl:n.apiUrl,apiKey:s.apiKey}):null,sessionKey:he});return p=c,n.defaultApp!==null&&c.seed(n.defaultApp,u({appSlug:n.defaultApp},b({appSlug:n.defaultApp}))),c}function dn(n,s){let a=n.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let p=a.replicaId??"proxy",u=new Map,c=new Map,d=new Map,w=i=>{process.stderr.write(`[decision-pool] ${i}
|
|
2
|
+
`)},g=(i,l)=>{let f=u.get(l);if(f)return f;let m=new re({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:p,openSlot:async h=>{let y=ye(n,i,l,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>m.markSessionDead(y)),await T(y.session),w(`slot attached pool=${l} slot=${h.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async h=>{h.gone.dispose(),h.audioDispose?.(),await h.session.end()},onDetach:(h,y)=>w(`slot detached pool=${l} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof B&&q(h)});return c.set(l,{target:i,env:a}),u.set(l,m),m},S=async(i,l)=>{let f=c.get(l);if(f)try{let m=await s.poolTuningFor(i);g(i,l).retune({min:m?.min??f.env.min,max:m?.max??f.env.max,inFlightCap:m?.in_flight_cap??f.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){w(`pool tuning refresh failed pool=${l} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(n.defaultApp===null)return;let i={appSlug:n.defaultApp};await g(i,b(i)).boot()},async sessionFor(i){let l=await s.resolveTargetFor(i),f=b(l),m=g(l,f);await S(l,f);let h=await m.acquire({timeoutMs:m.requestWaitMs}),y=d.get(h.entry)??[];return y.push(h),d.set(h.entry,y),{app:f,entry:h.entry,identity:se(l)}},async warmFor(i){let l=await s.resolveTargetFor(i);await g(l,b(l)).boot()},end(i){let l=d.get(i)?.shift();l&&(d.get(i)?.length===0&&d.delete(i),l.release())},evict(i){for(let l of u.values())l.evict(i)},markSessionDead(i){for(let l of u.values())l.markSessionDead(i)},reap(){for(let[i,{target:l}]of c)S(l,i).then(()=>{let f=u.get(i);f&&f.reap()})},async pingReady(i){for(let l of u.values())if(await l.pingReady(i))return!0;return!1},stats(){return[...u.entries()].map(([i,l])=>({poolKey:i,...l.stats()}))},async drain(i){await Promise.all([...u.values()].map(l=>l.drain({timeoutMs:i})))},async close(){await Promise.all([...u.values()].map(i=>i.close()))}}}function Re(n){return Le(n?.name)?n?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?ge:Ie:ge}async function T(n,s){let a=n.whenLive;if(typeof a!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await a.call(n,{timeout:Re(n.phase),signal:s})}async function G(n){if(typeof n.cancel=="function")try{await n.cancel();return}catch{}if(typeof n.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");n.detach()}function k(n){return n.reason instanceof Error?n.reason:new Error("the client socket closed")}function cn(n,s=X,a,p,u=U,c){let d=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,i=new WeakMap,l=e=>{let o=e.session.id;return typeof o=="string"&&o.length>0?o:null},f="lane",m=e=>{let o=x(e);if(!c||!o||o.app!==f)return null;let t=c.entryFor(o.key);if(!t)throw new _(`the lane behind this handle (${o.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:o.key,entry:t}},h=async e=>m(e)?.entry??(await n.sessionForHandle(e)).entry,y=e=>{let o=d.get(e);if(!o){let t={waiting:0,gone:new AbortController};i.set(e,t),o=(async()=>{if(await T(e.session,t.gone.signal),t.gone.signal.aborted)throw k(t.gone.signal);i.get(e)===t&&i.delete(e);let r=await J(e.session,await s());return Object.assign(r,{sessionId:e.session.id})})(),d.set(e,o),o.then(r=>{d.get(e)===o&&(e.audioDispose=()=>r.dispose())},()=>{}),o.catch(()=>{d.get(e)===o&&d.delete(e)}),o.then(()=>{i.get(e)===t&&i.delete(e)},()=>{i.get(e)===t&&i.delete(e)})}return o},F=e=>{let o=S.get(e);return o||(o=(async()=>{let t=await y(e);return{appendInputAudio:(r,P)=>t.appendInputAudio(r,P),onOutputAudio:r=>t.onOutputAudio(r),sessionId:l(e)}})(),S.set(e,o),o.catch(()=>{S.get(e)===o&&S.delete(e)})),o},I=async(e,o,t)=>{if(t?.aborted){let E=i.get(e);throw(d.get(e)===void 0||E!==void 0&&E.waiting===0)&&await G(e.session),k(t)}let r=o(e),P=i.get(e);return P!==void 0&&P.waiting++,t===void 0?r:new Promise((E,v)=>{let A=()=>{P!==void 0&&--P.waiting===0&&i.get(e)===P&&(P.gone.abort(),i.delete(e),d.delete(e),S.delete(e),G(e.session).catch(()=>{})),v(k(t))};t.addEventListener("abort",A,{once:!0});let K=()=>t.removeEventListener("abort",A);r.then(R=>{K(),E(R)},R=>{K(),v(R)})})},L=async(e,o,t)=>{try{return await t}catch(r){throw(r instanceof _||r instanceof B&&q(r))&&(n.evict(e,o),r instanceof B&&a?.(e,r.kind==="never-live"?"never-live":"create-failed")),r}};return{createResponse:le({sessionFor:c?async e=>{let o=await n.resolveTargetFor(e);if(o.sharedApp){let t=await c.sessionFor(e,o);return{app:t.app,entry:t.entry,identity:t.identity}}return p?p.sessionFor(e):n.sessionFor(e)}:p?e=>p.sessionFor(e):e=>n.sessionFor(e),sessionIdOf:e=>l(e),evict:(e,o)=>{c&&c.owns(o)?c.evict(o):p?p.evict(o):n.evict(e,o)},onAdmissionVerdict:(e,o,t)=>{q(t)&&(c&&c.owns(o)?c.evict(o):p?p.markSessionDead(o):n.evict(e,o),a?.(e,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(e,o)=>{try{await T(e.session);let t=ae(C(await e.responses.responses.create(o),e.gone),u);if(!p&&!c)return t;let r=e;return(async function*(){try{yield*t}catch(E){throw de(E)&&(c&&c.owns(r)?c.evict(r):p&&(E instanceof _?p.markSessionDead(r):p.evict(r))),E}finally{c&&c.owns(r)?c.release(r):p?.end(r)}})()}catch(t){throw c&&c.owns(e)?c.release(e):p&&p.end(e),t}}}),listModels:()=>n.modelList(),openRouterModels:()=>n.openRouterModels(),supportsImages:(e,o)=>n.supportsImages(e,o),listImageModels:()=>n.imageModelList(),catalogIdentity:e=>n.catalogIdentityFor(e),servingAppSlug:async e=>await n.servingAppSlugFor(e),supportsAudio:e=>n.supportsAudio(e),supportsSpeech:e=>n.supportsSpeech(e),speechVoices:e=>n.speechVoices(e),supportsTranscription:e=>n.supportsTranscription(e),transcriptStreamFor:e=>n.transcriptStreamFor(e),listSpeechToTextModels:()=>n.speechToTextModelList(),openAudio:async(e,o)=>{let{app:t,entry:r}=await n.sessionFor(e);return await L(t,r,I(r,y,o))},openAudioOn:async(e,o,t,r)=>{let P=m(e);if(P){let A=P.entry.session;return ue(A)}let{app:E,entry:v}=await n.sessionForHandle(e);if(r&&v.session.phase?.name!=="live"){let A=v.session.phase?.name;r({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}return await L(E,v,I(v,F,o))},openTurnsOn:async function*(e,o){if(o?.aborted)throw k(o);let t=await h(e);yield*ne(t.session,o)},openVideoOn:async e=>{let o=m(e);if(o)return fe(o.entry.session);let{entry:t}=await n.sessionForHandle(e),r=w.get(t);return r||(r=D(t.session),w.set(t,r)),r},openVideo:async e=>{let{entry:o}=await n.sessionFor(e),t=w.get(o);return t||(t=D(o.session),w.set(o,t)),t},openVideoOut:async e=>{let{entry:o}=await n.sessionFor(e),t=g.get(o);return t||(t=z(o.session),g.set(o,t)),t},sessionHandle:async e=>{if(c){let o=await n.resolveTargetFor(e);if(o.sharedApp){let t=await c.sessionFor(e,o),r=l(t.entry);if(r===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return N(f,r)}}return(await n.handleFor(e)).handle},dedicatedSessionHandle:async e=>{if(!(await n.resolveTargetFor(e)).sharedApp)return(await n.handleFor(e)).handle;let{app:t,entry:r}=await n.dedicatedSessionFor(e);return N(t,he(r))},releaseSessionHandle:e=>{let o=x(e);if(!o)return;if(o.app.startsWith(te)){(async()=>{let r=null;try{r=(await n.sessionForHandle(e)).entry}catch{return}await G(r.session).catch(()=>{}),await n.evict(o.app,r)})();return}if(!c||o.app!==f)return;let t=c.entryFor(o.key);t&&c.release(t)},speechSessionHandle:async e=>(await n.speechHandleFor(e)).handle,evictSpeechSession:async e=>{let{app:o,entry:t}=await n.sessionForHandle(e);await n.evict(o,t)},createResponseOn:async(e,o,t)=>{let r=await h(e);await T(r.session);let P=t!==void 0&&m(e)?new M({...r.session,consumerId:t},{sessionTag:t}):r.responses;return C(await P.responses.create(o),r.gone)},onSessionEnd:async(e,o)=>{let t=m(e);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:r}=await n.sessionForHandle(e),P=r.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(v=>{if(E||!Fe.has(v.name))return;E=!0;let A=P.endsAt??null;o({timeLeftMs:A?Math.max(0,A.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{sn as a,rn as b,an as c,dn as d,cn as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as o}from"./chunk-YSFSRI3D.js";o();async function l(e,n,r){if(e.synced===!0||typeof e.onSynced!="function")return;let t;await new Promise((i,s)=>{let u=e.onSynced(()=>{clearTimeout(t),i()});t=setTimeout(()=>{u(),s(new Error(`[urun] llm doc plane never synced within ${n}ms \u2014 ${r} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},n)})}o();import{gcRequest as f}from"@urun-sh/core/internal";function d(e,n){let r=e.delete;if(typeof r=="function"){f({get:t=>e.get(t),delete:t=>r.call(e,t),on:(t,i)=>e.on(t,i)},n);return}e.set({requests:{[n]:null}})}export{l as a,d as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as m,b as _}from"./chunk-7DUSLXPG.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function f(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function y(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function k(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();i();var v="llm-resp";async function*h(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let c=typeof a.index=="number"?a.index:0,u=n.get(c)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(c,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${c}`,tool_index:c,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield k(r);return}}}async function*g(e,t){let o=`${v}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*h(t,e.stream(o).messages())}finally{try{_(e.doc("llm"),t)}catch{}}}i();var w=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=y(t,o,this.consumerId);return this.write(n),g(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=f(t,o,n,this.consumerId);return this.write(s),g(this.session,n)})}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{f as a,y as b,k as c,h as d,g as e,w as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as r}from"./chunk-
|
|
1
|
+
import{f as r}from"./chunk-BFIKVTQB.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(t,n){this.transport=new r(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=a(),i=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*i})(),{requestId:n})}}};export{o as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as x}from"./chunk-YSFSRI3D.js";x();import{createHmac as y,randomUUID as T,timingSafeEqual as _}from"crypto";var L=["sfu","urun-doc"],I="runtime:lease",A="lane:join",S="urun-runtime-key-v1";function p(r,t){if(!r)throw new Error("deriveOrgRuntimeKey requires a master secret");if(!t)throw new Error("deriveOrgRuntimeKey requires an orgId");return y("sha256",r).update(`${S}|${t}`).digest("base64url")}var k=120;function N(r){return Buffer.from(r).toString("base64url")}function D(r,t,s){let o=N(JSON.stringify(r)),e=N(JSON.stringify(t)),i=y("sha256",s).update(`${o}.${e}`).digest("base64url");return`${o}.${e}.${i}`}function J(r,t,s=k,o=A,e){let i=e?p(t,e):t;return $(r,i,s,o,e)}function $(r,t,s,o,e){let i=Math.floor(Date.now()/1e3);return D({alg:"HS256",typ:"JWT"},{session_id:r,aud:"sfu",sub:r,scope:o,...e?{tenant:e}:{},iat:i,exp:i+s,jti:T()},t)}function U(r,t,s,o=Math.floor(Date.now()/1e3),e){let i=r.split(".");if(i.length!==3)return null;let[m,h,O]=i,E,n;try{E=JSON.parse(Buffer.from(m,"base64url").toString()),n=JSON.parse(Buffer.from(h,"base64url").toString())}catch{return null}if(E.alg!=="HS256")return null;let d;try{d=Buffer.from(O,"base64url")}catch{return null}let f=typeof n.tenant=="string"&&n.tenant!==""?n.tenant:void 0,u=[];if(f!==void 0?(u.push(p(s,f)),e&&u.push(p(e,f))):(u.push(s),e&&u.push(e)),!u.some(g=>{let b=y("sha256",g).update(`${m}.${h}`).digest();return d.length===b.length&&_(d,b)}))return null;let l=n.exp;if(typeof l!="number"||l<=o)return null;let a=typeof n.aud=="string"||Array.isArray(n.aud)?n.aud:void 0;if(!(a!==void 0&&L.some(g=>g===a||Array.isArray(a)&&a.includes(g))))return null;let c=n.session_id??n.sub;return typeof c!="string"||c!==t?null:{sessionId:c,aud:a,scope:typeof n.scope=="string"?n.scope:void 0,tenant:f,app:typeof n.app=="string"?n.app:void 0,fn:typeof n.fn=="string"?n.fn:void 0,exp:l}}export{I as a,J as b,U as c};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{c as w}from"./chunk-YSFSRI3D.js";w();import{randomUUID as Ke}from"crypto";w();var p=class extends Error{},ve=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Re(n){if(typeof n!="string")return!1;let e=ve.exec(n);if(!e)return!1;let[,t,o,r,i,s,d]=e.map(Number);if(!Number.isFinite(Date.parse(n)))return!1;let a=new Date(Date.UTC(t,o-1,r,i,s,d));return a.getUTCFullYear()===t&&a.getUTCMonth()===o-1&&a.getUTCDate()===r&&a.getUTCHours()===i&&a.getUTCMinutes()===s&&a.getUTCSeconds()===d}function be(n){if(n===null||typeof n!="object")return null;let e=n.shared;if(e==null)return null;if(typeof e!="object")throw new p(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:t,endpoints:o,regions:r,compliance:i}=e;if(typeof t!="string"||t==="")throw new p(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(o))throw new p(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let s=o.map((d,a)=>{if(d===null||typeof d!="object")throw new p(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(d)}`);let l=d;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new p(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new p(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let u=(c,g)=>{if(l[c]!==void 0&&l[c]!==null&&!g)throw new p(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};u("ready",typeof l.ready=="boolean"),u("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),u("ready_since",Re(l.ready_since));for(let c of["model_id","variant"]){let g=l[c];if(g.includes(":"))throw new p(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(g)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return u("output_free",typeof l.output_free=="boolean"),l});if(r!=null&&(!Array.isArray(r)||!r.every(d=>typeof d=="string"&&d.length>0)))throw new p(`catalog "shared" block regions is malformed: ${JSON.stringify(r)}`);if(i!=null){let d=i;if(typeof i!="object"||typeof d.zdr!="boolean"||typeof d.hipaa!="boolean")throw new p(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let a of Object.keys(d))if(a!=="zdr"&&a!=="hipaa")throw new p(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return s.length===0?null:{shared_org_id:t,endpoints:s,...r!=null?{regions:r}:{},...i!=null?{compliance:i}:{}}}function S(n){return[...n.endpoints].sort((e,t)=>e.model_id.localeCompare(t.model_id)||e.variant.localeCompare(t.variant))}function Qe(n){let e=n.filter(r=>typeof r.shared_org_id=="string"&&r.shared_org_id!=="");if(e.length===0)return null;let t=e[0].shared_org_id,o=e.map((r,i)=>{let s=d=>new p(`catalog rows[${i}] (${r.model_id}:${r.variant}) shared row is malformed: ${d}`);if(r.shared_org_id!==t)throw s(`shared_org_id ${JSON.stringify(r.shared_org_id)} disagrees with ${JSON.stringify(t)}`);for(let d of["model_id","variant"]){let a=r[d];if(typeof a!="string"||a===""||a.includes(":"))throw s(`"${d}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof r.app_slug!="string"||r.app_slug==="")throw s("no app_slug");if(typeof r.function!="string"||r.function==="")throw s("no function");if(r.app_id!==void 0&&r.app_id!==null&&(typeof r.app_id!="string"||r.app_id===""))throw s(`malformed app_id ${JSON.stringify(r.app_id)}`);return{model_id:r.model_id,variant:r.variant,app_slug:r.app_slug,app_id:r.app_id??null,function:r.function,...r.gpu_spec?{gpu_spec:r.gpu_spec}:{},...r.warm!==void 0&&r.warm!==null?{warm:r.warm}:{},...r.compat_default===!0?{compat_default:!0}:{},...r.output_free===!0?{output_free:!0}:{},...r.ready!==void 0&&r.ready!==null?{ready:r.ready}:{},...r.ready_runtimes!==void 0&&r.ready_runtimes!==null?{ready_runtimes:r.ready_runtimes}:{},...r.ready_since?{ready_since:r.ready_since}:{}}});return{shared_org_id:t,endpoints:o}}function D(n,e,t){let o=(e??"").trim();if(o==="")return null;let r=o,i=t,s=o.lastIndexOf(":");s>0&&(r=o.slice(0,s),i=o.slice(s+1));let d=n.endpoints.filter(l=>l.model_id===r);if(d.length===0)return null;if(i!==void 0){let l=d.find(u=>u.variant===i);return l?{shared_org_id:n.shared_org_id,endpoint:l}:null}if(d.length===1)return{shared_org_id:n.shared_org_id,endpoint:d[0]};let a=d.filter(l=>l.compat_default===!0);if(a.length!==1)throw new p(`shared model "${r}" has ${a.length} compat_default rows (exactly one required) among variants ${d.map(l=>l.variant).join(", ")}`);return{shared_org_id:n.shared_org_id,endpoint:a[0]}}async function Xe(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/catalog`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new p(`catalog read failed: GET ${t} \u2192 ${o.status}`);return be(await o.json())}w();function h(n){return n.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}w();var _=class extends Error{name="ModelPriceError"},j="per_million_input_tokens",U="per_million_output_tokens",X="model_id,variant,unit,price_usd,effective_at,expires_at",Q={per_request:!0,per_minute:!0,per_output_unit:!0},Se=5e3;function $e(n,e){let t=typeof n=="number"?n:typeof n=="string"&&n.trim()!==""?Number(n):NaN;if(!Number.isFinite(t)||t<0)throw new _(`${e}: price_usd is not a non-negative number (${JSON.stringify(n)})`);return t}function Z(n,e,t){let o=typeof n=="string"?Date.parse(n):NaN;if(!Number.isFinite(o))throw new _(`${e}: ${t} is not a parseable timestamp (${JSON.stringify(n)})`);return o}function Te(n,e,t){return n===null?null:Z(n,e,t)}function ke(n,e){if(n===j)return"input";if(n===U)return"output";if(typeof n=="string"&&Object.hasOwn(Q,n))return null;throw new _(`${e}: unit ${JSON.stringify(n)} is neither a per-token rate (${j} | ${U}) nor a known GPU-time unit (${Object.keys(Q).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Pe(n,e){let t=n.reduce((r,i)=>i.effective_at>r.effective_at?i:r,n[0]),o=n.find(r=>r.effective_at===t.effective_at&&r.usd!==t.usd);return o?{reason:`two ${e} rates are effective at the same instant (${t.usd} and ${o.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:t}}function J(n,e){return`${n}\0${e}`}function xe(n){if(!Array.isArray(n))throw new _(`model_prices read is not an array: ${JSON.stringify(n)}`);let e=[];for(let t=0;t<n.length;t++){let o=n[t],r=`model_prices[${t}]`;if(o===null||typeof o!="object"||Array.isArray(o))throw new _(`${r} is not an object: ${JSON.stringify(o)}`);let i=o;for(let l of X.split(","))if(!Object.hasOwn(i,l))throw new _(`${r} has no "${l}" column: ${JSON.stringify(i)}`);let s=ke(i.unit,r);if(s===null)continue;let d=i.model_id;if(typeof d!="string"||d==="")throw new _(`${r} has no model_id (${JSON.stringify(i)})`);let a=i.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new _(`${r} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:d,variant:a,side:s,usd:$e(i.price_usd,r),effective_at:Z(i.effective_at,r,"effective_at"),expires_at:Te(i.expires_at,r,"expires_at")})}return e}function ee(n,e=Date.now(),t){let o=new Map,r=new Map;for(let a of n){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=o.get(a.model_id);l||(l=new Map,o.set(a.model_id,l),r.set(a.model_id,new Map));let u=a.variant??"",c=l.get(u);c||(c={input:[],output:[]},l.set(u,c),r.get(a.model_id).set(u,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let i=[],s=[];for(let[a,l]of o){let u=l.get(""),c=(g,f,v)=>{let m=g&&g.length>0?g:u?.[f];if(!m||m.length===0)return null;let y=Pe(m,f);return"reason"in y?y:y.rate.usd===0?f==="output"&&v!==null&&t?.has(J(a,v))?y.rate:{reason:`the ${f} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:y.rate};for(let[g,f]of r.get(a)){let v=l.get(g),m=c(v?.input,"input",f),y=c(v?.output,"output",f);if(m!==null&&"reason"in m){s.push({model_id:a,variant:f,reason:m.reason});continue}if(y!==null&&"reason"in y){s.push({model_id:a,variant:f,reason:y.reason});continue}m===null||y===null||i.push({model_id:a,variant:f,pricing:{input:m.usd,output:y.usd}})}}let d=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:i.sort(d),refusals:s.sort(d)}}function O(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===e);if(o)return o.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===null);return r?r.pricing:null}var E={prices:[],refusals:[]};async function rt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${X}&unit=in.(${t})`,{headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`},signal:AbortSignal.timeout(Se)});if(!o.ok)throw new Error(`model_prices fetch failed: ${o.status}`);return xe(await o.json())}w();var dt="/partners/openrouter/models",Ce={chat:!0,code:!0,agent:!0,vl:!0},te={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Oe(n){let e=n.toLowerCase();return Object.hasOwn(te,e)?te[e]:null}var ne={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Ee(n,e){if(!n||n.length===0)return[];let t=[],o=[];for(let r of n){let i=Object.hasOwn(ne,r)?ne[r]:null;if(i===null){o.push(r);continue}t.some(d=>d.region===r)||t.push({country_code:i,region:r})}return o.length>0&&e(`urun openrouter doc: shared block region(s) ${o.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),t}var re={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},oe={2:"Llama2",3:"Llama3"};function Ae(n){if(!n)return null;let e=n.split("@")[0],t=e.indexOf("/"),o=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<o.length;r+=1){let i=o[r];if(Object.hasOwn(re,i))return re[i];let s=o[r+1];if(i==="llama"&&s!==void 0&&Object.hasOwn(oe,s))return oe[s];if(i==="phi"&&s!==void 0&&/^\d/.test(s))return"Phi"}return null}var Ie=["context_length","max_model_len"];function Me(n){let e=Ie.map(t=>n.engine_args?.[t]).filter(t=>typeof t=="number"&&Number.isFinite(t)&&t>0);return e.length===0?null:e.every(t=>t===e[0])?e[0]:null}function N(n){let e=n.map(Me),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function Ne(n){let e=n.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function B(n){if(n.length===0)return null;let e=n.map(Ne),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function K(n,e){let t=e.filter(r=>r.serve_app_slug===n);return new Set(t.map(r=>r.model_id)).size===1?t:[]}function Fe(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return A(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return A(o);let r=K(n,e);return r.length>0?A(r):null}function A(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e:Le(n),matches:n}:null}function Le(n){let e=n[0],t=o=>n.every(r=>(r[o]??void 0)===(e[o]??void 0))?e[o]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),updated_at:t("updated_at")}}var $=class extends Error{name="ModelCreatedError"};function T(n){if(n.length===0)return 0;let e=`${n[0].model_id}:${n[0].variant}`,t=n.map(u=>u.created_at??void 0);if(t.some(u=>u===void 0))throw new $(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let o=t[0];if(!t.every(u=>u===o))throw new $(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(t)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(r===null)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let i=Number(r[1]),s=Number(r[2]),d=Number(r[3]),a=Date.UTC(i,s-1,d),l=new Date(a);if(l.getUTCFullYear()!==i||l.getUTCMonth()!==s-1||l.getUTCDate()!==d)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 not a real calendar date`);return a/1e3}function b(n){let e={id:n.id,object:n.object,created:n.created,owned_by:n.owned_by,...n.context_length!==void 0?{context_length:n.context_length}:{},...n.pricing!==void 0?{pricing:n.pricing}:{},...n.voices!==void 0?{voices:n.voices}:{},...n.capabilities!==void 0?{capabilities:n.capabilities}:{}};return"image_modes"in n?{...e,image_modes:n.image_modes}:e}function F(n,e,t){let o=Fe(n,e);if(!o)return b({id:n,object:"model",created:0,owned_by:"urun"});let{row:r,matches:i}=o,s=N(i),d=T(i),a=O(r.model_id,r.variant,t),l=ae(r,i),u=B(i);return b({id:n,object:"model",created:d,owned_by:"urun",...s!==null?{context_length:s}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...u!==null?{capabilities:{reasoning:u}}:{}})}var De=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function ae(n,e){if((n.task??void 0)!=="tts")return{published:[],defect:null};let t=e.map(i=>i.engine_args?.voices),o=t[0];if(Array.isArray(o)&&o.length>0&&o.every(i=>typeof i=="string")&&t.every(i=>Array.isArray(i)&&i.length===o.length&&i.every((s,d)=>s===o[d])))return{published:[...o],defect:null};let r=t.some(i=>i!=null)?`the catalog's engine_args.voices for ${n.model_id}:${n.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return n.model_id==="qwen3-tts-customvoice"?{published:[...De],defect:r}:{published:[],defect:r}}function z(n){let e=n.length>0?A(n):null;return e===null?{published:[],defect:null}:ae(e.row,e.matches)}function ie(n){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(n));if(!e)throw new Error(`unrenderable per-token price: ${String(n)}`);let[,t="",o="",r=""]=e,i=t+o,s=t.length-6+(r===""?0:Number(r));return(s<=0?`0.${"0".repeat(-s)}${i}`:`${i.slice(0,s)}.${i.slice(s).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function se(n){return{input:[{type:"prompt",unit:"token",cost_usd:ie(n.input)}],output:[{type:"completion",unit:"token",cost_usd:ie(n.output)}]}}function je(n,e,t,o){if(e.length===0)return null;let r=A(e);if(!r)return null;let{row:i,matches:s}=r;if(!i.task||Ce[i.task]!==!0)return null;let d=N(s),a=O(i.model_id,i.variant,t),l=Ae(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:T(s),quantization:Oe(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...a?{pricing:se(a).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...a?{pricing:se(a).output}:{}}],...o.datacenters.length>0?{datacenters:o.datacenters}:{},...o.compliance?{compliance:o.compliance}:{}}}function le(n,e,t,o){let r=o??(l=>console.warn(l.trimEnd())),i=n?S(n):[];if(i.length>0){let l=i.filter(u=>u.ready===void 0);if(l.length===i.length)r("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let u=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");r(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${u} carry no ready field and are declared not ready`)}}let s={datacenters:Ee(n?.regions,r),compliance:n?.compliance??null},d=[],a=new Set;for(let l of i){let u=`${l.model_id}:${l.variant}`;if(a.has(u))continue;a.add(u);let c=je(l,e.filter(g=>g.model_id===l.model_id&&g.variant===l.variant),t,s);c&&d.push(c)}return{data:d}}w();var de={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},k=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function ue(n){let e=n.t;if(typeof e!="string"||!(e in de))throw new k(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(de).join(", ")}`);let t={kind:e};return typeof n.delta=="string"&&(t.text=n.delta),typeof n.start_ms=="number"&&Number.isFinite(n.start_ms)&&(t.startMs=n.start_ms),t}function Ue(n){if(typeof n=="string"){let e;try{e=JSON.parse(n)}catch(t){throw new k(`the "stt" transcript lane delivered a string payload that is not valid JSON (${t instanceof Error?t.message:String(t)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new k(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return ue(e)}if(n===null||typeof n!="object"||Array.isArray(n))throw new k(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(n)?"array":typeof n}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return ue(n)}function ce(n){return n.reason instanceof Error?n.reason:new Error("the turn-lane consumer aborted")}async function Je(n,e){return e.aborted?"aborted":await new Promise(t=>{let o=!1,r=s=>{o||(o=!0,e.removeEventListener("abort",i),t(s))},i=()=>r("aborted");e.addEventListener("abort",i,{once:!0}),n.then(()=>r("pulled"),()=>r("pulled"))})}function pt(n,e){let t=n.stream("stt");if(typeof t.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*o(){let r=t.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw ce(e);let i=r.next();if(e!==void 0&&await Je(i,e)==="aborted")throw i.catch(()=>{}),ce(e);let s=await i;if(s.done)return;yield Ue(s.value)}}finally{let i=r.return?.();i&&i.catch(()=>{})}}return o()}var bt="https://api.urun.sh/v1",P=class extends Error{},M=class extends Error{},V="urs1.";function pe(n,e){return V+Buffer.from(JSON.stringify([n,e]),"utf8").toString("base64url")}function ge(n){if(!n.startsWith(V))return null;try{let e=JSON.parse(Buffer.from(n.slice(V.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function St(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/apps`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}function fe(n){if(n.length===0)return[];if(!n.every(t=>(t.task??void 0)==="image"))return[];let e=Ve(n);return e===null?[]:[e]}function ze(n){if(n==null)return null;if(typeof n!="object"||Array.isArray(n))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(n)}
|
|
2
|
+
`),null;let e={},t=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],o=!1;for(let[r,i]of t){let s=n[r];if(s==null)continue;let d=typeof s=="number"?s:typeof s=="string"?Number.parseInt(s,10):NaN;if(!Number.isInteger(d)||d<i){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(r)}=${JSON.stringify(s)})
|
|
3
|
+
`),o=!0;break}e[r]=d}return o||Object.keys(e).length===0?null:e}function He(n,e){if(n.length===0)return null;let t;return e.modelId&&(t=n.find(o=>o.model_id===e.modelId&&(!e.variant||o.variant===e.variant))),t||(t=n.find(o=>o.serve_app_slug===e.appSlug||h(`${o.model_id}-${o.variant}`)===e.appSlug||h(o.model_id)===e.appSlug)),t?ze(t.engine_args?.pool):null}function H(n,e,t,o,r){if(!r)throw new p(`shared model "${n}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||t===void 0)throw new p(`shared model "${n}" resolved without a catalog id + variant to join on`);let i=o.filter(s=>s.model_id===e&&s.variant===t);if(i.length===0)throw new p(`shared model "${n}" names endpoint ${e}:${t} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function he(n,e){if(!e.every(r=>(r.task??void 0)==="image"))return[];let t=e.map(r=>r.engine_args?.expects_image),o=t[0];if(typeof o!="boolean"||!t.every(r=>r===o))throw new p(`shared image model "${n}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(t)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[o===!1?"generation":"edit"]}var we="shared:",me="speech:",qe="realtime:";function q(n){return n.sharedApp?we+n.appSlug:n.appSlug}function G(n){return typeof n.modelId=="string"&&typeof n.variant=="string"?{kind:"catalog",model_id:n.modelId,variant:n.variant}:{kind:"not-a-catalog-model",model:n.appSlug}}function W(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return t;let o=e.filter(i=>h(i.model_id)===n);return new Set(o.map(i=>i.variant)).size===1?o:[]}function Ge(n){let e=n.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Ve(n){let e=n.map(Ge),t=e[0];return t!=null&&e.every(o=>o===t)?t:null}var We={stt:"stt",tts:"tts"};function R(n){if(n.length===0)return null;let e=n[0].task??void 0,t=n.every(r=>(r.task??void 0)===e),o=e===void 0?void 0:We[e];return o!==void 0?t?o:null:t&&n.every(r=>r.engine_args?.realtime===!0)?"decision":null}function _e(n,e){let t=W(n,e);return t.length>0?t:K(n,e)}function I(n,e){return _e(n.appSlug,e)}function Ye(n){let e=n.map(o=>o.engine_args?.transcript_stream).filter(o=>o!=null);if(e.length===0)return"stt";let t=e[0];if(typeof t!="string"||t.length===0||!e.every(o=>o===t))throw new p(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return t}var L=6e4,ye=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,t,o){let r=e.current;return r&&Date.now()-r.at<o?r.value:r?(r.refreshing||(r.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{r.refreshing=void 0}})()),r.value):(e.current={at:Date.now(),value:await t()},e.current.value)}seed(e,t){this.snapshotMintId(t),this.pool.set(e,Promise.resolve(t))}snapshotMintId(e){try{let t=this.keyOf(e),o=e;this.mintedIds.has(o)||this.mintedIds.set(o,t)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??L):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??L):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??L):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??L;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let t=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:t},t}async pricesForListing(e){let t;try{t=await this.priceRows()}catch(r){if(r instanceof _)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
4
|
+
`),E}let o=ee(t,Date.now(),e);for(let r of o.refusals)this.warn(`urun /v1/models: refusing to price ${r.model_id}:${r.variant??"*"} \u2014 ${r.reason}
|
|
5
|
+
`);return o}outputFreeKeys(e){let t=new Set;if(!e)return t;for(let o of e.endpoints)o.output_free===!0&&t.add(J(o.model_id,o.variant));return t}warn(e){(this.opts.warn??(o=>console.warn(o.trimEnd())))(e)}servable(e){return e.filter(t=>t.serves==="openai"&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=this.opts.defaultApp,t=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())r.startsWith(we)||r.startsWith(me)||t.add(r);let o=[...t].filter(r=>r!==e).sort();return e===null?o:[e,...o]}async noDefaultApp(e){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new P(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${o}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${o}`)}async sharedLane(e){if(!this.opts.shared)return null;let t=await this.sharedBlock();if(!t)return null;let o=D(t,e);if(o)return o;let r=e.lastIndexOf(":"),i=r>0?e.slice(0,r):e,s=r>0?e.slice(r+1):void 0,d=h(i),a=t.endpoints.filter(c=>h(c.model_id)===d&&(s===void 0||c.variant===s)),l=new Set(a.map(c=>c.model_id)),u=[...l][0];return u===void 0||l.size!==1?null:D(t,u,s)}async resolveTarget(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):{appSlug:o};let r=h(t);if(r===o)return{appSlug:o};let i=await this.sharedLane(t);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:i.shared_org_id,gpuSpec:i.endpoint.gpu_spec??void 0,appId:i.endpoint.app_id??void 0};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let s=await this.deployedApps(),d=this.servable(s);if(d.includes(r))return{appSlug:r};let a=d.filter(u=>u.startsWith(`${r}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=s.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(l)throw new P(`model "${t}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let d=(await this.opts.listCatalog()).find(a=>t===a.model_id||t===`${a.model_id}:${a.variant}`||r===h(a.model_id)||r===h(`${a.model_id}-${a.variant}`));if(d)throw new P(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${d.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):{appSlug:o}}async catalogIdentityFor(e){let t=G(await this.resolveTarget(e));return t.kind==="catalog"?{model_id:t.model_id,variant:t.variant}:null}async poolTuningFor(e){return He(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return q(await this.resolveTarget(e))}async sessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,q(t))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return G(await this.resolveTarget(e))}async speechSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,me+q(t))}async dedicatedSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,qe+Ke())}async evictHandle(e){let t=ge(e);if(!t)return;let o=this.pool.get(t.app);if(!o)return;let r=await o.then(i=>i,()=>null);r!==null&&await this.evict(t.app,r)}async acquire(e,t){let o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(e,t)),this.pool.set(t,o),o.then(r=>this.snapshotMintId(r),()=>{}),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o,identity:G(e)}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(e);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(e){let{app:t,entry:o}=await this.sessionFor(e);return{app:t,handle:pe(t,this.keyOf(o))}}async speechHandleFor(e){let{app:t,entry:o}=await this.speechSessionFor(e);return{app:t,handle:pe(t,this.keyOf(o))}}async sessionForHandle(e){let t=ge(e);if(!t)throw new M(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,i=this.pool.get(o),s=i?await i.then(d=>d,()=>null):null;if(s===null)throw new M(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(s)!==r&&this.mintedIds.get(s)!==r)throw new M(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:s}}async evict(e,t){let o=this.pool.get(e);!o||await o.then(i=>i,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[o,r]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=o.rows,s=o.ok?r:E;o.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
|
|
6
|
+
`);let a=(t?S(t):[]).map(l=>{let u=i.filter(Y=>Y.model_id===l.model_id&&Y.variant===l.variant),c=N(u),g=T(u),f=B(u),v=O(l.model_id,l.variant,s),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>F(l,i,s)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[t,o]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return le(e,t,o,r=>this.warn(r))}async supportsImages(e,t){let o=await this.resolveTarget(e),r=await this.catalogRows();if(o.sharedApp){let i=H(String(e),o.modelId,o.variant,r,this.opts.listCatalog!==null);return he(`${o.modelId}:${o.variant}`,i).includes(t)}return fe(W(o.appSlug,r)).includes(t)}async supportsAudio(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))!==null:R(I(t,o))!==null}async supportsSpeech(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="tts":R(I(t,o))==="tts"}async supportsTranscription(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="stt":R(I(t,o))==="stt"}async transcriptStreamFor(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):I(t,o);return Ye(r)}async speechVoices(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):I(t,o);return z(r)}async imageModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds()){let s=fe(W(i,e));s.length!==0&&o.push(b({...F(i,e,t),image_modes:s}))}let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),d=he(`${i.model_id}:${i.variant}`,s);if(d.length===0)continue;let a=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(s),owned_by:"urun",image_modes:d});o.push(a)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds())R(_e(i,e))==="stt"&&o.push(F(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(s)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(s),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,Qe as b,Xe as c,rt as d,dt as e,$ as f,pt as g,bt as h,P as i,M as j,pe as k,ge as l,St as m,He as n,me as o,qe as p,q,G as r,ye as s};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as I,o as A}from"./chunk-
|
|
1
|
+
import{a as I,o as A}from"./chunk-MOX5FG2R.js";import{c as v}from"./chunk-YSFSRI3D.js";v();var J="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",k=1007,F=1008,R=1011,V=1008,n=class extends Error{constructor(o,i=k){super(o);this.closeCode=i}closeCode},d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,w=["setup","clientContent","realtimeInput","toolResponse"];function B(e){let t;try{t=JSON.parse(e)}catch{throw new n("client message is not valid JSON")}let o=d(t);if(!o)throw new n("client message must be a JSON object");let i=w.filter(c=>o[c]!==void 0),s=Object.keys(o).filter(c=>!w.includes(c));if(s.length>0)throw new n(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${w.join(", ")}`);if(i.length!==1)throw new n(`client message must contain exactly one of ${w.join(", ")} (got ${i.length})`);let r=i[0],a=d(o[r]);if(!a)throw new n(`"${r}" must be a JSON object`);return{kind:r,[r]:a}}function C(e,t){if(typeof e=="string")return e;let o=d(e),i=o?o.parts:void 0;if(!Array.isArray(i))throw new n(`${t}: expected a Content with a parts array`);let s=[];for(let r of i){let a=d(r);if(a&&typeof a.text=="string"){s.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new n(`${t}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):a&&(a.functionCall!==void 0||a.functionResponse!==void 0)?new n(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new n(`${t}: unsupported part ${JSON.stringify(r)}`)}return s.join(`
|
|
2
2
|
`)}var _={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},h="urun.videoOut";function G(e){return{framing:A,codec:e}}function Y(e){let{seq:t,ptsUs:o,codec:i,key:s}=e.header;return{[h]:{v:1,seq:t,ptsUs:o,codec:i,key:s,data:Buffer.from(e.au).toString("base64")}}}var x={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},S=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",h],T=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function E(e){let t=d(e);if(!t)throw new n("setup.realtimeInputConfig must be an object");for(let s of Object.keys(t))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new n(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let o=d(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!o)throw new n("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(o??{}))if(s!=="disabled")throw new n(`automaticActivityDetection.${s} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(o?.disabled!==!0)throw new n("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let i="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!T.includes(t.activityHandling))throw new n(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${T.join(", ")}`);i=t.activityHandling}return{manualActivity:!0,activityHandling:i}}var N=["temperature","maxOutputTokens","responseModalities"];function K(e){for(let[u,f]of Object.entries(x))if(e[u]!==void 0)throw new n(f);for(let u of Object.keys(e))if(!S.includes(u))throw new n(`unsupported setup field "${u}"`);if(typeof e.model!="string"||e.model.length===0)throw new n('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),o,i,s=!1,r=d(e.generationConfig);if(e.generationConfig!==void 0&&!r)throw new n("setup.generationConfig must be an object");if(r){for(let u of Object.keys(r))if(!N.includes(u))throw new n(`unsupported generationConfig field "${u}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new n("generationConfig.temperature must be a number");o=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new n("generationConfig.maxOutputTokens must be a number");i=r.maxOutputTokens}if(r.responseModalities!==void 0){let u=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let f of u){let y=String(f).toUpperCase();if(y==="AUDIO"){s=!0;continue}if(y!=="TEXT")throw new n(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let a=[];e.systemInstruction!==void 0&&a.push({role:"system",content:C(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new n("setup.tools must be an array");c=[];for(let u of e.tools){let f=d(u);if(!f)throw new n("setup.tools entries must be objects");for(let y of Object.keys(f))if(y!=="functionDeclarations")throw new n(`unsupported tool "${y}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new n("tool.functionDeclarations must be an array");for(let y of f.functionDeclarations){let g=d(y);if(!g||typeof g.name!="string")throw new n("functionDeclarations entries require a string name");c.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}c.length===0&&(c=void 0)}let m={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let u=d(e.sessionResumption);if(!u)throw new n("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(u))if(f!=="handle")throw new n(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(u.handle!==void 0&&(typeof u.handle!="string"||u.handle.length===0))throw new n("sessionResumption.handle must be a non-empty string when present");m={enabled:!0,handle:typeof u.handle=="string"?u.handle:null}}let p=e.realtimeInputConfig===void 0?_:E(e.realtimeInputConfig),l=!1;if(e[h]!==void 0){if(!d(e[h]))throw new n(`setup["${h}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:a,tools:c,temperature:o,maxOutputTokens:i,audioModality:s,activity:p,sessionResumption:m,videoOut:l}}function q(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function W(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function X(e){for(let i of Object.keys(e))if(i!=="turns"&&i!=="turnComplete")throw new n(`unsupported clientContent field "${i}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new n("clientContent.turns must be an array");let o=[];for(let i of t){let s=d(i);if(!s)throw new n("clientContent.turns entries must be Content objects");let r=s.role===void 0?"user":String(s.role).toLowerCase();if(r!=="user"&&r!=="model")throw new n(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);o.push({role:r==="model"?"assistant":"user",content:C(s,"clientContent.turns")})}return{items:o,turnComplete:e.turnComplete===!0}}var b=16e3,O=24e3,$=`audio/pcm;rate=${O}`,z=Buffer.alloc(960).toString("base64");function j(e,t,o){if(t===o)return e;let i=Math.floor(e.length*o/t),s=new Int16Array(i),r=t/o,a=e.length-1;for(let c=0;c<i;c++){let m=c*r,p=Math.floor(m);if(p>=a){s[c]=e[a];continue}let l=m-p;s[c]=Math.round(e[p]+(e[p+1]-e[p])*l)}return s}function U(e){let t=d(e);if(!t)throw new n("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new n(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(t.mimeType)}`);if(typeof t.data!="string"||t.data.length===0)throw new n("realtimeInput.video.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length<3||o[0]!==255||o[1]!==216)throw new n("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(o)}function D(e){let t=d(e);if(!t)throw new n("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new n(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let o=/;\s*rate=(\d+)/.exec(t.mimeType);if(o&&Number(o[1])!==b)throw new n(`realtimeInput.audio.mimeType declares rate=${o[1]} \u2014 the Live spec input format is ${b} Hz (audio/pcm;rate=${b})`);if(typeof t.data!="string"||t.data.length===0)throw new n("realtimeInput.audio.data must be non-empty base64");let i=Buffer.from(t.data,"base64");if(i.length===0||i.length%2!==0)throw new n(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${i.length} bytes \u2014 not even)`);let s=new Int16Array(i.length/2);for(let a=0;a<s.length;a++)s[a]=i.readInt16LE(a*2);let r=j(s,b,O);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}function Q(e){if(e.mediaChunks!==void 0)throw new n('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new n("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=e.activityStart!==void 0?"activityStart":"activityEnd",r=d(e[s]);if(!r||Object.keys(r).length!==0)throw new n(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let t=["text","audio","audioStreamEnd","video"];for(let i of Object.keys(e))if(!t.includes(i))throw new n(`unsupported realtimeInput field "${i}"`);let o=t.filter(i=>e[i]!==void 0);if(o.length!==1)throw new n(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${o.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:D(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:U(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new n("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new n("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function Z(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new n(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new n("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let o=d(t);if(!o||typeof o.id!="string"||o.id.length===0)throw new n("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:o.id,output:JSON.stringify(o.response??null)}})}function ee(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function te(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:$,data:e}}]}}}}function ne(e){let t=d(e)??{},o=Array.isArray(t.output)?t.output:[],i=[],s=[],r=typeof t.output_text=="string"?t.output_text:"";if(!r)for(let p of o){let l=d(p);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let u of l.content){let f=d(u);f?.type==="output_text"&&typeof f.text=="string"&&(r+=f.text)}}r&&s.push({role:"assistant",content:r});for(let p of o){let l=d(p);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new n(`upstream function_call item is missing call_id/name: ${JSON.stringify(p)}`,R);let u=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",f;try{f=JSON.parse(u)}catch{throw new n(`upstream function_call arguments are not valid JSON: ${u}`,R)}i.push({id:l.call_id,name:l.name,args:f}),s.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:u})}let a=[];i.length>0&&a.push({toolCall:{functionCalls:i}}),a.push({serverContent:{generationComplete:!0}});let c=d(t.usage),m={serverContent:{turnComplete:!0}};if(c){let p={};typeof c.input_tokens=="number"&&(p.promptTokenCount=c.input_tokens),typeof c.output_tokens=="number"&&(p.responseTokenCount=c.output_tokens),typeof c.total_tokens=="number"&&(p.totalTokenCount=c.total_tokens),Object.keys(p).length>0&&(m.usageMetadata=p)}return a.push(m),{messages:a,assistantItems:s}}export{J as a,k as b,F as c,R as d,V as e,n as f,B as g,h,G as i,Y as j,K as k,q as l,W as m,X as n,b as o,O as p,$ as q,z as r,j as s,Q as t,Z as u,ee as v,te as w,ne as x};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as d}from"./chunk-
|
|
1
|
+
import{j as d}from"./chunk-J3KCHTSA.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as m}from"./chunk-YSFSRI3D.js";m();var M=24e3,v="audio",w=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),i=Math.floor(r.byteLength/2),a=new Int16Array(i);for(let s=0;s<i;s++)a[s]=r.readInt16LE(s*2);this.source.onData(a),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let i of this.outHandlers)i(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function N(t,e,n=1e4){try{return await I(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function I(t,e,n){let r=new w(e,{sampleRate:24e3}),i=await r.startOutbound(),a=t.stream(v);await a.attach(i),typeof a.emit=="function"&&r.setDataEmit(u=>a.emit(u));let s=await L(t,n);return await r.startInbound(s),r}function L(t,e){let n=t.stream(v);return n.track!=null?Promise.resolve(n.track):new Promise((r,i)=>{let a,s=setTimeout(()=>{a?.(),i(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=o=>{o!=null&&(clearTimeout(s),a?.(),r(o))};a=n.on?.("track",u),n.track!=null&&u(n.track)})}var b="rt-video-in",k=256e3;function q(t){let e=t.stream(b),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${b}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>k)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${k}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var U=24e3,f=480,_=111,x=50,h=null;async function P(){if(h)return;let t=await import("opusscript");h=t.default??t}function B(){if(!h)throw new Error("[opus-guard] opusscript module not loaded");return new h(U,1,2048)}var g=class{constructor(e=B){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=x}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let i=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,i}catch(i){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${i instanceof Error?i.message:String(i)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function J(){let t=await import("werift");await P();let e=new g;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,i=Math.random()*65535&65535,a=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:n,onData:u=>{let o=new Int16Array(s.length+u.length);o.set(s,0),o.set(u,s.length);let d=0;for(;o.length-d>=f;){let c=o.subarray(d,d+f);d+=f;let l=Buffer.from(c.buffer,c.byteOffset,c.byteLength),y=e.encode(l,f);if(y===null){s=o.slice(d);break}i=i+1&65535,a=a+f>>>0;let A=new t.RtpHeader({version:2,payloadType:_,sequenceNumber:i,timestamp:a,ssrc:r,marker:!1}),R=new t.RtpPacket(A,y);n.writeRtp(R)}s=o.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(a=>{let s;try{s=e.decode(a.payload)}catch(o){if(e.wedged)throw o;return}let u=new Int16Array(s.length/2);for(let o=0;o<u.length;o++)u[o]=s.readInt16LE(o*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function Y(){let t=await import("@roamhq/wrtc");return{createSource:()=>{let e=new t.nonstandard.RTCAudioSource;return{track:e.createTrack(),onData:r=>e.onData({samples:r,sampleRate:24e3})}},createSink:e=>{let n={onframe:null},r=new t.nonstandard.RTCAudioSink(e);return r.ondata=i=>{n.onframe?.(i)},n}}}m();import{WtControlDecoder as D,consumeWtDataStreams as F,encodeWtControlFrame as W,STREAM_END as C}from"@urun-sh/core";var p="rt-video-out",$="urun.videoOut.v1",E="h264";function O(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function z(t,e){if(O(t,"encodeVideoOutRecord"),e.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:t.seq,ptsUs:t.ptsUs,codec:t.codec,key:t.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let r=new Uint8Array(2+n.byteLength+e.byteLength);return r[0]=n.byteLength&255,r[1]=n.byteLength>>8,r.set(n,2),r.set(e,2+n.byteLength),r}function S(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let i=r;O(i,"decodeVideoOutRecord");let a=t.subarray(2+e);if(a.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:i,au:a.slice()}}async function K(t){let e=t.wtDataEndpoint;if(typeof e!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await e.call(t),r=n.sessionId??t.sessionId;if(typeof r!="string"||r.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:r,stream:p,codec:E,framing:$}}var X="urun.videoOut.v2-ws";function Z(t){let e=t.stream(p);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${p}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,i=new Set,a=o=>{for(let d of r)d(o)},s=!1,u=async()=>{for await(let o of e.messages()){if(!(o instanceof Uint8Array)){a(new Error(`openSessionVideoOutLane: "${p}" delivered a non-BINARY \xA75 payload (${typeof o}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=S(o)}catch(c){a(c instanceof Error?c:new Error(String(c)));continue}for(let c of n)c(d)}for(let o of i)o()};return{codec:E,onOutputFrame:o=>(n.add(o),s||(s=!0,u().catch(d=>a(d instanceof Error?d:new Error(String(d))))),()=>n.delete(o)),onLaneError:o=>(r.add(o),()=>r.delete(o)),onEnd:o=>(i.add(o),()=>i.delete(o))}}function H(t){if(t.length%2!==0||/[^0-9a-fA-F]/.test(t))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(t)})`);let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}async function ee(t,e,n){let r=n??(typeof globalThis.WebTransport=="function"?(d,c)=>new globalThis.WebTransport(d,c):void 0);if(!r)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let i=r(t.url,{serverCertificateHashes:t.certHashes.map(d=>({algorithm:"sha-256",value:H(d)}))});await i.ready;let a=await i.createBidirectionalStream();await a.writable.getWriter().write(W({t:"hello",token:t.token,sessionId:t.sessionId}));let s=a.readable.getReader(),u=new D,o=!1;for(;!o;){let{value:d,done:c}=await s.read();if(c)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let l of u.push(d)){if(l.t==="hello-ack"){o=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(l.t)} before hello-ack)`)}}await F(i.incomingUnidirectionalStreams,{onData:(d,c)=>{if(d===t.stream){if(c===C){e.onEnd?.();return}if(!(c instanceof Uint8Array)){e.onLaneError(new Error(`consumeVideoOut: "${t.stream}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{e.onFrame(S(c))}catch(l){e.onLaneError(l instanceof Error?l:new Error(String(l)))}}},onLaneError:d=>e.onLaneError(d)})}export{M as a,w as b,N as c,b as d,k as e,q as f,J as g,Y as h,p as i,$ as j,E as k,z as l,S as m,K as n,X as o,Z as p,ee as q};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var E=3e4;var N=1e3,B=12e4;function M(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(d=>{t=setTimeout(d,Math.max(0,s))})])}finally{clearTimeout(t)}}function z(n){let s=n.now??Date.now,t=new Map,d=new Map,w=new Map,c=new Map,h=new Map,_=new Map,L=new Map,m=new Set,y=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??A(e),t.set(e,a)),a},A=e=>{let a=n.redis,g=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async f=>{let o=(await g.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,l)=>r.timestamp-l.timestamp);if(o.length===0)return{found:0};for(let r of o)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:f})}catch{}for(let r of o.slice(1))try{await r.remove()}catch{}return{found:o.length}},close:()=>g.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),g=[],f=new Map;for(let[r,l]of Object.entries(a)){let i=M(l);i&&i.proxy_url===n.docHostUrl&&(g.push(r),f.set(r,i.region))}if(g.length===0)return[];let p=await n.redis.mget(...g.map(r=>`lane_hosts:${r}`)),o=[];return g.forEach((r,l)=>{let i=p[l];i&&o.push({laneId:r,host:i,region:f.get(r)})}),o},v=async(e,a,g,f,p)=>{let o=g,r=f,l=p;if(typeof o!="string"||o===""||typeof r!="string"||r===""){let S=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(S)o=S.app,r=S.fn,l=S.sharedApp??l;else{let T=w.get(e)??0;if(s()-T<E)return;throw w.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let i=d.get(e)??0,b=s();if(b-i<E)return;if(d.set(e,b),(await y(e).reassertWaiting(s()).catch(S=>{throw d.delete(e),S})).found>0){h.set(a??"",(h.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,D=await n.admission.createLaneSession({pool:e,app:o,fn:r,...l?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(D.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${D.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);c.set(a??"",(c.get(a??"")??0)+1),L.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:g,sharedApp:f,model:p,holdMs:o=0}){m.add(e);let r=async()=>{try{await v(e,p,a,g,f)}catch(u){let R=u instanceof Error?u.message:String(u),x=u instanceof P?"identity":"admission";_.set(x,(_.get(x)??0)+1),L.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:p,reason:R})}},l=async()=>{try{return await k(e)}catch{return[]}},i=await l();if(i.length>0){let u=n.laneMinFor?.(e)??0;return u>i.length&&(async()=>{for(let R=i.length;R<u;R++)await r()})(),i}let b=s()+o;for(await O(r(),o);s()<b;){if(await new Promise(u=>setTimeout(u,N)),i=await l(),i.length>0)return i;await O(r(),b-s())}return[]},async status(){let e=[...m].sort();return Promise.all(e.map(async a=>{let g=[];try{let f=await n.redis.hgetall(`lanes:${a}`),p=Object.keys(f),o=p.length===0?[]:await n.redis.mget(...p.map(l=>`lane_hosts:${l}`)),r=s();g=p.map((l,i)=>{let b=f[l],u=b===void 0?null:M(b);return{laneId:l,occupantId:u?.occupant_id??"",capacity:u?.capacity??0,heartbeatAgeMs:u===null?null:r-u.heartbeat_ms,advertisedHere:u?.proxy_url===n.docHostUrl,hosted:!!o[i]}})}catch{}return{pool:a,lanes:g,lastDemandAt:d.get(a)??null}}))},demandCounters(){return[...new Set([...c.keys(),...h.keys()])].sort().map(a=>({model:a,enqueued:c.get(a)??0,reaffirmed:h.get(a)??0}))},demandRefusals(){return[..._.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return L.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var V=4e3,q=5e3;function j(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(V)})}function G(n){return{createLaneSession:async({pool:s,app:t,fn:d,sharedApp:w,laneId:c,laneHostUrl:h})=>{let _=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${d}`],bindPrincipal:!0,...w?{sharedApp:!0}:{},fetch:j(n.fetch??globalThis.fetch)}),L=n.fetch??globalThis.fetch,m;try{m=await L(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(q),headers:{"content-type":"application/json",authorization:`Bearer ${_.token}`,"x-tenant-id":_.orgId},body:JSON.stringify({app:t,function:d,...w?{shared_app:!0}:{},logical_id:c,idempotency_key:c,concurrency_key:c,lane_host_url:h})})}catch(k){throw new Error(`session-api lane admission for ${c} (app ${t}/${d}) failed: ${k instanceof Error?k.message:String(k)}`)}let y={};try{y=await m.json()}catch{}let A=y.session_id;if(m.status!==200||y.status!=="allocated"||typeof A!="string"){let k=typeof y.message=="string"?y.message:`HTTP ${m.status}`;throw new Error(`session-api lane admission refused for ${c} (app ${t}/${d}): ${k}`)}return{sessionId:A}}}}C();var Q="urun:catalog:v1";function Z(n){let s=n.refreshMs??5e3,t=n.now??Date.now,d=null,w=0,c=null,h=async()=>{let L=await n.redis.hgetall(Q),m=[];for(let y of Object.values(L))try{m.push(JSON.parse(y))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
2
|
+
`)}return d=m,w=t(),m},_=()=>d===null||t()-w>=s;return{rows(){return _()?(c||(c=h().finally(()=>{c=null})),c):Promise.resolve(d)},close(){d=null,c=null}}}export{B as a,z as b,G as c,Q as d,Z as e};
|