@urun-sh/openai 0.6.55 → 0.6.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{a as Me,b as Ct,c as xt,e as De,f as Mt,g as He}from"./chunk-HLSJAQHY.js";import{A as Ot,B as Tt,C as Pt,D as Ut,E as Nt,b as ct,d as dt,i as ht,j as pt,l as mt,m as yt,n as wt,o as bt,p as vt,q as _t,r as St,t as kt,u as de,v as Et,w as Rt,x as Lt,y as It,z as At}from"./chunk-PPEND4SP.js";import{a as lt}from"./chunk-KV3UXLNF.js";import{a as Ht,e as Wt}from"./chunk-BVM4ZQ2Y.js";import{a as $t}from"./chunk-KNWFUWXY.js";import{a as ut,b as le,c as ft,o as gt,p as ce}from"./chunk-Z74YK7AL.js";import{a as Dt,c as te,e as We}from"./chunk-XNRPTMSL.js";import{a as ot}from"./chunk-526ZJAOW.js";import{e as it,j as ie,p as at,q as ae,r as xe}from"./chunk-N3Y2GDQK.js";import{c as T}from"./chunk-YSFSRI3D.js";T();import{Counter as J,Gauge as ue,Histogram as fe,Registry as Un,collectDefaultMetrics as Nn}from"@prometheus-io/client";import{createServer as Cn}from"http";var Ds=9464,Ft="/metrics",he="(other)",$n="(none)",xn=64,Mn=128,Dn=["/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",kt,Rt,it],Hn=new Set(Dn);function Wn(t){return Hn.has(t)?t:he}function Fn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?$n:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,he):(this.admitted.add(e),e):he}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ge=class{registry=new Un;modelLabel=new pe(xn);orgLabel=new pe(Mn);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 Lt)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"},It()),this.ledgerQueue.set({measure:"oldest_age_seconds"},At()/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&&Nn({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=Wn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),a=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?he:e.method,status_class:Fn(e.status),stream:l,model:o,org:a}),this.duration.observe({lane:n,stream:l,model:o,org:a},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:a},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Gt(t){return Cn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ft){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ft}
1
+ import{a as Me,b as Ct,c as xt,e as De,f as Mt,g as He}from"./chunk-HIM6EB3J.js";import{A as Ot,B as Tt,C as Pt,D as Ut,E as Nt,b as ct,d as dt,i as ht,j as pt,l as mt,m as yt,n as wt,o as bt,p as vt,q as _t,r as St,t as kt,u as de,v as Et,w as Rt,x as Lt,y as It,z as At}from"./chunk-RONITPWW.js";import{a as lt}from"./chunk-KV3UXLNF.js";import{a as Ht,e as Wt}from"./chunk-2VZR5MAX.js";import{a as $t}from"./chunk-EA3GQ2MM.js";import{a as ut,b as le,c as ft,o as gt,p as ce}from"./chunk-O3Z5AY5E.js";import{a as Dt,c as te,e as We}from"./chunk-XNRPTMSL.js";import{a as ot}from"./chunk-526ZJAOW.js";import{e as it,j as ie,p as at,q as ae,r as xe}from"./chunk-4GW343S5.js";import{c as T}from"./chunk-YSFSRI3D.js";T();import{Counter as J,Gauge as ue,Histogram as fe,Registry as Un,collectDefaultMetrics as Nn}from"@prometheus-io/client";import{createServer as Cn}from"http";var Ds=9464,Ft="/metrics",he="(other)",$n="(none)",xn=64,Mn=128,Dn=["/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",kt,Rt,it],Hn=new Set(Dn);function Wn(t){return Hn.has(t)?t:he}function Fn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?$n:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,he):(this.admitted.add(e),e):he}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ge=class{registry=new Un;modelLabel=new pe(xn);orgLabel=new pe(Mn);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 Lt)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"},It()),this.ledgerQueue.set({measure:"oldest_age_seconds"},At()/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&&Nn({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=Wn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),a=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?he:e.method,status_class:Fn(e.status),stream:l,model:o,org:a}),this.duration.observe({lane:n,stream:l,model:o,org:a},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:a},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Gt(t){return Cn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ft){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ft}
2
2
  `);return}let s=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(s)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
3
3
  `);return}n.end()})})}T();import{createHash as Kt}from"crypto";import{createServer as Gn}from"http";var Bs=9465,Bn="x-urun-key-id",Kn="x-urun-key-fingerprint",jn="urun-ratelimit-bucket:",Jn="urun-ratelimit-tier:",Bt="anonymous",zn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function qn(t){return Kt("sha256").update(`${jn}${t}`).digest("hex")}function Vn(t){return Kt("sha256").update(`${Jn}${t}`).digest("hex")}function Yn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return zn.test(n)?n:null}function jt(){return Gn((t,e)=>{let n=Yn(t.headers.authorization);e.setHeader(Bn,n===null?Bt:qn(n)),e.setHeader(Kn,n===null?Bt:Vn(n)),e.writeHead(200),e.end()})}T();import{createClientToken as Qn,ClientTokenError as Jt}from"@urun-sh/core";import{createPublicKey as Xn,verify as Zn}from"crypto";var zt="urun-session-gateway",er="machine",tr=3e5;function Yt(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var N=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},q=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},G=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 N("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 N("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var nr=60,rr=6e4,sr=4096;function or(t){return t===401||t===403}var re=class{constructor(e){this.opts=e;this.mint=e.mint??Qn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new N("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<rr)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let s,o;try{let a=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:nr});s=a.orgId,o={...a.billingAudience!==void 0?{billingAudience:a.billingAudience}:{},...a.creditsAdmissionOk!==void 0?{creditsAdmissionOk:a.creditsAdmissionOk}:{},...a.creditsRefusalReason!==void 0?{creditsRefusalReason:a.creditsRefusalReason}:{}}}catch(a){throw a instanceof Jt&&a.status===402?(this.cache.delete(e),new q(a.code==="spend_cap_reached"||a.code==="insufficient_credits"?a.code:void 0)):a instanceof Jt&&or(a.status)?(this.cache.delete(e),new N(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 G(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${a instanceof Error?a.message:String(a)}`)}if(!s)throw new G(`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>=sr){let a=this.cache.keys().next();a.done||this.cache.delete(a.value)}return this.cache.set(e,{orgId:s,at:this.now(),...o}),{apiKey:e,orgId:s,credential:n,...o}}clear(){this.cache.clear()}};function ne(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function qt(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var me=class{constructor(e,n,r,s){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=s}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof G?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<tr)return r.keys;let s=this.inFlight.get(e);if(s!==void 0)return s;let o=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,o);let a=await o;return this.entries.set(e,{keys:a,at:this.now()}),a}async keyFor(e,n){let r=await this.keys(e,!1),s=n===""?void 0:r.find(o=>o.kid===n&&qt(o));return s===void 0&&(r=await this.keys(e,!0),s=n===""?void 0:r.find(o=>o.kid===n&&qt(o))),s}};function Qt(t,e,n){try{let r=Xn({key:n,format:"jwk"});return Zn("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 G("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new N("malformed machine token");let o,a;try{o=ne(n),a=ne(r)}catch{throw new N("malformed machine token")}if(o.alg!=="RS256")throw new N(`machine token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new N(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(a.aud!==zt)throw new N(`machine token audience must be ${zt} (got ${JSON.stringify(a.aud??null)})`);if(a.token_use!==er)throw new N(`bearer is a ${JSON.stringify(String(a.token_use??""))} token, not a machine token`);let h=typeof a.org_id=="string"?a.org_id:"";if(h==="")throw new N("machine token carries no org_id \u2014 no tenancy to route by");let f=typeof a.exp=="number"?a.exp:0;if(f<=Math.floor(this.now()/1e3))throw new N("machine token is expired \u2014 re-mint and retry");let m=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,i);if(m===void 0)throw new N(`machine token kid ${JSON.stringify(i)} is not in the machine issuer's JWKS`);let O=Buffer.from(`${n}.${r}`,"ascii"),P=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qt(O,P,m))throw new N("machine token signature failed verification");if(f<=Math.floor(this.now()/1e3))throw new N("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:h,credential:"machine"}}},ir="https://api.workos.com/sso/jwks/";function ar(t){return`${ir}${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 G("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(!Yt(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,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new N("malformed user token");let o,a;try{o=ne(n),a=ne(r)}catch{throw new N("malformed user token")}if(o.alg!=="RS256")throw new N(`user token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new N(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let h=typeof a.org_id=="string"?a.org_id:"";if(h==="")throw new N("user token carries no org_id \u2014 no tenancy to route by");let f=typeof a.sub=="string"?a.sub:"",m=typeof a.exp=="number"?a.exp:0;if(m<=Math.floor(this.now()/1e3))throw new N("user token is expired \u2014 re-authenticate and retry");let O=await this.cache.keyFor(ar(l),i);if(O===void 0)throw new N(`user token kid ${JSON.stringify(i)} is not in the WorkOS issuer's JWKS`);let P=Buffer.from(`${n}.${r}`,"ascii"),c=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qt(P,c,O))throw new N("user token signature failed verification");if(m<=Math.floor(this.now()/1e3))throw new N("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:h,credential:"user",subject:f}}},lr=5e3,cr=1500,dr=4096,z=class extends Error{status=403;detail;constructor(e,n){super(e),this.name="MembershipRefusalError",this.detail=n}};function Vt(){return new z("this account is not an active member of the organization \u2014 the membership may have been removed; sign out and sign back in")}var Ge=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now,this.timeoutMs=e.timeoutMs??cr}opts;cache=new Map;fetchImpl;now;timeoutMs;async assertActive(e,n){if(n==="")throw new z("the user token carries no subject \u2014 organization membership cannot be confirmed");let r=`${e}\0${n}`,s=this.cache.get(r);if(s!==void 0&&this.now()-s.at<lr){if(!s.active)throw Vt();return}let o=!1,a;try{let i=await this.fetchImpl(`${this.opts.url}/membership-check`,{method:"POST",headers:{authorization:`Bearer ${this.opts.token}`,"content-type":"application/json"},body:JSON.stringify({org_id:e,subject:n}),signal:AbortSignal.timeout(this.timeoutMs)});if(i.status!==200)a=`membership-check answered HTTP ${i.status}`;else try{let l=await i.json();l===null||typeof l!="object"||Array.isArray(l)||!("active"in l)||typeof l.active!="boolean"?a="membership-check answered a malformed body (expected {active: boolean})":o=l.active}catch(l){a=`membership-check answered a body that is not JSON (${l instanceof Error?l.message:String(l)})`}}catch(i){a=`membership-check failed (${i instanceof Error?i.message:String(i)})`}if(a!==void 0)throw new z("organization membership for this account could not be confirmed \u2014 try again shortly",a);if(this.cache.size>=dr){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}if(this.cache.set(r,{active:o,at:this.now()}),!o)throw Vt()}},we=class{verifier;bindings;memberGate;warnedGateDisabled=!1;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}:{}}),this.memberGate=e.memberGate!==void 0?new Ge(e.memberGate):null}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e);this.memberGate!==null?await this.memberGate.assertActive(n.orgId,n.subject):this.warnedGateDisabled||(this.warnedGateDisabled=!0,process.stderr.write(`[member-gate] member gate disabled \u2014 removed-member window remains open
4
4
  `));let r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new N("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(Yt(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}T();var ur=8080,Ke="serve",Qs="0.0.0.0";function fr(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Xs(t=process.env){let e=(t.PORT??"").trim(),n=e===""?ur: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=gt(ce(fr(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),s=(t.URUN_API_URL??"").trim(),o=s?ce(s,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,a=(t.URUN_CATALOG_URL??"").trim(),i=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!a!=!!i)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=a?{catalogUrl:ce(a,"URUN_CATALOG_URL"),anonKey:i}:null,h=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),f=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!h!=!!f)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let m=h?{keyId:f,key:h}:void 0,O={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},P=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],c=P.filter((v,A)=>Object.values(O)[A]==="");if(c.length!==0&&c.length!==P.length)throw new Error(`${P.join(", ")} must be set together (or all left unset) \u2014 missing: ${c.join(", ")}, which would half-configure the lane plane`);let y=c.length===0?O:void 0,_={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},k=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=k.filter((v,A)=>Object.values(_)[A]==="");if(g.length!==0&&g.length!==k.length)throw new Error(`${k.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let E=g.length===0?_:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},d=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=d.filter((v,A)=>Object.values(p)[A]==="");if(S.length!==0&&S.length!==d.length)throw new Error(`${d.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let R=p.issuers.split(",").map(v=>v.trim()).filter(v=>v!=="");if(R.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let w=Number(p.tokenTtlS);if(S.length===0&&(!Number.isFinite(w)||w<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let I=S.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:R,tokenTtlS:w}:void 0,U=(t.URUN_WORKOS_ISSUERS??"").trim(),$=U.split(",").map(v=>v.trim()).filter(v=>v!=="");if(U!==""&&$.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 v of $){let A;try{A=new URL(v)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(v)}`)}if(A.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${v}) \u2014 the issuer is the user rung's trust root`)}let u=(t.URUN_CONTROL_PLANE_URL??"").trim(),b=(t.URUN_CONTROL_PLANE_TOKEN??"").trim(),L=u!==""&&b!==""?{url:u.replace(/\/+$/,""),token:b}:void 0;return{port:n,baseUrl:r,apiUrl:o,catalog:l,ledgerSigning:m,lane:y,pooler:E,machine:I,memberGate:L,...$.length>0?{userIssuers:$}:{}}}T();import{createHash as hr,randomUUID as Xt}from"crypto";var pr=512;function ve(t){return`urun-inference-proxy-${hr("sha256").update(t).digest("hex").slice(0,32)}`}var _e=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let s=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;if(o===void 0)return s;let a=this.opts.lanes;return Object.assign(Object.create(s),{createResponse:async(i,l)=>{if(a!==void 0&&r!==void 0&&(await r.resolveTargetFor(i.model).catch(()=>null))?.sharedApp)return await s.createResponse(i,l);let h=`px_${Xt()}`;return Ct(o,i,h,h)}})}build(e){if(this.opts.build){let o=this.opts.build(e);return o.decision&&this.ensureDecisionReaper(),{router:o.router,clients:this.label(o.clients,e,o.router),decision:o.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName: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:xt(process.env,process.env.HOSTNAME)??void 0},r=De(n),s=n.decisionPool?Mt(n,r):null;return s&&this.ensureDecisionReaper(),{router:r,clients:this.label(He(r,void 0,void 0,s??void 0,void 0,this.opts.lanes),e,r),decision:s??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=pr;){let s=this.tenants.entries().next();if(s.done)break;let[o,a]=s.value;this.tenants.delete(o),a.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let s=[r.router.closeAll().catch(o=>{n.push(String(o instanceof Error?o.message:o))})];r.decision&&s.push(r.decision.close().catch(o=>{n.push(String(o instanceof Error?o.message:o))})),await Promise.all(s)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Zt=512,gr=1024,je=class extends Error{constructor(){super(`conversation capacity reached (${Zt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function mr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(ae))return{concurrencyKey:e};if(n.startsWith(ae)||n.startsWith(xe))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(ae)||n.startsWith(xe)||t.set(n,r)}}}function yr(t,e,n,r,s){let o=De({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",...mr(r,s)});return{clients:He(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Se=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let s={id:n,subject:r!==void 0?`${ve(e.apiKey)}:live`:`${ve(e.apiKey)}:live:${n}`},o=new Map,a=this.opts.build?this.opts.build(e,s):yr(this.opts,e,s,o,r);return{id:n,backhaul:a,attachments:0,nativeRefs:o}}attachEntry(e,n,r){let s=this.byCaller.get(e.apiKey);s===void 0&&(s=new Map,this.byCaller.set(e.apiKey,s));let o=s.get(n);if(o!==void 0)return s.delete(n),s.set(n,o),o.attachments+=1,o;this.evictOverflow();let a=this.build(e,n,r);return a.attachments=1,s.set(n,a),a}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Zt;){let e=!1;for(let[n,r]of this.byCaller){for(let[s,o]of r)if(!(o.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),o.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new je}}dropHandleIndexFor(e,n){for(let[r,s]of this.byHandle)s.apiKey===e&&s.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,s=!1,o=()=>(r===null&&(r=this.attachEntry(e,Xt(),n)),r),a={createResponse:(i,l)=>o().backhaul.clients.createResponse(i,l),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let l=o().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),dedicatedSessionHandle:i=>{let l=o().backhaul.clients.dedicatedSessionHandle;return l===void 0?o().backhaul.clients.sessionHandle(i):l(i)},releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),endDedicatedSession:i=>o().backhaul.clients.endDedicatedSession?.(i),touchSessionPresence:(i,l)=>o().backhaul.clients.touchSessionPresence?.(i,l),detachSessionPresence:(i,l)=>o().backhaul.clients.detachSessionPresence?.(i,l),createResponseOn:(i,l,h)=>o().backhaul.clients.createResponseOn(i,l,h),onSessionEnd:(i,l)=>o().backhaul.clients.onSessionEnd(i,l)};return a.openAudio=async(i,l)=>{let h=o().backhaul.clients.openAudio;if(h===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return h(i,l)},a.openVideo=async i=>{let l=o().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(i)},a.openVideoOut=async i=>{let l=o().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(i)},a.supportsAudio=async i=>{let l=o().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(i)},a.supportsSpeech=async i=>{let l=o().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(i)},a.speechVoices=async i=>{let l=o().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(i)},a.speechSessionHandle=async i=>{let l=o().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(i)},a.openAudioOn=async(i,l,h)=>{let f=o().backhaul.clients.openAudioOn;if(f===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return f(i,l,h)},a.openVideoOn=async(i,l)=>{let h=o().backhaul.clients.openVideoOn;if(h===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 h(i,l)},a.openTurnsOn=(i,l)=>{let h=o().backhaul.clients.openTurnsOn;if(h===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 h(i,l)},a.evictSpeechSession=async i=>{let l=o().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(i)},a.supportsTranscription=async i=>{let l=o().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(i)},a.transcriptStreamFor=async i=>{let l=o().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(i)},a.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:a,bindResumeHandle:i=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=gr;){let h=this.byHandle.keys().next();if(h.done)break;this.byHandle.delete(h.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async i=>{let l=this.byHandle.get(i),h=l===void 0?void 0:this.byCaller.get(l.apiKey),f=l===void 0||h===void 0?void 0:h.get(l.conversationId);if(l===void 0||f===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=f,f.attachments+=1,f.backhaul.clients},release:async()=>{if(s)return;s=!0;let i=r;r=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let s of r.values())e.push(s.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(s){n.push(String(s instanceof Error?s.message:s))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};T();var wr="/inference-ledger",br=1e4,ke=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},qe=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},H=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Ve=class extends N{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ye=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},vr=[["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",Je],["output_minutes",Je],["cost_nano_usd",Je],["price_version",t=>t===null||typeof t=="string"]];function _r(t){for(let[e,n]of vr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Sr(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"}:_r(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Je(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ze(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function kr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function en(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 Er(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&&en(t.started_at,n.started_at)&&en(t.completed_at,n.completed_at)&&ze(t.prompt_tokens,n.prompt_tokens)&&ze(t.completion_tokens,n.completion_tokens)&&ze(t.output_units,n.output_units)&&kr(t.output_minutes,n.output_minutes)}function Rr(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(`
@@ -205,7 +205,7 @@ interface InferenceRecord {
205
205
  */
206
206
 
207
207
  /** The turn kinds the transcribe bridge emits (TranscriptEvent kinds). */
208
- type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
208
+ type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
209
209
  /**
210
210
  * One decoded transcript-lane event — the `RealtimeBinding.turns` event
211
211
  * shape. `text` is the wire `delta` field (a transcript PIECE — the adapter
@@ -389,8 +389,10 @@ interface RealtimeBinding<S = unknown> {
389
389
  * (urun.serve.transcribe_bridge wire shape: `t` = delta/final/turn_start/
390
390
  * turn_end/turn_eager_end/turn_resumed, `delta` text, additive `start_ms`
391
391
  * and semantic-VAD `confidence`). The resolver maps `session.stream('stt')
392
- * .messages()` onto this. Its `turn_end` IS the native commit and
393
- * `turn_start` IS the native barge-in — the adapter drives server-VAD
392
+ * .messages()` onto this. Its `turn_end` IS the native commit,
393
+ * `turn_start` IS the native barge-in, and `turn_dropped` closes a
394
+ * `turn_start` window that ended with NO user turn (speech_stopped, no
395
+ * commit) — the adapter drives server-VAD
394
396
  * emulation, real transcription events, and model-visible committed audio
395
397
  * from it. Absent = the backend wired no turn lane: manual mode only.
396
398
  *
@@ -401,7 +403,7 @@ interface RealtimeBinding<S = unknown> {
401
403
  * un-raced lane (its own teardown is then its own problem).
402
404
  */
403
405
  turns?: (signal?: AbortSignal) => AsyncIterable<{
404
- kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
406
+ kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
405
407
  text?: string;
406
408
  confidence?: number;
407
409
  startMs?: number;
@@ -426,9 +428,11 @@ interface RealtimeBinding<S = unknown> {
426
428
  * and serves no upstream turn seam. The connection subscribes its voice
427
429
  * OUT at connect; the engine's `turn_end` commits the user item but never
428
430
  * dispatches a model turn; engine speech opens a SERVER-INITIATED response
429
- * (`response.output_audio.delta`), closed `completed` by a quiet-track run
430
- * or `cancelled` by the user's `turn_start`; a client `response.create` is
431
- * the non-fatal `duplex_engine_owns_turns` error. Requires `voice`.
431
+ * (`response.output_audio.delta`) — never while the user's turn is open
432
+ * (`turn_start` → `turn_end`): frames inside it are dropped — closed
433
+ * `completed` by a quiet-track run or `cancelled` by the user's
434
+ * `turn_start`; a client `response.create` is the non-fatal
435
+ * `duplex_engine_owns_turns` error. Requires `voice`.
432
436
  */
433
437
  duplex?: boolean;
434
438
  /**
@@ -65,7 +65,7 @@ interface InferenceRecord {
65
65
  readonly catalog: TurnCatalogIdentity;
66
66
  }
67
67
 
68
- type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
68
+ type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
69
69
 
70
70
  interface SessionTurnLaneEvent {
71
71
  kind: SessionTurnKind;
@@ -124,7 +124,7 @@ interface RealtimeBinding<S = unknown> {
124
124
  };
125
125
 
126
126
  turns?: (signal?: AbortSignal) => AsyncIterable<{
127
- kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
127
+ kind: 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
128
128
  text?: string;
129
129
  confidence?: number;
130
130
  startMs?: number;