@urun-sh/openai 0.6.26 → 0.6.28
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/{chunk-VVFQC4IC.js → chunk-AEMDPBN7.js} +1 -1
- package/dist/chunk-W3BULR2V.js +8 -0
- package/dist/{chunk-3QCAOHZT.js → chunk-ZWFOK53M.js} +2 -2
- package/dist/hosted/bin.cjs +28 -27
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +31 -30
- package/dist/hosted/index.d.cts +77 -22
- package/dist/hosted/index.d.ts +13 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +26 -26
- package/dist/proxy/cli.cjs +2 -2
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +1 -1
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/dist/{responses-turn-C0PBaF29.d.cts → responses-turn-BFURb0jK.d.cts} +16 -3
- package/dist/{responses-turn-2UJImii3.d.ts → responses-turn-Cxfv-oXb.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-MTE2WBU2.js +0 -7
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as M}from"./chunk-K23AZPI4.js";import{I as j,J as B,N as _,O as K,P as q}from"./chunk-
|
|
1
|
+
import{a as M}from"./chunk-K23AZPI4.js";import{I as j,J as B,N as _,O as K,P as q}from"./chunk-ZWFOK53M.js";import{a as F}from"./chunk-76BZLCGT.js";import{a as x,b as G,d as $,g as A,h as W,j as E,k as H,l as V}from"./chunk-CUDFHFNX.js";import{c as R,f as D,g as N,p as U}from"./chunk-6M5JK4YC.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as z,createClientToken as de,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as ue,DEFAULT_WHEN_LIVE_TIMEOUT_MS as Z,isWakingPhase as pe}from"@urun-sh/core";v();import{SessionFailedError as te}from"@urun-sh/core";var L=2;function se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function ie(e){let s=e?.type;return s==="response.completed"||s==="error"}function Q(e){return async function(a,d){return(async function*(){for(let l=1;l<=L;l++){let{app:p,entry:f,identity:t}=await e.sessionFor(a.model);d?.({sessionId:e.sessionIdOf?.(f)??null,identity:t});let i=!1,c=!1;try{let m=await e.createStream(f,a);for await(let g of m){if(ie(g)&&(i=!0),se(g)){if(l>1)continue}else c=!0;yield g}}catch(m){if(m instanceof te&&(m.kind==="never-live"||m.kind==="create-failed")){try{e.onAdmissionVerdict?.(p,f,m)}catch{}throw m}if(l<L&&!c){await e.evict(p,f);continue}throw m}if(i)return;if(l<L&&!c){await e.evict(p,f);continue}return}})()}}import{randomUUID as fe}from"crypto";v();var re=3,ae="llm",le=new Set(["paused","error"]);function Y(e,s){let a=e.doc(ae),d=typeof a.onConnectionState=="function",u=typeof e.onPhase=="function";if(!d&&!u)throw new Error(`session for app "${s}" 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 l=null,p=!1,f=new Set,t=[],i=c=>{if(!l){l=c;for(let m of[...f])m(c);f.clear()}};return d&&t.push(a.onConnectionState(c=>{p&&(c.consecutiveFailures<re||i(new A(`the pooled session for app "${s}" is gone: its doc backhaul failed ${c.consecutiveFailures} consecutive times (last close ${c.lastCloseCode===null?"by provider liveness reap":`code ${c.lastCloseCode}`}${c.lastCloseReason?`, reason ${JSON.stringify(c.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),u&&t.push(e.onPhase(c=>{if(c.name==="live"){p=!0;return}p&&le.has(c.name)&&i(new A(`the pooled session for app "${s}" lost its compute binding (phase "${c.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:()=>l,onGone(c){return l?(c(l),()=>{}):(f.add(c),()=>f.delete(c))},dispose(){f.clear();for(let c of t.splice(0))c()}}}async function*C(e,s){let a=s.gone();if(a)throw a;let d=e[Symbol.asyncIterator](),u,l=new Promise((p,f)=>{u=s.onGone(t=>f(t))});l.catch(()=>{});try{for(;;){let p=await Promise.race([d.next(),l]);if(p.done)return;yield p.value}}finally{u?.(),d.return?.(void 0)}}var me=1,ge=4,he=4;function He(e,s){let a=(p,f)=>{let t=(e[p]??"").trim();if(!t)return f;let i=Number.parseInt(t,10);if(!Number.isInteger(i)||i<1)throw new Error(`${p} must be a positive integer (got ${JSON.stringify(e[p])})`);return i},d=(e.URUN_DECISION_POOL_MIN??"").trim();if(d==="0")return null;let u=d?Number.parseInt(d,10):me;if(!Number.isInteger(u)||u<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let l=a("URUN_DECISION_POOL_MAX",Math.max(u,ge));return{min:u,max:l,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",he),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function Ve(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return _;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(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function ee(e,s,a,d){let u=e[a];if(typeof u!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let l=d?u(void 0,d):u();if(typeof l.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return l}function oe(e,s,a,d){let{baseUrl:u,orgId:l,auth:p}=e,f=s.fnName??e.fnName,t=e.sessionStartOptions?.(a),i=d||t||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...t,...d}:void 0,c=o=>({session:o,responses:new F(o),gone:Y(o,a)});if(p.lane==="jwt"){let o=z(s.appSlug,{baseUrl:u,orgId:l,jwt:p.jwt});return c(ee(o,s.appSlug,f,i))}let{apiKey:m,gatewayUrl:g}=p,w=(typeof e.subject=="function"?e.subject():e.subject)??fe(),n=z(s.appSlug,{baseUrl:u,orgId:l,getAccessToken:async()=>(await de(m,{baseUrl:g,expiresIn:300,allowedFunctions:[`${s.appSlug}/${f}`],subject:w,...s.sharedApp?{sharedApp:!0}:{}})).token});return c(ee(n,s.appSlug,f,i))}function we(e){let s=e.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 Se(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var ye=new Set(["error","paused"]);function je(e){let{auth:s,catalog:a}=e,d=null,u=(p,f)=>{let t=oe(e,p,f);return e.onSessionOpen&&typeof t.session.id=="string"&&t.session.id!==""&&e.onSessionOpen(f,t.session.id),t.gone.onGone(()=>{d?.evict(f,t)}),t},l=new V({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:u,closeSession:async p=>{if(p.gone.dispose(),e.release==="detach"){if(typeof p.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');p.session.detach();return}await p.session.end()},listApps:s.lane==="api-key"?()=>W({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:a?()=>M(a):null,listPrices:a?()=>G(a):null,shared:s.lane==="api-key"?()=>x({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,sessionKey:we});return d=l,e.defaultApp!==null&&l.seed(e.defaultApp,u({appSlug:e.defaultApp},E({appSlug:e.defaultApp}))),l}function Be(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let d=a.replicaId??"proxy",u=new Map,l=new Map,p=t=>{process.stderr.write(`[decision-pool] ${t}
|
|
2
2
|
`)},f=(t,i)=>{let c=u.get(i);if(c)return c;let m=new B({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:d,openSlot:async g=>{let w=oe(e,t,i,{concurrencyKey:g.concurrencyKey});return w.gone.onGone(()=>m.evict(w)),await b(w.session),p(`slot attached pool=${i} slot=${g.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async g=>{g.gone.dispose(),await g.session.end()},onDetach:(g,w)=>p(`slot detached pool=${i} slot=${g.concurrencyKey} reason=${w}`)});return u.set(i,m),m};return{async boot(){if(e.defaultApp===null)return;let t={appSlug:e.defaultApp};await f(t,E(t)).boot()},async sessionFor(t){let i=await s.resolveTargetFor(t),c=E(i),m=f(i,c).tryAcquireReady();if(!m)throw new j(f(i,c).stats().lastMissAgeMs);let g=l.get(m.entry)??[];return g.push(m),l.set(m.entry,g),{app:c,entry:m.entry,identity:H(i)}},async warmFor(t){let i=await s.resolveTargetFor(t);await f(i,E(i)).boot()},end(t){let i=l.get(t)?.shift();i&&(l.get(t)?.length===0&&l.delete(t),i.release())},evict(t){for(let i of u.values())i.evict(t)},reap(){for(let t of u.values())t.reap()},async pingReady(t){for(let i of u.values())if(await i.pingReady(t))return!0;return!1},stats(){return[...u.entries()].map(([t,i])=>({poolKey:t,...i.stats()}))},async drain(t){await Promise.all([...u.values()].map(i=>i.drain({timeoutMs:t})))},async close(){await Promise.all([...u.values()].map(t=>t.close()))}}}function ve(e){return pe(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?Z:ue:Z}async function b(e,s){let a=e.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(e,{timeout:ve(e.phase),signal:s})}async function ne(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function O(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Ke(e,s=N,a,d,u=_){let l=new WeakMap,p=new WeakMap,f=new WeakMap,t=new WeakMap,i=new WeakMap,c=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},m=n=>{let o=l.get(n);if(!o){let r={waiting:0,gone:new AbortController};i.set(n,r),o=(async()=>{if(await b(n.session,r.gone.signal),r.gone.signal.aborted)throw O(r.gone.signal);i.get(n)===r&&i.delete(n);let h=await R(n.session,await s());return Object.assign(h,{sessionId:n.session.id})})(),l.set(n,o),o.catch(()=>{l.get(n)===o&&l.delete(n)}),o.then(()=>{i.get(n)===r&&i.delete(n)},()=>{i.get(n)===r&&i.delete(n)})}return o},g=n=>{let o=t.get(n);return o||(o=(async()=>{let r=await m(n);return{appendInputAudio:h=>r.appendInputAudio(h),onOutputAudio:h=>r.onOutputAudio(h),sessionId:c(n)}})(),t.set(n,o),o.catch(()=>{t.get(n)===o&&t.delete(n)})),o},w=async(n,o,r)=>{if(r?.aborted){let S=i.get(n);throw(l.get(n)===void 0||S!==void 0&&S.waiting===0)&&await ne(n.session),O(r)}let h=o(n),y=i.get(n);return y!==void 0&&y.waiting++,r===void 0?h:new Promise((S,P)=>{let T=()=>{y!==void 0&&--y.waiting===0&&i.get(n)===y&&(y.gone.abort(),i.delete(n),l.delete(n),t.delete(n),ne(n.session).catch(()=>{})),P(O(r))};r.addEventListener("abort",T,{once:!0});let k=()=>r.removeEventListener("abort",T);h.then(I=>{k(),S(I)},I=>{k(),P(I)})})};return{createResponse:Q({sessionFor:d?n=>d.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>c(n),evict:(n,o)=>{d?d.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,r)=>{Se(r)&&(d?d.evict(o):e.evict(n,o),a?.(n,r.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await b(n.session);let r=K(C(await n.responses.responses.create(o),n.gone),u);if(!d)return r;let h=n;return(async function*(){try{yield*r}catch(S){throw q(S)&&d.evict(h),S}finally{d.end(h)}})()}catch(r){throw d&&d.end(n),r}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,o)=>{let{entry:r}=await e.sessionFor(n);return await w(r,m,o)},openAudioOn:async(n,o)=>{let{entry:r}=await e.sessionForHandle(n);return await w(r,g,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw O(o);let{entry:r}=await e.sessionForHandle(n);yield*$(r.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),r=p.get(o);return r||(r=D(o.session),p.set(o,r)),r},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),r=f.get(o);return r||(r=U(o.session),f.set(o,r)),r},sessionHandle:async n=>(await e.handleFor(n)).handle,speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:r}=await e.sessionForHandle(n);await e.evict(o,r)},createResponseOn:async(n,o)=>{let{entry:r}=await e.sessionForHandle(n);return await b(r.session),C(await r.responses.responses.create(o),r.gone)},onSessionEnd:async(n,o)=>{let{entry:r}=await e.sessionForHandle(n),h=r.session;if(typeof h.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let y=!1;return h.onPhase(S=>{if(y||!ye.has(S.name))return;y=!0;let P=h.endsAt??null;o({timeLeftMs:P?Math.max(0,P.getTime()-Date.now()):null,reason:S.reason??`session ${S.name}`})})}}}export{He as a,Ve as b,je as c,Be as d,Ke as e};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{a as ke,c as W,d as xe,e as J}from"./chunk-AEMDPBN7.js";import{C as ue,D as de,E as he,F as pe,G as ge,K as fe,L as T,M as me,Q as ye,R as we,S as be,T as _e,U as ve,V as Ee,W as Se,X as Re,b as ie,d as ae,e as le,q as ce,r as O}from"./chunk-ZWFOK53M.js";import{c as re,g as oe,i as j}from"./chunk-CUDFHFNX.js";import{a as se}from"./chunk-3JWYIKHM.js";import{c as m}from"./chunk-YSFSRI3D.js";m();import{Counter as I,Gauge as Ie,Histogram as Ce,Registry as Ke,collectDefaultMetrics as Be}from"@prometheus-io/client";import{createServer as ze}from"http";var jt=9464,Ne="/metrics",A="(other)",je="(none)",We=64,Je=128,Ye=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",fe,ye,re],Ve=new Set(Ye);function qe(t){return Ve.has(t)?t:A}function Qe(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var P=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?je:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,A):(this.admitted.add(e),e):A}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},U=class{registry=new Ke;modelLabel=new P(We);orgLabel=new P(Je);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;constructor(e={}){this.requests=new I({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 Ce({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 Ce({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 I({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 I({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 I({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 we)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new Ie({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"},be()),this.ledgerQueue.set({measure:"oldest_age_seconds"},_e()/1e3)}}),this.labelCardinality=new Ie({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 I({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]}),e.defaultMetrics!==!1&&Be({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observe(e){let n=qe(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,a=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let u=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?A:e.method,status_class:Qe(e.status),stream:u,model:a,org:s}),this.duration.observe({lane:n,stream:u,model:a,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:a,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:a}),e.delivered||this.undelivered.inc({lane:n,model:a})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Oe(t){return ze((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ne){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ne}
|
|
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()})})}m();import{createHash as Ae}from"crypto";import{createServer as Xe}from"http";var qt=9465,Ze="x-urun-key-id",et="x-urun-key-fingerprint",tt="urun-ratelimit-bucket:",nt="urun-ratelimit-tier:",Te="anonymous",rt=/^urun_sk_[A-Za-z0-9_-]{43}$/;function ot(t){return Ae("sha256").update(`${tt}${t}`).digest("hex")}function st(t){return Ae("sha256").update(`${nt}${t}`).digest("hex")}function it(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return rt.test(n)?n:null}function Pe(){return Xe((t,e)=>{let n=it(t.headers.authorization);e.setHeader(Ze,n===null?Te:ot(n)),e.setHeader(et,n===null?Te:st(n)),e.writeHead(200),e.end()})}m();import{createClientToken as at,ClientTokenError as lt}from"@urun-sh/core";var w=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},k=class extends Error{constructor(e){super(e),this.name="ControlPlaneUnavailableError"}};function C(t){let e=(t??"").trim();if(e==="")throw new w("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 w("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var ct=60,ut=6e4,dt=4096;function ht(t){return t===401||t===403}var L=class{constructor(e){this.opts=e;this.mint=e.mint??at,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new w("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<ut)return{apiKey:e,orgId:n.orgId};let r;try{r=(await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:ct})).orgId}catch(o){throw o instanceof lt&&ht(o.status)?(this.cache.delete(e),new w("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new k(`could not verify the API key against the uRun control plane at ${this.opts.gatewayUrl}: ${o instanceof Error?o.message:String(o)}`)}if(!r)throw new k("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=dt){let o=this.cache.keys().next();o.done||this.cache.delete(o.value)}return this.cache.set(e,{orgId:r,at:this.now()}),{apiKey:e,orgId:r}}clear(){this.cache.clear()}};m();var pt=8080,Y="serve",rn="0.0.0.0";function gt(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function on(t=process.env){let e=(t.PORT??"").trim(),n=e===""?pt: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=ce(O(gt(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(),a=o?O(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),i=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!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 u=s?{catalogUrl:O(s,"URUN_CATALOG_URL"),anonKey:i}:null,c=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),h=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!c!=!!h)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");return{port:n,baseUrl:r,apiUrl:a,catalog:u,ledgerSigning:c?{keyId:h,key:c}:void 0}}m();import{createHash as ft,randomUUID as mt}from"crypto";var yt=512;function V(t){return`urun-inference-proxy-${ft("sha256").update(t).digest("hex").slice(0,32)}`}var $=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n){return Object.assign(Object.create(e),{tenant:n.orgId})}build(e){if(this.opts.build){let a=this.opts.build(e);return a.decision&&this.ensureDecisionReaper(),{router:a.router,clients:this.label(a.clients,e),decision:a.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Y,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalog,release:"end",decisionPool:ke(process.env,process.env.HOSTNAME)??void 0},r=W(n),o=n.decisionPool?xe(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(J(r,void 0,void 0,o??void 0),e),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>=yt;){let o=this.tenants.entries().next();if(o.done)break;let[a,s]=o.value;this.tenants.delete(a),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(a=>{n.push(String(a instanceof Error?a.message:a))})];r.decision&&o.push(r.decision.close().catch(a=>{n.push(String(a instanceof Error?a.message:a))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Ue=512,wt=1024,H=class extends Error{constructor(){super(`conversation capacity reached (${Ue} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function bt(t){return{sessionStartOptions:e=>{if(e.startsWith(j))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(j)||t.set(e,n)}}}function _t(t,e,n,r){let o=W({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Y,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalog,subject:n.subject,release:"detach",...bt(r)});return{clients:J(o),release:async()=>{await o.closeAll()}}}var D=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${V(e.apiKey)}:live:${n}`},o=new Map,a=this.opts.build?this.opts.build(e,r):_t(this.opts,e,r,o);return{id:n,backhaul:a,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let a=this.build(e,n);return a.attachments=1,r.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>=Ue;){let e=this.byCaller.keys().next();if(e.done)throw new H;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[a,s]of r)if(!(s.attachments>0)){r.delete(a),this.dropHandleIndexFor(n,a),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new H;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,mt())),n),a={createResponse:(s,i)=>o().backhaul.clients.createResponse(s,i),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let i=o().backhaul.clients.servingAppSlug;if(i===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 i(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),createResponseOn:(s,i)=>o().backhaul.clients.createResponseOn(s,i),onSessionEnd:(s,i)=>o().backhaul.clients.onSessionEnd(s,i)};return a.openAudio=async(s,i)=>{let u=o().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(s,i)},a.openVideo=async s=>{let i=o().backhaul.clients.openVideo;if(i===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return i(s)},a.openVideoOut=async s=>{let i=o().backhaul.clients.openVideoOut;if(i===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return i(s)},a.supportsAudio=async s=>{let i=o().backhaul.clients.supportsAudio;if(i===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return i(s)},a.supportsSpeech=async s=>{let i=o().backhaul.clients.supportsSpeech;if(i===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return i(s)},a.speechVoices=async s=>{let i=o().backhaul.clients.speechVoices;if(i===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 i(s)},a.speechSessionHandle=async s=>{let i=o().backhaul.clients.speechSessionHandle;if(i===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 i(s)},a.openAudioOn=async(s,i)=>{let u=o().backhaul.clients.openAudioOn;if(u===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 u(s,i)},a.openTurnsOn=(s,i)=>{let u=o().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(s,i)},a.evictSpeechSession=async s=>{let i=o().backhaul.clients.evictSpeechSession;if(i===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 i(s)},a.supportsTranscription=async s=>{let i=o().backhaul.clients.supportsTranscription;if(i===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return i(s)},a.transcriptStreamFor=async s=>{let i=o().backhaul.clients.transcriptStreamFor;if(i===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 i(s)},a.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return s()},{clients:a,bindResumeHandle:s=>{let i=n;if(i===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=wt;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:i.id})},clientsForResume:async s=>{let i=this.byHandle.get(s),u=i===void 0?void 0:this.byCaller.get(i.apiKey),c=i===void 0||u===void 0?void 0:u.get(i.conversationId);if(i===void 0||c===void 0||i.apiKey!==e.apiKey)throw new oe("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=c,c.attachments+=1,c.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};m();var vt="/inference-ledger",Et=1e4,M=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},X=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},g=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Z=class extends w{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ee=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},St=[["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",q],["output_minutes",q],["cost_nano_usd",q],["price_version",t=>t===null||typeof t=="string"]];function Rt(t){for(let[e,n]of St){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function kt(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"}:Rt(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function q(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Q(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function xt(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Le(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 It(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&&Le(t.started_at,n.started_at)&&Le(t.completed_at,n.completed_at)&&Q(t.prompt_tokens,n.prompt_tokens)&&Q(t.completion_tokens,n.completion_tokens)&&Q(t.output_units,n.output_units)&&xt(t.output_minutes,n.output_minutes)}function Ct(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v1",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(n),t.started_at,t.completed_at].join(`
|
|
4
|
+
`)}async function Nt(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(Ct(t)));return{signature:Array.from(new Uint8Array(o),s=>s.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function Ot(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new g(`${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 g(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new g(`${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 g(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let a=c=>{if(!(c in n))throw new g(`${e} answered a row with no ${c} field: ${JSON.stringify(t)}`);let h=n[c];if(h===null)return null;if(typeof h!="string")throw new g(`${e} answered a non-string ${c}: ${JSON.stringify(h)}`);if(!/[^\s]/.test(h))throw new g(`${e} answered a BLANK ${c} (${JSON.stringify(h)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return h},s=a("price_version"),i=a("unpriced_reason"),u=o!=null;if(u&&(s===null||i!==null))throw new g(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(i)}`);if(!u&&(s!==null||i===null))throw new g(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(i)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:i}}var G=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${vt}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await Nt(n,this.opts.signing)}):JSON.stringify(n)}catch(c){throw new g(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${c instanceof Error?c.message:String(c)}`)}let a;try{a=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(Et)})}catch(c){throw new g(`the uRun ledger surface at ${r} could not be reached: ${c instanceof Error?c.message:String(c)}`)}if(a.status===409){let c=await a.text().catch(()=>""),h=kt(c);throw h.status==="found"&&It(n,h.row)?new X(h.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.`):h.status==="not_in_this_org"?new M(`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 M(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${h.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${c.slice(0,400)}`)}if(a.status===401||a.status===403)throw await a.text().catch(()=>{}),new Z("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(!a.ok){let c=await a.text().catch(y=>`<body unreadable: ${y instanceof Error?y.message:String(y)}>`),h;try{let y=JSON.parse(c);if(y!==null&&typeof y=="object"&&"error"in y){let E=y.error;E!==null&&typeof E=="object"&&"code"in E&&(h=E.code)}}catch{}throw h==="ledger_signature_invalid"?new ee(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+c.slice(0,400)):new g(`the uRun ledger surface at ${r} answered HTTP ${a.status}: ${c.slice(0,400)}`)}let s;try{s=await a.json()}catch(c){throw new g(`the uRun ledger surface at ${r} answered a body that is not JSON: ${c instanceof Error?c.message:String(c)}`)}let i=s?.recorded;if(i===void 0)throw new g(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let u=Ot(i,`the uRun ledger surface at ${r}`);if(u.inference_id!==n.inference_id)throw new g(`the uRun ledger surface at ${r} answered for inference_id ${u.inference_id} when asked about ${n.inference_id}`);return u}};m();import{createServer as At}from"http";m();var F="/inference-usage",$e=25e3;var Tt=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function He(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Tt.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 K=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${F}`,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($e)})}catch(s){throw new T(`the uRun usage surface (POST ${F}) could not be reached within ${$e}ms: ${He(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new w("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),i=s===null?"body unreadable":`${s.length}-character body`;throw new T(`the uRun usage surface (POST ${F}) answered HTTP ${o.status} (${i})`)}let a;try{a=await o.json()}catch(s){throw new T(`the uRun usage surface (POST ${F}) answered HTTP ${o.status} with a body that is not JSON: ${He(s)}`)}return me(a,this.opts.onRejectedRow)}};var Pt=5e3,Ut=1e3,Lt=1500,$t=3e3,Ht="/api/client-tokens";function te(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function De(t,e,n,r){te(t,e,{error:{message:n,type:r}})}async function Dt(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Ht}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout($t)});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 Ln(t){let e=t.resolver??new L({gatewayUrl:t.baseUrl}),n=t.registry??new $({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),r=t.probeControlPlane??(()=>Dt(t.baseUrl)),o=async()=>{let l=null;for(let f of n.decisionPools()){l=f;break}if(!l)return null;let d=l.stats();if(d.some(f=>f.draining))return{ok:!1,detail:"decision pool draining"};if(d.every(f=>f.attached===0&&f.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let p=await l.pingReady(Lt);return{ok:p,detail:p?"a decision slot answered its session ping":"no decision slot answered its session ping"}},a=t.usageClient??new K({apiUrl:t.apiUrl}),s=t.ledgerClient??new G({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),i=process.env.URUN_SHARED_ORG_ID?.trim(),u=process.env.URUN_SHARED_ORG_API_KEY?.trim();i&&u&&(async()=>{try{await n.decisionWarmerFor({orgId:i,apiKey:u})?.warmFor(Se)}catch(l){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(l instanceof Error?l.message:l)}
|
|
5
|
+
`)}})();let c=new U(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),h=async l=>e.resolve(C(l.headers.authorization)),y=l=>l instanceof w?{status:l.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:l instanceof k?{status:502,openaiType:"upstream_error",anthropicType:"api_error"}:null,E=Re({clients:async l=>n.clientsFor(await h(l)),usage:{authorize:l=>C(l.headers.authorization),lookup:(l,d)=>a.lookup(l,d)},statusOf:y,...t.requestLog?{requestLog:t.requestLog}:{},observe:l=>c.observe(l),ledger:{write:(l,d)=>s.write(C(l.headers.authorization),d),observe:l=>c.observeLedger(l),...t.ledgerLog?{report:t.ledgerLog}:{}}}),S=null,R=null,x=At((l,d)=>{let p=new URL(l.url??"/","http://localhost");(async()=>{if(l.method==="GET"&&p.pathname==="/healthz"){te(d,200,{ok:!0});return}if(l.method==="GET"&&p.pathname==="/readyz"){let b=Date.now();if((!S||b-S.at>=Pt)&&(S={at:b,...await r()}),!R||b-R.at>=Ut){let z=await o();R=z===null?{at:b,ok:!0,detail:null}:{at:b,ok:z.ok,detail:z.detail}}let ne=(S?.ready??!1)&&R.ok,Fe=R.detail===null?S?.detail??"control plane not yet probed":`${S?.detail??"control plane not yet probed"}; ${R.detail}`;te(d,ne?200:503,{ok:ne,control_plane:Fe});return}let f=p.pathname==="/v1"||p.pathname.startsWith("/v1/"),N=p.pathname.startsWith("/partners/");if(!f&&!N){De(d,404,`no route for ${l.method} ${p.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 and /readyz`,"invalid_request_error");return}E(l,d)})().catch(f=>{if(!d.headersSent){De(d,500,String(f instanceof Error?f.message:f),"proxy_error");return}d.end()})}),B=t.conversations??new D({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:t.catalog}),Me=[ie(x,{authenticate:async l=>{let d=await e.resolve(l),p=B.connectionFor(d);return{clients:p.clients,scope:V(d.apiKey),onBindResumeHandle:p.bindResumeHandle,clientsForResume:p.clientsForResume,release:p.release}}}),le(x,{clients:async l=>n.clientsFor(await h(l)),statusOf:y}).close,de(x,{resolver:{resolve:async(l,d)=>{let p=await e.resolve(C(l.headers.authorization)),f=B.connectionFor(p),N;try{N=await ge(f.clients,he(l),d,pe(l))}catch(b){throw f.release().catch(()=>{}),b}return{...N,release:f.release}}}})];x.on("upgrade",(l,d)=>{let p=new URL(l.url??"/","http://localhost");p.pathname===se||p.pathname===ae||p.pathname===ue||d.destroyed||(d.write(`HTTP/1.1 404 Not Found\r
|
|
6
|
+
Connection: close\r
|
|
7
|
+
\r
|
|
8
|
+
no WS route for ${p.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),d.destroy())});let Ge=async()=>{for(let l of Me)await l();await B.detachAll()};return{server:x,metricsServer:Oe(c),metrics:c,edgeIdentityServer:Pe(),registry:n,closeAll:()=>n.closeAll(),closeWebSockets:Ge}}async function $n(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await ve()||Ee(),await e()}export{jt as a,Ne as b,A as c,je as d,We as e,Je as f,qe as g,Qe as h,P as i,U as j,Oe as k,qt as l,Ze as m,et as n,tt as o,nt as p,Te as q,ot as r,st as s,it as t,Pe as u,w as v,k as w,C as x,ut as y,dt as z,L as A,pt as B,Y as C,rn as D,on as E,yt as F,V as G,$ as H,Ue as I,wt as J,H as K,D as L,vt as M,Et as N,M as O,g as P,Ot as Q,G as R,Pt as S,$t as T,Ln as U,$n as V};
|
|
@@ -2,7 +2,7 @@ import{c as He,e as _n,f as D,g as se}from"./chunk-CUDFHFNX.js";import{a as yn,c
|
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
4
|
${p}\r
|
|
5
|
-
`),a.destroy())}))});let o=null;return()=>(o??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),o)}function Bi(n,e,t=new lt){new ct(n,e,t)}A();import ps from"os";import ms from"path";import{fileURLToPath as fs}from"url";import{format as hs}from"util";var Un="0.6.
|
|
5
|
+
`),a.destroy())}))});let o=null;return()=>(o??=(async()=>{for(let i of r.clients)i.close(1001,"server closing");await new Promise((i,a)=>r.close(u=>u===void 0?i():a(u)))})(),o)}function Bi(n,e,t=new lt){new ct(n,e,t)}A();import ps from"os";import ms from"path";import{fileURLToPath as fs}from"url";import{format as hs}from"util";var Un="0.6.28";var Nn=4141,gs=Un,Xi={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 _s(n,e="openai"){if(e==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${n}`,ANTHROPIC_API_KEY:"urun-local"};let t=`http://127.0.0.1:${n}/v1`;return{OPENAI_BASE_URL:t,OPENAI_API_BASE:t,OPENAI_API_KEY:"urun-local"}}function Qi(n,e,t){let r={...n,..._s(e,t)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function Zi(n,e,t){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${n}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],s=t.indexOf("--"),o=s===-1?t:t.slice(0,s),i=o.some(l=>l==="-m"||l==="--model"||l.startsWith("--model=")),a=t[0]==="exec",u=o.includes("--skip-git-repo-check"),d=a&&!u?["exec","--skip-git-repo-check",...t.slice(1)]:t;return[...r,...i?[]:["-m",e],...d]}function ea(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--provider","urun","--model",n,...e]}function ta(n,e){return e.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?e:["--model",`urun/${n}`,...e]}function na(n,e,t){let r=(n.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!t(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 s=fs(new URL("../pi-extension/standalone.cjs",e));if(!t(s))throw new Error(`pi extension entry not found at ${s} \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 s}function Fn(n){let e=Number(n);if(!Number.isInteger(e)||e<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${n}`);return e}function ra(n){if(n[0]!=="--port")return null;let e=Fn(n[1]);return n.splice(0,2),e}function sa(n){let e=n.indexOf("--port");if(e===-1)return Nn;let t=Fn(n[e+1]);return n.splice(e,2),t}function oa(n){if(n===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 n}function Nt(n,e){let t=(n[e]??"").trim();if(!t)throw new Error(`${e} 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 t}function ia(n){let e=ys(Nt(n,"URUN_BASE_URL")),t=Nt(n,"URUN_ORG_ID"),r=Nt(n,"URUN_APP"),s=(n.URUN_FUNCTION??"serve").trim()||"serve",o=(n.URUN_API_URL??"").trim(),i=o?$n(o,"URUN_API_URL"):_n,a=(n.URUN_JWT??"").trim();if(a)return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:i,auth:{lane:"jwt",jwt:a}};let u=(n.URUN_API_KEY??"").trim();if(u){let d=(n.URUN_GATEWAY_URL??"").trim(),l=d?$n(d):void 0;return{baseUrl:e,orgId:t,appId:r,fnName:s,apiUrl:i,auth:{lane:"api-key",apiKey:u,gatewayUrl:l}}}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 ys(n,e="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(n).pathname))throw new Error(`${e} must be the session-gateway base (e.g. https://api.urun.sh), got ${n} \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 n}function $n(n,e="URUN_GATEWAY_URL"){let t=new URL(n),r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!r)throw new Error(`${e} must be https (got ${n}) \u2014 the org API key rides the request's Authorization header`);return n}function aa(n){return{app:n.appId,org:n.orgId,fn:n.fnName,base_url:n.baseUrl,proxy_version:gs}}function ws(n,e){return n.app===e.app&&n.org===e.org&&n.fn===e.fn&&n.base_url===e.base_url&&n.proxy_version===e.proxy_version}var vs=250;async function bs(n,e=vs){try{let t=await fetch(`http://127.0.0.1:${n}/stats`,{signal:AbortSignal.timeout(e)});if(!t.ok)return null;let r=(await t.json()).identity;if(r==null||typeof r!="object")return null;let{app:s,org:o,fn:i,base_url:a,proxy_version:u}=r;return typeof s!="string"||typeof o!="string"||typeof i!="string"||typeof a!="string"||typeof u!="string"?null:{app:s,org:o,fn:i,base_url:a,proxy_version:u}}catch{return null}}var Dn=2e3;async function xs(n,e=Dn){try{let t=await fetch(`http://127.0.0.1:${n}/v1/models`,{signal:AbortSignal.timeout(e)});return t.ok?null:`GET /v1/models answered HTTP ${t.status}`}catch(t){return`GET /v1/models failed (${String(t instanceof Error?t.message:t)})`}}async function ua(n,e,t=Nn,r=Dn){if(n!=null)return{mode:"spawn",port:n};let s=await bs(t);if(s!==null&&ws(s,e)){let o=await xs(t,r);return o===null?{mode:"reuse",port:t,identity:s}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${t} matches this invocation's identity but failed the serving-surface liveness check (${o}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function da(n,e=ps.homedir()){return ms.join(e,".urun","logs",`compat-proxy-${n}.log`)}var Ft=["log","info","warn","error","debug","trace"];function la(n,e=process,t=console){let r=e.stdout.write,s=e.stderr.write,o=(a,...u)=>n.write(a,...u);e.stdout.write=o,e.stderr.write=o;let i=Object.fromEntries(Ft.map(a=>[a,t[a]]));for(let a of Ft)t[a]=(...u)=>{n.write(`${hs(...u)}
|
|
6
6
|
`)};return()=>{e.stdout.write=r,e.stderr.write=s;for(let a of Ft)t[a]=i[a]}}var ks=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function qn(n){let e=n?.code;return typeof e=="string"&&ks.has(e)}function ge(n,e){try{return n.write(e),!0}catch(t){if(qn(t))return!1;throw t}}function ca(n){let e={stdout:!1,stderr:!1},t=[];for(let r of["stdout","stderr"]){let s=n.streams[r],o=i=>{qn(i)&&(e[r]=!0);let a=i?.code;try{n.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(a??(i instanceof Error?i.message:i))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
7
7
|
`)}catch{}};s.on("error",o),t.push([s,o])}return{isDead:r=>e[r],uninstall:()=>{for(let[r,s]of t)r.off("error",s)}}}function pa(n){let e=t=>{let r=t instanceof Error?`${t.stack??`${t.name}: ${t.message}`}`:String(t);try{n.appendSync(n.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
8
8
|
`)}catch{}n.restore();try{n.writeStderr(`urun compat: the in-process proxy crashed (${t instanceof Error?t.message:String(t)}) \u2014 terminating the harness (its backend is gone); details: ${n.logPath}
|
|
@@ -21,7 +21,7 @@ Content-Type: text/plain; charset=utf-8\r
|
|
|
21
21
|
Content-Length: ${Buffer.byteLength(s)}\r
|
|
22
22
|
\r
|
|
23
23
|
${s}`)}function er(n,e){let t=new no({noServer:!0,maxPayload:so}),r=new xe,s=new Set,o=new Set,i=new Set,a=typeof e.clients=="function"?e.clients:()=>e.clients,u=!1,d=(l,c,v)=>{let p;try{p=new URL(l.url??"/","http://localhost")}catch{yt(c,400,"malformed upgrade URL");return}if(c.on("error",()=>c.destroy()),c.on("close",()=>i.delete(c)),p.pathname!==ro){i.add(c);return}o.add(c);let x=!1;(async()=>{if(e.apiKey&&(l.headers.authorization??"")!==`Bearer ${e.apiKey}`){yt(c,401,"invalid local proxy api key");return}let R;try{R=await a(l)}catch(b){let m=e.statusOf?.(b)??null;yt(c,m?.status??500,"upstream resolver rejected the connection");return}u||c.destroyed||(x=!0,t.handleUpgrade(l,c,v,b=>{o.delete(c),s.add(b),b.on("close",()=>s.delete(b));try{new Qt(b,R,r,e.statusOf)}catch{s.delete(b),b.close(1011,"responses websocket setup failed")}}))})().catch(()=>{!x&&!c.destroyed&&yt(c,500,"responses websocket upgrade failed")}).finally(()=>o.delete(c))};return n.on("upgrade",d),{stats:r,close:()=>{let{promise:l,resolve:c}=Zt();if(u)return c(),l;u=!0,n.off("upgrade",d);for(let p of o)p.destroy();o.clear();for(let p of i)p.destroy();i.clear();for(let p of s)p.close(1001,"server shutting down");let v=setTimeout(()=>{for(let p of s)p.readyState!==Qe.CLOSED&&p.terminate()},2e3);return v.unref?.(),t.close(()=>{clearTimeout(v),c()}),l}}}A();var Ne=class extends Error{code;status;retryAfterSeconds;constructor(e,t,r,s){super(s),this.name="DecisionStreamFailure",this.code=e,this.status=t,this.retryAfterSeconds=r,Object.setPrototypeOf(this,new.target.prototype)}},Ze=class extends Ne{constructor(){super("draining",503,5,"decision pool is draining (GOAWAY): no new decisions may start; retry on the next replica")}},en=class extends Ne{constructor(e){super("acquire_timeout",429,30,`no decision slot capacity within ${e}ms (all slots at their in-flight cap)`)}},et=class extends Error{lastDemandAgeMs;constructor(e){super("no ready decision slot on this proxy \u2014 the request was refused fast, not fenced; retry shortly (an out-of-band slot add was submitted)"),this.name="DecisionCapacityError",this.lastDemandAgeMs=e}},tr=class{constructor(e){this.opts=e;if(!Number.isInteger(e.min)||e.min<0)throw new Error("decision pool min must be a non-negative integer");if(!Number.isInteger(e.max)||e.max<e.min||e.max<1)throw new Error("decision pool max must be an integer >= min and >= 1");if(e.idleGraceMs!==void 0&&e.idleGraceMs<0)throw new Error("decision pool idleGraceMs must be >= 0");if(!Number.isInteger(e.inFlightCap)||e.inFlightCap<1)throw new Error("decision pool inFlightCap must be an integer >= 1");if(!e.replicaId)throw new Error("decision pool replicaId must be non-empty");this.now=e.now??Date.now,this.idleGraceMs=e.idleGraceMs??3e4}opts;slots=[];nextIndex=0;lastDemandAt=null;missCount=0;missCountPastWindow=0;lastMissAgeMs=null;idleGraceMs;waiters=[];now;closed=!1;draining=!1;drainComplete=null;slotKey(e){return`decision:${this.opts.replicaId}:${e}`}async boot(){this.closed||this.draining||await Promise.all(this.slots.map(e=>e.opening??Promise.resolve()))}openForDemand(){let e=this.slots.filter(t=>t.state==="paused"&&!t.opening).sort((t,r)=>t.slot.index-r.slot.index);return e.length>0?(this.openRuntime(e[0]),e[0]):this.ensureSlot()}ensureSlot(){let e=this.nextIndex++,r={slot:{index:e,concurrencyKey:this.slotKey(e)},state:"queued",entry:null,inFlight:0,idleSince:null,opening:null};return this.slots.push(r),this.openRuntime(r),r}openRuntime(e){e.opening||(e.state="queued",e.opening=(async()=>{try{let t=await this.opts.openSlot(e.slot);if(this.closed||this.draining){await this.opts.closeSlot(t).catch(()=>{}),this.signalDrain();return}e.entry=t,e.state="attached",e.idleSince=this.now(),this.pump()}catch(t){e.entry=null,e.state="paused",e.opening=null,this.opts.onDetach?.(e.slot,t instanceof Error?t.message:String(t)),this.pump();return}e.opening=null})())}async acquire(){if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Ze;this.lastDemandAt=this.now();let e=this.opts.acquireTimeoutMs??6e5,t=Date.now();for(;;){let r=this.tryLease();if(r)return r;if(this.draining)throw new Ze;if(!this.slots.some(u=>u.state==="queued")&&this.slots.length<this.opts.max){this.openForDemand();continue}let o=t+e-Date.now();if(o<=0)throw new en(e);let i,a={resolve:()=>{},settled:!1};try{await Promise.race([new Promise(u=>{a.resolve=u,this.waiters.push(a)}),new Promise(u=>{i=setTimeout(u,o)})])}finally{clearTimeout(i);let u=this.waiters.indexOf(a);u!==-1&&this.waiters.splice(u,1),a.settled=!0}if(this.closed)throw new Error("decision pool is closed");if(this.draining)throw new Ze}}tryAcquireReady(){if(this.closed)return null;let e=this.lastDemandAt===null?null:this.now()-this.lastDemandAt;this.lastDemandAt=this.now();let t=this.tryLease();return t||(!this.slots.some(r=>r.state==="queued")&&this.slots.length<this.opts.max&&this.openForDemand(),this.missCount+=1,e!==null&&e>this.idleGraceMs&&(this.missCountPastWindow+=1),this.lastMissAgeMs=e,null)}async pingReady(e){if(this.closed)return!1;for(let t=0;t<this.slots.length;t++){let r=this.slots[t];if(r.state!=="attached"||r.entry===null)continue;let s=r.entry;if(s===null||typeof s!="object"||!("session"in s))return!1;let o=s.session;if(typeof o!="object"||o===null||!("whenLive"in o))return!1;let i=o.whenLive;if(typeof i!="function")return!1;let a=r.entry;try{return await i.call(o,{timeout:e}),!0}catch{this.evict(a),r.entry!==null&&r.entry!==a&&t--;continue}}return!1}tryLease(){let e=null;for(let o of this.slots)o.state!=="attached"||o.inFlight>=this.opts.inFlightCap||(!e||o.inFlight<e.inFlight)&&(e=o);if(!e)return null;let t=e.entry;if(t===null)return null;let r=e;r.inFlight+=1;let s=!1;return{slot:r.slot,entry:t,release:()=>{s||(s=!0,r.inFlight=Math.max(0,r.inFlight-1),r.inFlight===0&&(r.idleSince=this.now()),this.pump(),this.reap(),this.signalDrain())}}}pump(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(!e.settled){e.settled=!0,e.resolve();return}}}evict(e){let t=this.slots.find(r=>r.entry===e);t&&(t.entry=null,t.state="paused",t.opening=null,this.opts.onDetach?.(t.slot,"runtime detached"),this.signalDrain())}reap(){if(this.closed||this.draining)return;let e=this.now(),t=this.slots.filter(r=>r.state==="attached"&&r.inFlight===0&&r.idleSince!==null&&e-r.idleSince>=this.idleGraceMs).sort((r,s)=>(r.idleSince??0)-(s.idleSince??0)||s.slot.index-r.slot.index);for(let r of t)this.endSlot(r)}endSlot(e){e.state="paused";let t=e.entry;e.entry=null,this.slots.splice(this.slots.indexOf(e),1),t&&this.opts.closeSlot(t).catch(()=>{})}stats(){let e=this.slots.filter(s=>s.state==="attached").length,t=this.slots.filter(s=>s.state==="queued").length,r=this.slots.filter(s=>s.state==="paused").length;return{requested:this.slots.length,attached:e,queued:t,paused:r,inFlight:this.slots.reduce((s,o)=>s+o.inFlight,0),draining:this.draining,misses:this.missCount,missesPastWindow:this.missCountPastWindow,lastMissAgeMs:this.lastMissAgeMs}}signalDrain(){if(!(!this.draining||this.drainComplete===null)&&this.slots.reduce((e,t)=>e+t.inFlight,0)===0){let e=this.drainComplete;this.drainComplete=null,e.resolve()}}async drain(e){if(!this.closed){this.draining=!0;for(let t of this.waiters.splice(0))t.settled||(t.settled=!0,t.resolve());if(this.slots.reduce((t,r)=>t+r.inFlight,0)>0){if(!this.drainComplete){let r,s=new Promise(o=>{r=o});this.drainComplete={promise:s,resolve:r}}let t=this.drainComplete;await Promise.race([t.promise,new Promise(r=>setTimeout(r,e?.timeoutMs??5e3))])}await this.close()}}async close(){this.closed=!0;for(let s of this.waiters.splice(0))s.settled||(s.settled=!0,s.resolve());let e=this.slots.map(s=>s.entry).filter(s=>s!==null);this.slots.length=0;let r=(await Promise.allSettled(e.map(s=>this.opts.closeSlot(s)))).filter(s=>s.status==="rejected");if(r.length>0)throw new Error(`failed to end ${r.length} decision pool session(s)`)}};A();A();var Y=class extends Error{};async function wt(n,e){let t=Number(n.headers["content-length"]??"0");if(Number.isFinite(t)&&t>e)throw new Y(`request body exceeds the ${e}-byte limit`);let r=[],s=0;for await(let o of n){let i=o;if(s+=i.length,s>e)throw new Y(`request body exceeds the ${e}-byte limit`);r.push(i)}return Buffer.concat(r)}async function vt(n,e){let t=n[Symbol.asyncIterator](),r=0,s=new ReadableStream({async pull(i){try{let a=await t.next();if(a.done){i.close();return}if(r+=a.value.length,r>e){i.error(new Y(`request body exceeds the ${e}-byte limit`));return}i.enqueue(a.value)}catch(a){i.error(a)}},cancel(){t.return?.()}}),o;try{let i=new Headers;for(let[d,l]of Object.entries(n.headers))if(typeof l=="string")i.set(d,l);else if(Array.isArray(l))for(let c of l)i.append(d,c);let a={method:"POST",headers:i,body:s,duplex:"half"};o=await new Request(`https://proxy.internal${n.url??"/"}`,a).formData()}catch(i){throw i instanceof Y?i:new Error(`malformed multipart body: ${String(i instanceof Error?i.message:i)}`)}return o}var nr="/v1/images/generations",bt="/v1/images/edits";function rr(n){return n===nr||n===bt}var sr="/v1/images/models";async function or(n,e,t){if(n){if(n.model=te({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}var M=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}},co=16*1024*1024,ir=64*1024*1024;function ar(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":null}function tt(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}async function ur(n,e,t,r){let s=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1},r),o=null;for await(let c of s){if(c.type==="error"){let v=c.error??{};throw new M(502,`image upstream error: ${String(v.message??"upstream reported an error")}`)}if(c.type==="response.completed"){o=c.response??null;break}}if(o===null)throw new M(502,"image upstream produced no terminal response \u2014 refusing to fabricate an image");let i=o.images;if(!Array.isArray(i)||i.length!==1||typeof i[0]!="string"||i[0].length===0)throw new M(502,`image upstream returned ${Array.isArray(i)?i.length:"a non-array images field"} images for the single-shot (n=1) contract, which produces exactly one \u2014 refusing to truncate or fabricate`);let a=[],u=i[0].startsWith("data:")?i[0].slice(i[0].indexOf(";base64,")+8):i[0],d=Buffer.from(u,"base64");if(ar(d)===null)throw new M(502,`image upstream returned a payload that is not a PNG/JPEG/WebP image (${d.length} bytes) \u2014 refusing to pass it through`);return a.push(u),{images:a}}function dr(n){return n instanceof M?n:n instanceof D?new M(404,n.message):new M(502,`image upstream failed: ${String(n instanceof Error?n.message:n)}`)}async function lr(n,e,t,r){if(await n(e,t))return!0;let s=t==="edit"?"no image-input (expects_image) edit destination":"no pure text-to-image (expects_image=false) generation destination";return tt(r,new M(404,e===void 0?`no image-capable default model is configured for this caller (${s}) \u2014 name an image-capable \`model\``:`model "${e}" is not ${t==="edit"?"edit-capable":"generation-capable"} for this caller (${s}; capability is read from the catalog's modality metadata, not the serve function name)`)),!1}function cr(n,e){n&&(n.outputUnits=e.images.length)}function pr(n,e){n.statusCode=200,n.setHeader("content-type","application/json"),n.end(JSON.stringify({created:Math.floor(Date.now()/1e3),data:e.images.map(t=>({b64_json:t}))}))}var po={model:!0,prompt:!0,response_format:!0,n:!0};async function mr(n,e,t){let r=t.maxBodyBytes??ir;try{if(n.method!=="POST")throw new M(405,`${String(n.method)} is not supported on ${nr}`);let s;try{s=JSON.parse((await wt(n,r)).toString("utf8")||"{}")}catch(c){throw c instanceof Y?new M(413,c.message):new M(400,"request body is not valid JSON")}if(s===null||typeof s!="object"||Array.isArray(s))throw new M(400,"request body must be a JSON object");let o=s;for(let c of Object.keys(o))if(!po[c])throw new M(400,`request field "${c}" is not implemented: the native image request schema carries only the prompt (size, quality, style, seed, mask and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, n.`,c);let i=o.prompt;if(typeof i!="string"||i.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string","prompt");let a=o.model===void 0?void 0:o.model;if(a!==void 0&&typeof a!="string")throw new M(400,"model must be a string","model");await or(t.turn,t.clients,a);let u=o.n??1;if(u!==1)throw new M(400,`n=${JSON.stringify(u)} is not supported: the native image request is single-shot and produces exactly one image per request (no batch support yet)`,"n");let d=o.response_format??"b64_json";if(d!=="b64_json")throw new M(400,`response_format ${JSON.stringify(d)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");if(t.stats?.request("images_generations",i.length,i.length),!await lr(t.imageModels,a,"generation",e))return;let l=[{type:"input_text",text:i}];try{let c=await ur(t.clients,a,l,t.turn?oe(t.turn):void 0);cr(t.turn,c),pr(e,c)}catch(c){throw dr(c)}}catch(s){if(s instanceof Y){tt(e,new M(413,s.message));return}if(s instanceof M){tt(e,s);return}throw s}}var mo={model:!0,prompt:!0,response_format:!0,image:!0,"image[]":!0};async function fr(n,e,t){let r=t.maxBodyBytes??ir,s=t.maxImagePartBytes??co;try{if(n.method!=="POST")throw new M(405,`${String(n.method)} is not supported on ${bt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new M(400,`the edit endpoint consumes multipart/form-data, got ${o||"none"}`);let i;try{i=await vt(n,r)}catch(p){throw p instanceof Y?new M(413,p.message):new M(400,String(p instanceof Error?p.message:p))}let a=i.get("prompt");if(typeof a!="string"||a.trim().length===0)throw new M(400,"prompt is required and must be a non-empty string field","prompt");let u=i.get("model");if(u!==null&&typeof u!="string")throw new M(400,"model must be a string field","model");let d=u===null?void 0:u;await or(t.turn,t.clients,d);let l=i.get("response_format")??"b64_json";if(l!=="b64_json")throw new M(400,`response_format ${JSON.stringify(l)} is not supported: the runtime returns bare base64 PNG and exposes no image hosting, so b64_json is the only output format`,"response_format");for(let p of i.keys())if(!mo[p])throw new M(400,`form field "${p}" is not implemented: the native image request schema carries the prompt and the image inputs only (mask, size, seed and similar knobs are per-deployment engine config, not per-request fields). Supported fields: model, prompt, response_format, image (or image[]).`,p);let c=[];for(let p of["image","image[]"])for(let x of i.getAll(p)){if(!(x instanceof File))throw new M(400,"image must be an uploaded file: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths",p);if(x.size>s)throw new M(413,`image part exceeds the ${s}-byte limit (the serve protocol's MAX_IMAGE_BYTES)`,p);let R=new Uint8Array(await x.arrayBuffer()),b=ar(R);if(b===null)throw new M(400,"image payload is not a supported format \u2014 supported: PNG, JPEG, WebP (detected by magic bytes, not the declared Content-Type)",p);c.push({bytes:R,mime:b})}if(c.length===0)throw new M(400,"the edit endpoint requires at least one `image` file part","image");if(t.stats?.request("images_edits",a.length,a.length),!await lr(t.imageModels,d,"edit",e))return;let v=[{type:"input_text",text:a}];for(let{bytes:p,mime:x}of c)v.push({type:"input_image",image_url:`data:${x};base64,${Buffer.from(p).toString("base64")}`});try{let p=await ur(t.clients,d,v,t.turn?oe(t.turn):void 0);cr(t.turn,p),pr(e,p)}catch(p){throw dr(p)}}catch(o){if(o instanceof Y){tt(e,new M(413,o.message));return}if(o instanceof M){tt(e,o);return}throw o}}A();var nt="/v1/audio/speech";function kr(n){return n===nt}var hr=4096,gr=18e4,_r=5e3,fo=64*1024*1024,yr=8,wr=5,vr=1024*1024,Fe="voice_applied",kt="X-Urun-Voice-Applied",T=class extends Error{status;param;retryAfterSeconds;constructor(e,t,r,s){super(t),this.status=e,this.param=r,this.retryAfterSeconds=s}};function tn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),e.retryAfterSeconds!==void 0&&n.setHeader("retry-after",String(e.retryAfterSeconds)),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}var St=class extends T{constructor(e){super(502,e)}};function Sr(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t!==9&&!(t>=32&&t<=126)&&!(t>=128&&t<=255))return!1}return!0}function Rr(n){return new T(502,`the runtime's ${Fe} receipt ${JSON.stringify(n)} cannot be relayed as the ${kt} header \u2014 it carries a character no HTTP header or trailer value can carry (a newline, another control character, or a non-Latin-1 character); the lane never serves an answer whose receipt it cannot deliver nor silently drops the runtime's own acknowledgment`)}async function ho(n,e,t){if(n){if(n.model=te({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Er(n,e){if(!n)return;let t=e/(24e3*2);n.outputUnits=t,n.outputMinutes=t/60}var go=2;function _o(n){for(let e=0;e+1<n.byteLength;e+=2)if(Math.abs(n.readInt16LE(e))>go)return!1;return!0}function yo(n){let e=24e3,t=2,r=1,s=Buffer.alloc(44);return s.write("RIFF",0,"ascii"),s.writeUInt32LE(36+n,4),s.write("WAVE",8,"ascii"),s.write("fmt ",12,"ascii"),s.writeUInt32LE(16,16),s.writeUInt16LE(1,20),s.writeUInt16LE(r,22),s.writeUInt32LE(e,24),s.writeUInt32LE(e*r*t,28),s.writeUInt16LE(r*t,32),s.writeUInt16LE(16,34),s.write("data",36,"ascii"),s.writeUInt32LE(n,40),s}var br=new WeakMap,xt=new WeakMap;function wo(n,e){let t=xt.get(n)??0;if(t>=yr)throw new T(503,`this model's speech queue is full \u2014 ${yr} requests are already admitted (one in-flight turn plus the queued depth) and each holds a pooled session turn; retry after ${wr}s`,void 0,wr);xt.set(n,t+1);let r=br.get(n)??Promise.resolve(),s,o=new Promise(i=>{s=i});return br.set(n,o),(async()=>{await r;try{return await e()}finally{xt.set(n,(xt.get(n)??1)-1),s()}})()}async function vo(n,e,t,r){if(typeof n.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned session after a failed turn \u2014 refusing loudly rather than handing the next request the failed turn\u2019s audio");try{await n.evictSpeechSession(e)}catch(i){if(!(i instanceof se))throw i}if(t?.return===void 0)return;let s=Promise.resolve(t.return()).then(()=>{},()=>{}),o;await Promise.race([s,new Promise(i=>{o=setTimeout(i,r)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}function Ee(n){return n instanceof T?n:n instanceof D?new T(404,n.message):new T(502,`speech upstream failed: ${String(n instanceof Error?n.message:n)}`)}async function xr(n,e,t,r,s,o,i,a){let u=a??(()=>{});return wo(e,async()=>{if(i?.()===!0)return null;let d=!1,l=!1,c=!1,v,p=new Promise(_=>{v=_}),x=[],R=()=>{l&&!c&&x.length>=s.quietRunFrames&&(c=!0,v())},b=e.onOutputAudio(_=>{let f=Buffer.from(_,"base64");if(f.byteLength===0)return;let y=_o(f);if(!d){if(y)return;d=!0}if(y){x.push(f),R();return}for(let P of x)u(P);x.length=0,u(f),R()}),m=null,h,g,E;try{E=(await n.createResponseOn(t,{model:r.model,input:[{role:"user",content:[{type:"input_text",text:r.text}]}],stream:!1,...r.voice!==void 0?{voice:r.voice}:{}}))[Symbol.asyncIterator]();let f=new Promise(w=>{g=setTimeout(w,o.capMs)}),y=!1;for(;;){let w=E.next(),I=await Promise.race([w,f]);if(I===void 0){y=!0,w.catch(()=>{});break}if(I.done)break;let C=I.value;if(C.type==="error"){let $=C.error??{};throw await E.return?.(),new T(502,`speech upstream error: ${String($.message??"upstream reported an error")}`)}if(C.type==="response.completed"){m=C.response??null,l=!0,R(),await E.return?.();break}}if(clearTimeout(g),y)throw new T(504,`the speech turn produced no terminal event within ${o.capMs}ms \u2014 the upstream stream never completed, so the pinned speech session is evicted (the next request opens a fresh one), the serialized lane is released and the caller can retry; a stuck turn must not hold every later request on this lane`);if(m===null)throw new T(502,"speech upstream produced no terminal response \u2014 refusing to fabricate audio");let P=!1;if(await Promise.race([p,new Promise(w=>{h=setTimeout(()=>{P=!0,w()},s.capMs)})]),h!==void 0&&clearTimeout(h),r.voice!==void 0){let w=m[Fe];if(typeof w!="string"||w!==r.voice){let I=`the runtime did not acknowledge the requested voice ${JSON.stringify(r.voice)} \u2014 the terminal response carried ${typeof w=="string"?`${Fe} ${JSON.stringify(w)}`:`no ${Fe} field`}; the speak-bridge companion is not deployed, and this lane never serves default-voice audio as the requested voice`;throw c?new St(I):new T(502,I)}}if(!d)throw new T(502,"the upstream produced no voice for this utterance \u2014 refusing to serve silence as success");if(P&&!c&&x.length<1)throw new T(502,`the upstream audio stream did not quiesce within ${s.capMs}ms of the turn's end (voiced frames still arriving) \u2014 refusing to serve audio whose tail cannot be vouched for`);return m}catch(_){throw _ instanceof St||await vo(n,t,E,o.returnBoundMs),_}finally{h!==void 0&&clearTimeout(h),g!==void 0&&clearTimeout(g),b()}})}function bo(n,e,t,r){let s=!1,o=0,i=a=>{n.destroy(a instanceof Error?a:new Error(String(a)))};return{sink(a){t()||(s||(s=!0,n.statusCode=200,n.setHeader("content-type","audio/pcm"),r&&n.setHeader("trailer",kt)),n.write(a,u=>{u||(o+=a.byteLength,Er(e,o))}),n.writableLength>vr&&(e&&(e.streamError=!0),i(new Error(`the streamed pcm answer's undrained buffer crossed ${vr} bytes (1 MiB \u2014 about 21 s of 24 kHz mono PCM16): the caller stopped reading the stream, and the lane bounds what it will buffer for one answer rather than let a stalled reader hold the process's memory; the transfer is aborted (an after-first-byte failure \u2014 the bytes whose writes the socket confirmed are billed) and the caller should retry when it can drain the audio as it arrives`))))},started:()=>s,async finish(a){if(!t()){if(r){let u=a[Fe];if(typeof u=="string"){if(!Sr(u))throw Rr(u);n.addTrailers({[kt]:u})}}await new Promise(u=>{n.end(()=>u())})}},fail:i}}async function xo(n,e,t){let r;try{r=await n(e)}catch(s){throw Ee(s)}return r?!0:(tn(t,new T(404,e===void 0?"no speech-capable default model is configured for this caller (catalog task tts) \u2014 name a tts model":`model "${e}" is not speech-capable (catalog task is not tts) \u2014 this lane serves only text-to-speech models; chat models ride /v1/chat/completions`)),!1)}var ko={model:!0,input:!0,voice:!0,response_format:!0,stream_format:!0,speed:!0,instructions:!0},So="wav, pcm";async function Ir(n,e,t){let r=t.maxBodyBytes??fo,s=!1;e.once("close",()=>{s=!0});let o=()=>s||e.destroyed;try{if(n.method!=="POST")throw new T(405,`${String(n.method)} is not supported on ${nt}`);let i;try{i=JSON.parse((await wt(n,r)).toString("utf8")||"{}")}catch(g){throw g instanceof Y?new T(413,g.message):new T(400,"request body is not valid JSON")}if(i===null||typeof i!="object"||Array.isArray(i))throw new T(400,"request body must be a JSON object");let a=i;for(let g of Object.keys(a))if(!ko[g])throw new T(400,`request field "${g}" is not implemented: the speech request schema carries the utterance and its voice (the qwen3 backend fixes voice style at deploy time, and sample rate is pinned to the engine's native 24 kHz mono). Supported fields: model, input, voice, response_format, stream_format, speed, instructions.`,g);let u=a.input;if(typeof u!="string"||u.trim().length===0)throw new T(400,"input is required and must be a non-empty string","input");if(u.length>hr)throw new T(400,`input is ${u.length} chars \u2014 over the ${hr}-char limit (one utterance; the backend bounds generation text-shaped, and an unbounded text is an unbounded synthesis)`,"input");let d=a.model===void 0?void 0:a.model;if(d!==void 0&&typeof d!="string")throw new T(400,"model must be a string","model");let l=a.voice;if(l!==void 0&&(typeof l!="string"||l.trim().length===0))throw new T(400,"voice must be a non-empty string","voice");if(typeof t.clients.speechVoices!="function")throw new T(501,`the speech lane needs a router-backed client (speechVoices) to resolve the voice set GET /v1/models publishes \u2014 refusing loudly rather than validating voices of ${nt} against a stale copy of the list`);let c;try{c=await t.clients.speechVoices(d)}catch(g){throw Ee(g)}if(c.defect!==null)throw new T(500,`the voice set for this model cannot be resolved: ${c.defect} \u2014 fix the catalog row; the lane refuses to serve rather than validate against a set nobody vouched`);let v=typeof l=="string"?l:void 0;if(v!==void 0&&c.published.length>0&&!c.published.includes(v))throw new T(400,`voice ${JSON.stringify(v)} is not one of the voices this model publishes \u2014 accepted voices: ${c.published.join(", ")}`,"voice");let p=a.response_format??"wav";if(p!=="wav"&&p!=="pcm")throw new T(400,`response_format ${JSON.stringify(p)} is not supported: this lane serves the engine's raw 24 kHz mono PCM16, so the supported formats are ${So} \u2014 and the lane will not label bytes with a format it did not encode`,"response_format");if(a.stream_format!==void 0&&typeof a.stream_format!="string")throw new T(400,"stream_format, when present, must be a string","stream_format");let x=a.speed;if(x!==void 0){if(typeof x!="number"||!Number.isFinite(x))throw new T(400,"speed, when present, must be a number","speed");if(x!==1)throw new T(400,`speed=${JSON.stringify(x)} is not supported: the backend exposes no speed knob (the qwen3 engine's speaking rate is fixed), so a non-default speed would be silently ignored \u2014 1 (the OpenAI default) is the only accepted value`,"speed")}let R=a.instructions;if(R!==void 0){if(typeof R!="string")throw new T(400,"instructions, when present, must be a string","instructions");if(R.trim().length>0)throw new T(400,"instructions are not supported: the backend fixes the voice style (instruct) at deploy time, so a per-request instruction would be silently ignored \u2014 the deployment speaks with its configured style","instructions")}await ho(t.turn,t.clients,d);let b=Buffer.byteLength(JSON.stringify(a));if(t.stats?.request("audio_speech",b,b),!await xo(t.speechModels,d,e))return;if(typeof t.clients.openAudioOn!="function")throw new T(501,"a speech-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the same session identity as the response turn \u2014 refusing loudly rather than answering an utterance whose audio cannot be collected");if(typeof t.clients.speechSessionHandle!="function")throw new T(501,"a speech-capable model needs a router-backed client (speechSessionHandle) to resolve the speech lane's own pooled session \u2014 one no interactive binding shares, because the per-session audio bridge broadcasts every output frame to every subscriber \u2014 refusing loudly rather than collecting speech audio on a session a realtime/gemini lane can be speaking on");if(typeof t.clients.evictSpeechSession!="function")throw new T(501,"a speech-capable model needs a router-backed client (evictSpeechSession) to retire its pinned speech session after a failed turn (a turn-cap timeout above all) \u2014 without it, the next request on the same model would silently collect the failed turn\u2019s still-emitting audio; refusing loudly rather than serving on an un-evictable speech slot");if(o())return;let m;try{m=await t.clients.speechSessionHandle(d)}catch(g){throw Ee(g)}let h;try{h=await t.clients.openAudioOn(m)}catch(g){throw Ee(g)}t.turn&&(t.turn.sessionId=h.sessionId);try{if(p==="wav"){let g=[],E=await xr(t.clients,h,m,{model:d,text:u,...v!==void 0?{voice:v}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??gr,returnBoundMs:t.turnReturnBoundMs??_r},o,f=>g.push(f));if(E===null||o())return;let _=Buffer.concat(g);if(v===void 0){let f=E[Fe];if(typeof f=="string"){if(!Sr(f))throw Rr(f);e.setHeader(kt,f)}}Er(t.turn,_.byteLength),e.statusCode=200,e.setHeader("content-type","audio/wav"),e.end(Buffer.concat([yo(_.byteLength),_]))}else{let g=bo(e,t.turn,o,v===void 0),E;try{E=await xr(t.clients,h,m,{model:d,text:u,...v!==void 0?{voice:v}:{}},{quietRunFrames:t.quietRunFrames??3,capMs:t.drainCapMs??2e3},{capMs:t.turnCapMs??gr,returnBoundMs:t.turnReturnBoundMs??_r},o,g.sink)}catch(_){let f=Ee(_);if(!g.started())throw f;t.turn&&(t.turn.streamError=!0),g.fail(f);return}if(E===null)return;try{await g.finish(E)}catch(_){let f=Ee(_);t.turn&&(t.turn.streamError=!0),g.fail(f);return}}}catch(g){throw Ee(g)}}catch(i){if(i instanceof Y){tn(e,new T(413,i.message));return}if(i instanceof T){tn(e,i);return}throw i}}A();var Rt="/v1/audio/transcriptions";function Ar(n){return n===Rt}var Or="/v1/audio/models",Ro=16*1024*1024,Eo=64*1024*1024,F=class extends Error{status;param;constructor(e,t,r){super(t),this.status=e,this.param=r}};function nn(n,e){n.statusCode=e.status,n.setHeader("content-type","application/json"),n.end(JSON.stringify({error:{message:e.message,type:e.status>=500?"upstream_error":"invalid_request_error",...e.param?{param:e.param}:{}}}))}function Tr(n){return n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===65&&n[10]===86&&n[11]===69}function Io(n){if(!Tr(n))return null;let e=12,t=null,r=null;for(;e+8<=n.length;){let o=String.fromCharCode(n[e],n[e+1],n[e+2],n[e+3]),i=(n[e+4]|n[e+5]<<8|n[e+6]<<16|n[e+7]<<24)>>>0,a=e+8;if(o==="fmt "&&a+16<=n.length){let u=n[a+2]|n[a+3]<<8,d=(n[a+4]|n[a+5]<<8|n[a+6]<<16|n[a+7]<<24)>>>0,l=n[a+14]|n[a+15]<<8;t={sampleRate:d,channels:u,bitsPerSample:l}}else if(o==="data"){let u=n.length-a;r=Math.min(i===0||i===4294967295?u:i,u)}e=a+i+i%2}if(t===null||r===null||r===0||t.sampleRate===0||t.channels===0||t.bitsPerSample===0)return null;let s=r/(t.sampleRate*t.channels*(t.bitsPerSample/8));return!Number.isFinite(s)||s<0?null:{seconds:s,sampleRate:t.sampleRate,channels:t.channels,bitsPerSample:t.bitsPerSample}}async function Ao(n,e,t){if(n){if(n.model=te({model:t}),n.stream=!1,typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}}function Oo(n,e){n&&(n.outputUnits=e.seconds)}async function To(n,e,t,r,s){let o=await n.createResponse({model:e,input:[{role:"user",content:t}],stream:!1,...r!==void 0?{language:r}:{}},s),i=[],a=null;for await(let u of o){if(i.push(u),u.type==="error"){let d=u.error??{},l=typeof d.type=="string"?d.type:"upstream_error",c=String(d.message??"upstream reported an error");throw new F(l==="invalid_request_error"?400:502,`transcription upstream error: ${c}`)}if(u.type==="response.completed"){a=u.response??null;break}}if(a===null)throw new F(502,"transcription upstream produced no terminal response \u2014 refusing to fabricate a transcript");return Ue(i,a)}function Pr(n){return n instanceof F?n:n instanceof D?new F(404,n.message):new F(502,`transcription upstream failed: ${String(n instanceof Error?n.message:n)}`)}async function Po(n,e,t){let r;try{r=await n(e)}catch(s){throw Pr(s)}return r?!0:(nn(t,new F(404,e===void 0?"no transcription-capable default model is configured for this caller (catalog task stt) \u2014 name an stt model":`model "${e}" is not transcription-capable (catalog task is not stt) \u2014 this lane serves only speech-to-text models; tts models ride /v1/audio/speech and chat models ride /v1/chat/completions`)),!1)}var Co=new Set(["file","model","language","response_format"]);async function Cr(n,e,t){let r=t.maxBodyBytes??Eo,s=t.maxAudioPartBytes??Ro;try{if(n.method!=="POST")throw new F(405,`${String(n.method)} is not supported on ${Rt}`);let o=String(n.headers["content-type"]??"");if(!o.toLowerCase().startsWith("multipart/form-data"))throw new F(400,`the transcriptions endpoint consumes multipart/form-data, got ${o||"none"}`);let i;try{i=await vt(n,r)}catch(m){throw m instanceof Y?new F(413,m.message):new F(400,String(m instanceof Error?m.message:m))}let a=new Map;for(let m of i.keys()){if(!Co.has(m))throw new F(400,`form field "${m}" is not implemented: the native transcription request carries the audio clip and a language hint only (prompt, temperature, timestamps and similar knobs have no native surface on this lane). Supported fields: file, model, language, response_format.`,m);a.set(m,(a.get(m)??0)+1)}for(let[m,h]of a)if(h>1)throw new F(400,`form field "${m}" appears ${h} times: the lane reads exactly one value per field, and a repeat is refused rather than silently discarded \u2014 resend the request with each field once`,m);let u=i.get("model");if(u!==null&&typeof u!="string")throw new F(400,"model must be a string field","model");let d=u===null?void 0:u,l=i.get("language");if(l!==null&&(typeof l!="string"||l.trim().length===0))throw new F(400,"language, when present, must be a non-empty string","language");let c=l===null?void 0:l,v=i.get("response_format")??"json";if(v!=="json")throw new F(400,`response_format ${JSON.stringify(v)} is not supported: timestamps/segments are not produced on this lane yet \u2014 the runtime answers terminal transcript text only, so json is the only output format`,"response_format");let p=i.get("file");if(!(p instanceof File))throw new F(400,"file must be an uploaded WAV: the proxy accepts only multipart file bytes and never fetches URLs or server-side paths","file");if(p.size>s)throw new F(413,`file part exceeds the ${s}-byte limit (the serve protocol's MAX_AUDIO_BYTES)`,"file");let x=new Uint8Array(await p.arrayBuffer());if(!Tr(x))throw new F(400,"the audio payload is not a RIFF/WAVE container \u2014 this lane accepts WAV uploads only (detected by magic bytes, not the declared Content-Type); the runtime decodes PCM16 WAV and nothing else","file");let R=Io(x);if(R===null)throw new F(400,"the WAV header cannot be read (no fmt /data chunk pair, or a zero rate/channel/depth) \u2014 the runtime decodes RIFF/WAVE PCM16 and this container cannot be honestly decoded or billed","file");if(await Ao(t.turn,t.clients,d),t.stats?.request("audio_transcriptions",x.length,x.length),!await Po(t.transcriptionModels,d,e))return;let b=[{type:"input_audio",input_audio:{data:Buffer.from(x).toString("base64"),format:"wav"}}];try{let m=await To(t.clients,d,b,c,t.turn?oe(t.turn):void 0);Oo(t.turn,R),e.statusCode=200,e.setHeader("content-type","application/json"),e.end(JSON.stringify({text:m}))}catch(m){throw Pr(m)}}catch(o){if(o instanceof Y){nn(e,new F(413,o.message));return}if(o instanceof F){nn(e,o);return}throw o}}A();var Nr="/v1/usage/requests",Mr=1e4,Mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ye=class extends Error{constructor(t,r=400){super(t);this.status=r;this.name="UsageRequestError"}status},V=class extends Error{constructor(e){super(e),this.name="UsageSurfaceError"}},Et=class extends V{constructor(e){super(e),this.name="UsageWithholdingError"}},Fr=1024*1024;function on(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new ye(`request body must be a JSON object of the form {"${e}": ["<uuid>", ...]}`);let t=n[e];if(!Array.isArray(t))throw new ye(`"${e}" must be an array of uuid strings`);if(t.length>Mr)throw new ye(`"${e}" carries ${t.length} ids; at most ${Mr} may be looked up in one request. Split the batch \u2014 the ids past the limit are NOT silently dropped`);let r=[],s=new Set;for(let o of t){if(typeof o!="string"||!Mo.test(o))throw new ye(`"${e}" contains ${JSON.stringify(o)}, which is not a LOWERCASE uuid \u2014 every uRun inference id is the lowercase uuid returned in the \`Inference-Id\` response header, and answering a differently-cased spelling would echo back an id the caller cannot match`);s.has(o)||(s.add(o),r.push(o))}return r}function Dr(n){return on(n,"inference_ids")}var Lo=["inference_id","model_id","identity_kind","variant","task","http_status","started_at","completed_at","prompt_tokens","completion_tokens","output_units","output_minutes","cost_nano_usd","price_version","priced_at"];function De(n,e,t){let r=n[e];if(typeof r!="string"||r==="")throw new V(`${t}: ${e} is not a non-empty string (got ${Be(r)})`);return r}function rn(n,e,t){let r=n[e];if(r===null)return null;if(typeof r!="string"||r==="")throw new V(`${t}: ${e} is neither null nor a non-empty string (got ${Be(r)})`);return r}function qe(n,e,t,r){let s=n[e];if(s===null)return null;let o=typeof s=="number"?s:typeof s=="string"&&/^-?\d+(\.\d+)?$/.test(s.trim())?Number(s.trim()):NaN;if(!Number.isFinite(o))throw new V(`${t}: ${e} is not a number (got ${Be(s)})`);if(r&&!Number.isSafeInteger(o))throw new V(`${t}: ${e} is not a safely representable integer \u2014 a billing quantity that silently loses digits must fail rather than be reported`);if(o<0)throw new V(`${t}: ${e} is negative`);return Object.is(o,-0)?0:o}var Uo=40,Lr=64,Ur=600;function qr(n){let e=Object.keys(n).sort(),r=e.slice(0,Uo).map(s=>s.length>Lr?`${s.slice(0,Lr)}\u2026`:s).join(", ");return r.length>Ur&&(r=`${r.slice(0,Ur)}\u2026`),`${e.length} keys present: [${r}]`}function Be(n){return n===null?"null":n===void 0?"undefined":Array.isArray(n)?"an array":typeof n=="object"?"an object":`a ${typeof n}`}function sn(n){ge(process.stdout,`${JSON.stringify({event:"usage_row_rejected",ts:new Date().toISOString(),where:n.where,reason:n.reason})}
|
|
24
|
-
`)}function $o(n,e){let t;try{t=n(e)}catch{$r(n,e);return}No(t)&&Promise.resolve(t).catch(()=>{$r(n,e)})}function No(n){return typeof n?.then=="function"}function $r(n,e){if(n!==sn)try{sn(e)}catch{}}function xu(n,e=sn){let t=n?.requests;if(!Array.isArray(t)){let s=n!==null&&typeof n=="object"&&!Array.isArray(n)?qr(n):Be(n);throw new V(`the usage surface answered without a "requests" array: got ${Be(t)} (${s})`)}let r=[];for(let s=0;s<t.length;s++){let o=`usage.requests[${s}]`;try{r.push(Fo(t[s],o))}catch(i){if(i instanceof Et||!(i instanceof V))throw i;$o(e,{where:o,reason:i.message})}}if(t.length>0&&r.length===0)throw new V(`the usage surface returned ${t.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Fo(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new V(`${e} is not an object: got ${Be(n)}`);let t=n;if(Object.hasOwn(t,"gpu_seconds"))throw new Et(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let s of Lo)if(!Object.hasOwn(t,s))throw new V(`${e} has no "${s}" column (${qr(t)})`);let r=qe(t,"http_status",e,!0);if(r===null)throw new V(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:De(t,"inference_id",e),model_id:De(t,"model_id",e),identity_kind:De(t,"identity_kind",e),variant:rn(t,"variant",e),task:De(t,"task",e),http_status:r,started_at:De(t,"started_at",e),completed_at:De(t,"completed_at",e),prompt_tokens:qe(t,"prompt_tokens",e,!0),completion_tokens:qe(t,"completion_tokens",e,!0),output_units:qe(t,"output_units",e,!1),output_minutes:qe(t,"output_minutes",e,!1),cost_nano_usd:qe(t,"cost_nano_usd",e,!0),price_version:rn(t,"price_version",e),priced_at:rn(t,"priced_at",e)}}function It(n,e){let t=new Set(e),r=new Set;for(let s=0;s<n.length;s++){let o=n[s];if(!t.has(o.inference_id))throw new V(`the usage surface returned an id at validated answer position ${s} that was not in the request (${e.length} asked, ${n.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(o.inference_id))throw new V(`the usage surface returned ${o.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(o.inference_id)}}import{SessionAllocationError as ci,SessionFailedError as pi}from"@urun-sh/core";A();import{SessionFailedError as Br}from"@urun-sh/core";var pe=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},Do=33e4;function Iu(n,e=Do){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,o=new Promise((d,l)=>{s=l}),i=setTimeout(()=>s(new At),e),a;try{a=await Promise.race([r.next(),o])}catch(d){throw d instanceof se||d instanceof Br&&d.kind==="transport-failed"?d:d instanceof At?(await r.return?.(void 0),new pe("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new pe("upstream_threw",`decision stream failed: ${String(d instanceof Error?d.message:d)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new pe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var At=class extends Error{constructor(){super("stream idle timeout")}};function Au(n){return n instanceof pe?!1:n instanceof se?!0:n instanceof Br?n.kind==="transport-failed":!1}A();var an="/partners/huggingface/v1/billing/requests";function qo(n){return on(n,"requestIds")}function Bo(n){return n>=200&&n<=399}function jo(n){let e=[];for(let t of n)t.cost_nano_usd!==null&&Bo(t.http_status)&&e.push({requestId:t.inference_id,costNanoUsd:t.cost_nano_usd});return{requests:e.length>0?e:null}}async function jr(n,e){let t=qo(n),r=await e(t);return It(r,t),jo(r)}A();var Go={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Ho(n){return Go[n]??null}var Jr=["duplicate","duplicate_foreign","auth","surface","unknown","dwell_expired","dropped_on_exit"];function Jo(n){let e=n?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Wo(n){return n==="surface"}function Vo(n){let e=n?.ledgerFailureReason;return Jr.includes(e)?e:"unknown"}var Ko=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Gr=["priced","unpriced"],zo={written:Gr,already_written:Gr,skipped:Ko,failed:Jr},Uu=Object.entries(zo).flatMap(([n,e])=>e.map(t=>({outcome:n,reason:t})));function Yo(n){return n.status===null?!1:n.status>=200&&n.status<400&&!n.stream_error}function Xo(n){let e=Date.parse(n.ts),t=Number.isFinite(n.duration_ms)?Math.max(0,n.duration_ms):0;return new Date(e-Math.round(t)).toISOString()}var Qo=256,Hr=4096,rt=12e4,Zo=250,ei=8e3,me=[],un=new Set,st=0,je=!1;function $u(){return me.length}function Nu(n=Date.now()){let e=me[0];return e===void 0?0:Math.max(0,n-e.queuedAt)}var Ot=new Set;function Wr(){return st===0&&me.length===0}function Vr(){if(Wr()){je=!1;for(let n of[...Ot])n()}}async function Fu(n=Kr){return Wr()?!0:await new Promise(e=>{let t=null,r=()=>{Ot.delete(r),t&&clearTimeout(t),e(!0)};Ot.add(r),t=setTimeout(()=>{Ot.delete(r),e(!1)},n),t.unref?.()})}function Du(){je=!0;let n=[...me.splice(0,me.length),...un];for(let e of n)e.settled||Ie(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Kr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Vr(),n.length}var Kr=5e3;function zr(n,e){return`${JSON.stringify({event:n,ts:new Date().toISOString(),...e})}
|
|
24
|
+
`)}function $o(n,e){let t;try{t=n(e)}catch{$r(n,e);return}No(t)&&Promise.resolve(t).catch(()=>{$r(n,e)})}function No(n){return typeof n?.then=="function"}function $r(n,e){if(n!==sn)try{sn(e)}catch{}}function xu(n,e=sn){let t=n?.requests;if(!Array.isArray(t)){let s=n!==null&&typeof n=="object"&&!Array.isArray(n)?qr(n):Be(n);throw new V(`the usage surface answered without a "requests" array: got ${Be(t)} (${s})`)}let r=[];for(let s=0;s<t.length;s++){let o=`usage.requests[${s}]`;try{r.push(Fo(t[s],o))}catch(i){if(i instanceof Et||!(i instanceof V))throw i;$o(e,{where:o,reason:i.message})}}if(t.length>0&&r.length===0)throw new V(`the usage surface returned ${t.length} row(s) and NONE of them could be validated \u2014 answering an empty result here would be indistinguishable from "we hold nothing for these ids", which a billing caller treats as final and writes the whole batch off unbilled`);return r}function Fo(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new V(`${e} is not an object: got ${Be(n)}`);let t=n;if(Object.hasOwn(t,"gpu_seconds"))throw new Et(`${e} carries gpu_seconds \u2014 that column was DROPPED from the ledger (ENG-417): the cost of compute is metered once, on the instance, and a per-request figure counts the same GPU-second twice. Its reappearance means a second, competing measure has been reintroduced upstream`);for(let s of Lo)if(!Object.hasOwn(t,s))throw new V(`${e} has no "${s}" column (${qr(t)})`);let r=qe(t,"http_status",e,!0);if(r===null)throw new V(`${e}: http_status is null, but the ledger column is NOT NULL`);return{inference_id:De(t,"inference_id",e),model_id:De(t,"model_id",e),identity_kind:De(t,"identity_kind",e),variant:rn(t,"variant",e),task:De(t,"task",e),http_status:r,started_at:De(t,"started_at",e),completed_at:De(t,"completed_at",e),prompt_tokens:qe(t,"prompt_tokens",e,!0),completion_tokens:qe(t,"completion_tokens",e,!0),output_units:qe(t,"output_units",e,!1),output_minutes:qe(t,"output_minutes",e,!1),cost_nano_usd:qe(t,"cost_nano_usd",e,!0),price_version:rn(t,"price_version",e),priced_at:rn(t,"priced_at",e)}}function It(n,e){let t=new Set(e),r=new Set;for(let s=0;s<n.length;s++){let o=n[s];if(!t.has(o.inference_id))throw new V(`the usage surface returned an id at validated answer position ${s} that was not in the request (${e.length} asked, ${n.length} answered) \u2014 an answer carrying ids nobody asked about cannot be attributed to this caller`);if(r.has(o.inference_id))throw new V(`the usage surface returned ${o.inference_id} more than once \u2014 inference_id is the ledger primary key, so a duplicate means the upstream query is not the one we asked, and a caller that sums the entries would bill the request twice`);r.add(o.inference_id)}}import{SessionAllocationError as ci,SessionFailedError as pi}from"@urun-sh/core";A();import{SessionFailedError as Br}from"@urun-sh/core";var pe=class extends Error{kind;code;retryable;constructor(e,t,r,s){super(t),this.name="DecisionStreamError",this.kind=e,this.code=r,this.retryable=s,Object.setPrototypeOf(this,new.target.prototype)}},Do=33e4;function Iu(n,e=Do){return(async function*(){let r=n[Symbol.asyncIterator]();for(;;){let s,o=new Promise((d,l)=>{s=l}),i=setTimeout(()=>s(new At),e),a;try{a=await Promise.race([r.next(),o])}catch(d){throw d instanceof se||d instanceof Br&&d.kind==="transport-failed"?d:d instanceof At?(await r.return?.(void 0),new pe("upstream_idle_timeout",`decision lane produced no event for ${e}ms (upstream wedged) \u2014 the session is untouched; retry this decision`,"upstream_idle_timeout",!0)):new pe("upstream_threw",`decision stream failed: ${String(d instanceof Error?d.message:d)}`,"upstream_threw",!1)}finally{clearTimeout(i)}if(a.done)return;let u=a.value;if(typeof u=="object"&&u!==null&&"type"in u&&u.type==="error")throw new pe("upstream_error","decision stream ended with an upstream error event","upstream_error",!1);yield u}})()}var At=class extends Error{constructor(){super("stream idle timeout")}};function Au(n){return n instanceof pe?!1:n instanceof se?!0:n instanceof Br?n.kind==="transport-failed":!1}A();var an="/partners/huggingface/v1/billing/requests";function qo(n){return on(n,"requestIds")}function Bo(n){return n>=200&&n<=399}function jo(n){let e=[];for(let t of n)t.cost_nano_usd!==null&&Bo(t.http_status)&&e.push({requestId:t.inference_id,costNanoUsd:t.cost_nano_usd});return{requests:e.length>0?e:null}}async function jr(n,e){let t=qo(n),r=await e(t);return It(r,t),jo(r)}A();var Go={"/v1/chat/completions":"conversational","/v1/responses":"conversational","/v1/messages":"conversational","/v1/systemone":"conversational","/v1/images/generations":"text-to-image","/v1/images/edits":"image-to-image","/v1/audio/speech":"text-to-speech","/v1/audio/transcriptions":"speech-to-text"};function Ho(n){return Go[n]??null}var Jr=["duplicate","duplicate_foreign","auth","ledger_signature_invalid","surface","unknown","dwell_expired","dropped_on_exit"];function Jo(n){let e=n?.ledgerAlreadyWritten;return e!==null&&typeof e=="object"?e:null}function Wo(n){return n==="surface"}function Vo(n){let e=n?.ledgerFailureReason;return Jr.includes(e)?e:"unknown"}var Ko=["no_response_head","no_org","model_unresolved","no_model_named","queue_full"],Gr=["priced","unpriced"],zo={written:Gr,already_written:Gr,skipped:Ko,failed:Jr},Uu=Object.entries(zo).flatMap(([n,e])=>e.map(t=>({outcome:n,reason:t})));function Yo(n){return n.status===null?!1:n.status>=200&&n.status<400&&!n.stream_error}function Xo(n){let e=Date.parse(n.ts),t=Number.isFinite(n.duration_ms)?Math.max(0,n.duration_ms):0;return new Date(e-Math.round(t)).toISOString()}var Qo=256,Hr=4096,rt=12e4,Zo=250,ei=8e3,me=[],un=new Set,st=0,je=!1;function $u(){return me.length}function Nu(n=Date.now()){let e=me[0];return e===void 0?0:Math.max(0,n-e.queuedAt)}var Ot=new Set;function Wr(){return st===0&&me.length===0}function Vr(){if(Wr()){je=!1;for(let n of[...Ot])n()}}async function Fu(n=Kr){return Wr()?!0:await new Promise(e=>{let t=null,r=()=>{Ot.delete(r),t&&clearTimeout(t),e(!0)};Ot.add(r),t=setTimeout(()=>{Ot.delete(r),e(!1)},n),t.unref?.()})}function Du(){je=!0;let n=[...me.splice(0,me.length),...un];for(let e of n)e.settled||Ie(e,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:e.attempts,error:`the proxy is shutting down and this row was still unplaced after the ${Kr}ms drain \u2014 the request was served and answered, and its billing row was never written`});return Vr(),n.length}var Kr=5e3;function zr(n,e){return`${JSON.stringify({event:n,ts:new Date().toISOString(),...e})}
|
|
25
25
|
`}function ti(n){ge(process.stdout,n)}function Yr(n,e){try{n(e)}catch{}}function Xr(n){let{record:e,ledger:t}=n;if(t===null)return;let r=t.report??ti,s=Ho(e.path);if(s===null)return;let o=l=>{try{t.observe(l)}catch{}},i=(l,c)=>{o({outcome:"skipped",reason:l}),Yr(r,zr("inference_ledger_skipped",{inference_id:e.inference_id,path:e.path,reason:l,detail:c}))};if(e.status===null){i("no_response_head","no head flushed, so the caller never received an Inference-Id and no status can be recorded honestly");return}if(e.org===null){i("no_org","the request never resolved a tenant, so there is no org to attribute the row to");return}let a=e.catalog;if(a.kind==="unresolved"){i("model_unresolved",a.reason);return}let u;if(a.kind==="catalog")u={model_id:a.model_id,identity_kind:"catalog_model",variant:a.variant};else{if(a.model===null){i("no_model_named","the request resolved to a caller-org app but named no model, so there is no app slug to record and `model_id` cannot be written honestly");return}u={model_id:a.model,identity_kind:"caller_org_app",variant:null}}let d={inference_id:e.inference_id,...u,task:s,http_status:e.status,started_at:Xo(e),completed_at:e.ts,billable_outcome:Yo(e),session_id:e.session_id,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,output_units:e.output_units,output_minutes:e.output_minutes,queue_ms:e.queue_ms,prefill_ms:e.prefill_ms,decode_ms:e.decode_ms,total_ms:e.total_ms,ttft_ms:e.ttft_ms===null?null:Math.round(e.ttft_ms),e2e_ms:Math.round(e.duration_ms)};if(me.length>=Hr){i("queue_full",`${me.length} ledger writes are already waiting (capacity ${Hr}, ${st} in flight) \u2014 the control plane is not draining them fast enough and this row is lost`);return}me.push({entry:d,req:n.req,record:e,ledger:t,report:r,queuedAt:Date.now(),attempts:0,settled:!1}),st<Qo&&(st+=1,ni())}async function ni(){try{for(;;){let n=ri();if(n===void 0)return;un.add(n);try{await si(n)}finally{un.delete(n)}}}finally{st-=1,Vr()}}function ri(){let n=Date.now();for(;;){let e=me.shift();if(e===void 0)return;let t=n-e.queuedAt;if(t<rt)return e;Ie(e,{outcome:"failed",reason:"dwell_expired"},{event:"inference_ledger_write_failed",reason:"dwell_expired",error:`this row waited ${t}ms for the control plane (bound ${rt}ms) after ${e.attempts} attempt(s) and was given up on \u2014 the request was served and answered, and it will never be billed. Hugging Face writes a request off ~30 minutes after serving, so a row placed later than this is not worth the memory to keep trying`})}}async function si(n){let{entry:e,record:t,ledger:r}=n;for(;;){n.attempts+=1;try{let s=await r.write(n.req,e);Ie(n,{outcome:"written",reason:s.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_written",inference_id:s.inference_id,path:t.path,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,org:t.org,session_id:e.session_id,cost_nano_usd:s.cost_nano_usd,price_version:s.price_version,unpriced_reason:s.unpriced_reason,attempts:n.attempts});return}catch(s){let o=Jo(s);if(o!==null){Ie(n,{outcome:"already_written",reason:o.cost_nano_usd===null?"unpriced":"priced"},{event:"inference_ledger_already_written",inference_id:e.inference_id,model_id:e.model_id,identity_kind:e.identity_kind,variant:e.variant,cost_nano_usd:o.cost_nano_usd,price_version:o.price_version,attempts:n.attempts});return}let i=Vo(s),a=Date.now()-n.queuedAt;if(je){Ie(n,{outcome:"failed",reason:"dropped_on_exit"},{event:"inference_ledger_write_failed",reason:"dropped_on_exit",attempts:n.attempts,waited_ms:a,error:`the proxy is shutting down and this row was still being retried when the drain ran out \u2014 the request was served and answered, and its billing row was never written. Last failure: ${s instanceof Error?s.message:String(s)}`});return}if(Wo(i)&&a<rt){if(await ii(oi(n.attempts)),je||Date.now()-n.queuedAt>=rt){let u=Date.now()-n.queuedAt;Ie(n,{outcome:"failed",reason:je?"dropped_on_exit":"dwell_expired"},{event:"inference_ledger_write_failed",reason:je?"dropped_on_exit":"dwell_expired",attempts:n.attempts,waited_ms:u,error:`this row's backoff outlived the ${rt}ms dwell bound (waited ${u}ms over ${n.attempts} attempt(s)) and was given up on rather than starting an attempt that could only finish past it. Last failure: ${s instanceof Error?s.message:String(s)}`});return}continue}Ie(n,{outcome:"failed",reason:i},{event:"inference_ledger_write_failed",reason:i,attempts:n.attempts,waited_ms:a,error:s instanceof Error?s.message:String(s)});return}}}function oi(n){return Math.min(ei,Zo*2**Math.max(0,n-1))}function ii(n){return new Promise(e=>{setTimeout(e,n).unref?.()})}function Ie(n,e,t){if(n.settled)return;n.settled=!0;try{n.ledger.observe(e)}catch{}let{event:r,...s}=t;Yr(n.report,zr(r,{inference_id:n.entry.inference_id,path:n.record.path,org:n.record.org,...s}))}A();var ln="x-urun-profile",ot="voice";var re=class extends Error{status=400},ai=/(?:[.!?:;]|\n)[)\]"'\u2019\u201d\u00bb\u300d\u300b\u3011\uff09\uff3d]?\s*$/,ui=/\s/;function di(n){return ai.test(n)}function dn(n,e,t){let r=n[e];if(r===void 0)return t;if(typeof r!="boolean")throw new re(`stream_options.voice.${e} must be a boolean when present (got ${typeof r})`);return r}function Qr(n,e,t,r={}){let s=n[e];if(s===void 0)return t;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new re(`stream_options.voice.${e} must be a positive finite number when present (got ${JSON.stringify(s)})`);if(r.min!==void 0&&s<r.min)throw new re(`stream_options.voice.${e} must be at least ${r.min} when present (got ${JSON.stringify(s)})${r.minReason?` \u2014 ${r.minReason}`:""}`);if(r.max!==void 0&&s>r.max)throw new re(`stream_options.voice.${e} must be at most ${r.max} when present (got ${JSON.stringify(s)}) \u2014 larger values wrap Node's setTimeout to a 1ms delay`);return s}function Zr(n,e){let t=Array.isArray(n)?n[0]:n,r=e.stream_options??void 0;if(r!==void 0&&(typeof r!="object"||Array.isArray(r)))throw new re(`stream_options must be a JSON object when present, e.g. {"profile":"voice","voice":{...}} (got ${JSON.stringify(r)})`);let s=r,o=s?.profile,i=!1;if(t!=null){let d=t.trim();if(d==="")throw new re(`the ${ln} header is empty \u2014 the only profile this lane accepts is "${ot}" (omit the header for the ordinary lane)`);if(d!==ot)throw new re(`unknown profile "${d}" \u2014 the only profile this lane accepts is "${ot}"`);i=!0}if(o!==void 0){if(typeof o!="string"||o!==ot)throw new re(`unknown profile ${JSON.stringify(o)} \u2014 the only profile this lane accepts is "${ot}"`);i=!0}if(!i)return null;if(e.stream!==!0)throw new re("the voice profile is streaming-only \u2014 send stream: true");let a=s?.voice;if(a!==void 0&&(typeof a!="object"||a===null||Array.isArray(a)))throw new re("stream_options.voice must be an object when present (flush_max_chars, flush_max_ms, sentence_flush, include_reasoning, metadata)");let u=a??{};return{flushMaxChars:Qr(u,"flush_max_chars",120,{min:2,minReason:"a hard split at a bound below 2 cannot keep UTF-16 surrogate pairs (astral characters) intact"}),flushMaxMs:Qr(u,"flush_max_ms",250,{max:2147483647}),sentenceFlush:dn(u,"sentence_flush",!0),includeReasoning:dn(u,"include_reasoning",!1),metadata:dn(u,"metadata",!1)}}var Tt=class{constructor(e,t){this.config=e;this.sink=t}config;sink;buffer="";timer=null;push(e){e!==""&&(this.buffer===""&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushMaxMs)),this.buffer+=e,this.drain())}flush(){if(this.clearTimer(),this.buffer==="")return;let e=this.buffer;this.buffer="",this.sink(e)}dispose(){this.clearTimer()}drain(){let e=this.config.flushMaxChars;for(;this.buffer.length>e;){let t=this.boundedCut();this.sink(this.buffer.slice(0,t)),this.buffer=this.buffer.slice(t)}(this.buffer.length>=e||this.config.sentenceFlush&&di(this.buffer))&&this.flush(),this.buffer===""&&this.clearTimer()}boundedCut(){let e=Math.min(Math.floor(this.config.flushMaxChars),this.buffer.length);for(let s=e-1;s>0;s--)if(ui.test(this.buffer[s]))return s+1;let t=Math.max(1,e),r=this.buffer.charCodeAt(t-1);return r>=55296&&r<=56319?t-1:t}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function mn(n){n.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function mi(n){n.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"}),n.flushHeaders(),n.socket?.setNoDelay(!0)}function Z(n,e,t){n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify(t))}function J(n,e,t,r="invalid_request_error",s){Z(n,e,{error:s?{message:t,type:r,code:s}:{message:t,type:r}})}function fn(n,e){let t=e.error,r=t?.type??"upstream_error",s=t?.message??JSON.stringify(e);Z(n,r==="invalid_request_error"?400:502,{error:{message:s,type:r,code:t?.code??null}})}function le(n,e,t,r){Z(n,e,{type:"error",error:{type:t,message:r}})}function Ge(n,e,t){if(e==="anthropic"){Z(n,404,{type:"error",error:{type:"not_found_error",message:t.message}});return}Z(n,404,{error:{message:t.message,type:"invalid_request_error",code:"model_not_found"}})}var fi=64*1024*1024,it=class extends Error{};async function es(n,e=fi){let t=[],r=0;for await(let o of n){if(r+=o.length,r>e)throw new it(`request body exceeds ${e} bytes`);t.push(o)}let s=Buffer.concat(t).toString("utf8");return s?JSON.parse(s):{}}function Ae(n,e,t,r){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:t,finish_reason:r}]}}function rs(n){let e=n?.usage;if(!e||typeof e!="object")return{kind:"absent"};let t=e,r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,s=r(t.input_tokens),o=r(t.output_tokens),i=u=>u??0,a=r(t.total_tokens)??i(s)+i(o);if(i(s)>0||i(o)>0){let u={input_tokens:i(s),output_tokens:i(o),total_tokens:a};return s===null||o===null?{kind:"partial",usage:u}:{kind:"counts",usage:u}}return s===null||o===null?{kind:"absent"}:{kind:"zero",usage:{input_tokens:0,output_tokens:0,total_tokens:a}}}function Pt(n){let e=rs(n);return e.kind==="counts"||e.kind==="partial"?e.usage:null}function ts(n){let e=Pt(n);return e?{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}function hi(n,e){let t=rs(e);t.kind==="absent"||t.kind==="partial"||(n.promptTokens=t.usage.input_tokens,n.completionTokens=t.usage.output_tokens)}function gi(n){let e=n?.urun_timing;if(!e||typeof e!="object")return null;let t=e,r=u=>{let d=t[u];return typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?d:null},s=r("queue_ms"),o=r("prefill_ms"),i=r("decode_ms"),a=r("total_ms");return s===null||o===null||i===null||a===null?null:{queue_ms:s,prefill_ms:o,decode_ms:i,total_ms:a}}function _i(n,e){let t=gi(e);t&&(n.timing=t)}function Oe(n,e){hi(n,e),_i(n,e)}async function Lt(n,e,t){if(typeof e.catalogIdentity!="function"){n.catalog={kind:"unresolved",reason:"this backhaul exposes no catalogIdentity seam, so the catalog (model_id, variant) that served the request cannot be known and no honest ledger row can be written"};return}try{let r=await e.catalogIdentity(t);if(r!==null){n.catalog={kind:"catalog",model_id:r.model_id,variant:r.variant};return}let s=typeof e.servingAppSlug=="function"?await e.servingAppSlug(t):null;n.catalog={kind:"not-a-catalog-model",model:s??t??null}}catch(r){n.catalog={kind:"unresolved",reason:`model ${JSON.stringify(t??null)} could not be resolved to a catalog identity: ${r instanceof Error?r.message:String(r)}`}}}function ss(n){let e=n?.output;if(!Array.isArray(e))return"";let t="";for(let r of e)if(!(r.type!=="reasoning"||!Array.isArray(r.content)))for(let s of r.content)s.type==="reasoning_text"&&(t+=String(s.text??""));return t}function yi(n){if(Array.isArray(n))return n.map(e=>{let t=e.function;return!t||typeof t!="object"?e:{type:"function",name:t.name,description:t.description,parameters:t.parameters,strict:t.strict}})}var Ct=class extends Error{};function wi(n,e){return Array.isArray(e)?e.map(t=>{let r=t;if(r.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:r.text};if(r.type==="image_url"){let s=r.image_url??{};return{type:"input_image",image_url:s.url,detail:s.detail}}throw new Ct(`unsupported chat content part type "${String(r.type)}" \u2014 the proxy translates text and image_url parts`)}):e}function vi(n){let e=[];for(let t of n){if(t.role==="tool"){e.push({type:"function_call_output",call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:JSON.stringify(t.content??"")});continue}if(t.role==="assistant"&&Array.isArray(t.tool_calls)){typeof t.content=="string"&&t.content&&e.push({role:"assistant",content:t.content});for(let r of t.tool_calls){let s=r.function??{};e.push({type:"function_call",call_id:r.id,name:s.name,arguments:s.arguments})}continue}e.push({...t,content:wi(t.role,t.content)})}return e}function cn(n){return Me(n).map((e,t)=>({index:t,id:e.call_id??e.id??`call_${t}`,type:"function",function:{name:e.name??"",arguments:e.arguments??"{}"}}))}async function bi(n,e,t,r,s,o){let i=ze(o.id),a=n.stream===!0;if(o.model=te(n),o.stream=a,await Lt(o,e,typeof n.model=="string"?n.model:void 0),a){let m;try{m=await Xe({body:n,clients:e,store:t,stats:s,responseId:i,turn:o})}catch(h){if(h instanceof D){Ge(r,"openai",h);return}if(h instanceof ie){J(r,h.status,h.message);return}throw h}mn(r);for await(let h of m.events)h.type==="error"&&(o.streamError=!0),h.type==="response.completed"&&Oe(o,h.response),r.write(`event: ${String(h.type??"message")}
|
|
26
26
|
data: ${JSON.stringify(h)}
|
|
27
27
|
|