@urun-sh/openai 0.6.47 → 0.6.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{a as ne}from"./chunk-CAR4AEQJ.js";import{e as ue,f as B,g as pe,h as fe}from"./chunk-P2YVKUSQ.js";import{c as Z,f as j,g as ee,p as oe}from"./chunk-64VO62LW.js";import{a as me,b as W}from"./chunk-XGAF2NDT.js";import{c as le}from"./chunk-5D7TVOAX.js";import{a as V}from"./chunk-Q3AIBMET.js";import{b as Y,d as $}from"./chunk-PXV7QBSD.js";import{b as te,c as se,d as re,g as ie,j as R,m as H,n as _,o as ae,r as N,s as L,t as ce,u as de}from"./chunk-C452ZIU5.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as q,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as He,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as Be,SessionFailedError as K}from"@urun-sh/core";v();import{SessionFailedError as Ie}from"@urun-sh/core";var G=2;function _e(e){let o=e?.type;return o==="response.created"||o==="response.in_progress"}function Le(e){let o=e?.type;return o==="response.completed"||o==="error"}function ge(e){return async function(s,i){let a=await e.sessionFor(s.model);return(async function*(){for(let l=1;l<=G;l++){let{app:g,entry:y,identity:h}=l===1?a:await e.sessionFor(s.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:h});let d=!1,p=!1;try{let m=await e.createStream(y,s);for await(let f of m){if(Le(f)&&(d=!0),_e(f)){if(l>1)continue}else p=!0;yield f}}catch(m){if(m instanceof Ie&&(m.kind==="never-live"||m.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,m)}catch{}throw m}if(l<G&&!p){await e.evict(g,y);continue}throw m}if(d)return;if(l<G&&!p){await e.evict(g,y);continue}return}})()}}import{randomUUID as ve}from"crypto";v();import{request as Te}from"http";var Fe="/pooler/v1/inference",k=class extends Error{constructor(s,i,a,c){super(a);this.status=s;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Re=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let o=e.messages?.find(s=>s.role==="system"||s.role==="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content)},Ne=e=>{let o=e.messages?.find(s=>s.role!=="system"&&s.role!=="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let s=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(s===void 0)return;if(typeof s=="string")return s;if(s!==null&&typeof s=="object"&&"content"in s){let i=s.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(s)}},we=e=>new Promise((o,s)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>o(Buffer.concat(i).toString("utf8"))),e.on("error",s)}),Me=async e=>{let o="pooler_error",s=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await we(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(o=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(s=a.message)}}catch{}return new k(e.status,o,s,e.retryAfterSeconds)};async function De(e,o,s,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Fe}`),l=JSON.stringify({region:e.region,model:i,request_id:s,streaming:a,payload:o,affinity:{systemPrompt:Re(o),firstMessage:Ne(o)}});return new Promise((g,y)=>{let h=Te({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},d=>{let p=Number(d.headers["retry-after"]??"");g({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(p)?p:void 0,body:d})});h.on("error",d=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),h.end(l)})}var ye=e=>{if(!e.startsWith("data: "))return null;let o=e.slice(6).trim();if(o===""||o==="[DONE]")return null;let s;try{s=JSON.parse(o)}catch{return null}if(s===null||typeof s!="object")return null;let i=s;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*xe(e){let o="";for await(let i of e.body)for(o+=String(i);;){let a=o.indexOf(`
1
+ import{a as ne}from"./chunk-CAR4AEQJ.js";import{e as ue,f as B,g as pe,h as fe}from"./chunk-HZNYGJGF.js";import{c as Z,f as j,g as ee,p as oe}from"./chunk-64VO62LW.js";import{a as me,b as W}from"./chunk-XGAF2NDT.js";import{c as le}from"./chunk-RX37QTWI.js";import{a as V}from"./chunk-Q3AIBMET.js";import{b as Y,d as $}from"./chunk-PXV7QBSD.js";import{b as te,c as se,d as re,g as ie,j as R,m as H,n as _,o as ae,r as N,s as L,t as ce,u as de}from"./chunk-C452ZIU5.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as q,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as He,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as Be,SessionFailedError as K}from"@urun-sh/core";v();import{SessionFailedError as Ie}from"@urun-sh/core";var G=2;function _e(e){let o=e?.type;return o==="response.created"||o==="response.in_progress"}function Le(e){let o=e?.type;return o==="response.completed"||o==="error"}function ge(e){return async function(s,i){let a=await e.sessionFor(s.model);return(async function*(){for(let l=1;l<=G;l++){let{app:g,entry:y,identity:h}=l===1?a:await e.sessionFor(s.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:h});let d=!1,p=!1;try{let m=await e.createStream(y,s);for await(let f of m){if(Le(f)&&(d=!0),_e(f)){if(l>1)continue}else p=!0;yield f}}catch(m){if(m instanceof Ie&&(m.kind==="never-live"||m.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,m)}catch{}throw m}if(l<G&&!p){await e.evict(g,y);continue}throw m}if(d)return;if(l<G&&!p){await e.evict(g,y);continue}return}})()}}import{randomUUID as ve}from"crypto";v();import{request as Te}from"http";var Fe="/pooler/v1/inference",k=class extends Error{constructor(s,i,a,c){super(a);this.status=s;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Re=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let o=e.messages?.find(s=>s.role==="system"||s.role==="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content)},Ne=e=>{let o=e.messages?.find(s=>s.role!=="system"&&s.role!=="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let s=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(s===void 0)return;if(typeof s=="string")return s;if(s!==null&&typeof s=="object"&&"content"in s){let i=s.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(s)}},we=e=>new Promise((o,s)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>o(Buffer.concat(i).toString("utf8"))),e.on("error",s)}),Me=async e=>{let o="pooler_error",s=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await we(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(o=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(s=a.message)}}catch{}return new k(e.status,o,s,e.retryAfterSeconds)};async function De(e,o,s,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Fe}`),l=JSON.stringify({region:e.region,model:i,request_id:s,streaming:a,payload:o,affinity:{systemPrompt:Re(o),firstMessage:Ne(o)}});return new Promise((g,y)=>{let h=Te({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},d=>{let p=Number(d.headers["retry-after"]??"");g({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(p)?p:void 0,body:d})});h.on("error",d=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),h.end(l)})}var ye=e=>{if(!e.startsWith("data: "))return null;let o=e.slice(6).trim();if(o===""||o==="[DONE]")return null;let s;try{s=JSON.parse(o)}catch{return null}if(s===null||typeof s!="object")return null;let i=s;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*xe(e){let o="";for await(let i of e.body)for(o+=String(i);;){let a=o.indexOf(`
2
2
 
3
3
  `);if(a===-1)break;let c=o.slice(0,a);o=o.slice(a+2);let l=ye(c);l!==null&&(yield l)}let s=ye(o);s!==null&&(yield s)}async function on(e,o,s,i){let a=Y(o,s,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await De(e,a,s,c,o.stream===!0);if(l.status>=400)throw await Me(l);let g=o.stream===!0?$(s,xe(l)):await Ce(l,s);return(async function*(){yield{type:"response.created",response:{id:`resp_${s}`,status:"in_progress"}},yield*g})()}async function Ce(e,o){let s=await we(e.body),i=null;try{let c=JSON.parse(s);c!==null&&typeof c=="object"&&(i=c)}catch{i=null}if(i===null)throw new k(502,"pooler_bad_body","the pooler answered a non-object body");let a=i;return $(o,(async function*(){yield a})())}v();import{encodeStreamEnvelope as he}from"@urun-sh/core";var Ue="audio";function Se(e){let o=e.streamEndpoint(Ue);return{sessionId:e.id,appendInputAudio(s,i){let a=Buffer.from(s,"base64");if(a.byteLength!==0){if(i===void 0){o.send(he(new Uint8Array(a)));return}o.send(he({pcm16:s,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}v();import{encodeStreamEnvelope as $e}from"@urun-sh/core";var je="rt-video-in";function Pe(e){let o=e.streamEndpoint(je);return{sendInputFrame:async s=>{o.send($e(s))}}}var We=0,Ge=4,qe=4;function Tn(e,o){let s=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let h=Number.parseInt(y,10);if(!Number.isInteger(h)||h<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return h},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):We;if(!Number.isInteger(a)||a<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=s("URUN_DECISION_POOL_MAX",Math.max(a,Ge));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:s("URUN_DECISION_POOL_INFLIGHT_CAP",qe),replicaId:(e.URUN_REPLICA_ID??"").trim()||o||"proxy"}}function Fn(e){let o=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!o)return B;let s=Number.parseInt(o,10);if(!Number.isInteger(s)||s<=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 s*1e3}function J(e,o,s,i){let a=e[s];if(typeof a!="function")throw new Error(`app "${o}" has no function "${s}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${o}" function "${s}" returned a session without end()`);return c}function Ae(e,o,s,i){let{baseUrl:a,orgId:c,auth:l}=e,g=o.fnName??e.fnName,y=e.sessionStartOptions?.(s),h=i||y||o.sharedApp?{...o.sharedApp?{sharedApp:!0}:{},...y,...i}:void 0,d=w=>({session:w,responses:new V(w),gone:me(w,s)});if(l.lane==="jwt"){let w=q(o.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return d(J(w,o.appSlug,g,h))}if(l.lane==="machine"||l.lane==="user"){let w=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:I}=l,T=(typeof e.subject=="function"?e.subject():e.subject)??ve(),F=q(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(w,{baseUrl:I,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:T,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(J(F,o.appSlug,g,h))}let{apiKey:p,gatewayUrl:m}=l,f=(typeof e.subject=="function"?e.subject():e.subject)??ve(),S=q(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(p,{baseUrl:m,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:f,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(J(S,o.appSlug,g,h))}function ke(e){let o=e.session.id;if(typeof o!="string"||o.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 o}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let o=e.status.error?.httpStatus,s=e.status.error?.code;return o===410||o===409&&(s==="cancelled"||s==="expired")?!0:s==="client_ended"}var Je=new Set(["error","paused"]);function Rn(e){let{auth:o,catalog:s}=e,i=null,a=(l,g)=>{let y=Ae(e,l,g);return e.onSessionOpen&&typeof y.session.id=="string"&&y.session.id!==""&&e.onSessionOpen(g,y.session.id),y.gone.onGone(()=>{i?.evict(g,y)}),y},c=new de({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:a,closeSession:async l=>{if(l.gone.dispose(),l.audioDispose?.(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:o.lane==="api-key"?()=>ae({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,listCatalog:e.catalogRows??(s?()=>ne(s):null),listPrices:s?()=>re(s):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return te(l)}:o.lane==="api-key"?()=>se({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,sessionKey:ke});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},L({appSlug:e.defaultApp}))),c}function Nn(e,o){let s=e.decisionPool;if(!s)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=s.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=d=>{process.stderr.write(`[decision-pool] ${d}
4
4
  `)},y=(d,p)=>{let m=a.get(p);if(m)return m;let f=new ue({min:s.min,max:s.max,idleGraceMs:s.idleGraceMs,inFlightCap:s.inFlightCap,replicaId:i,openSlot:async S=>{let w=Ae(e,d,p,{concurrencyKey:S.concurrencyKey});return w.gone.onGone(I=>I.bindingLost?f.evict(w):f.markSessionDead(w)),await C(w.session),g(`slot attached pool=${p} slot=${S.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async S=>{S.gone.dispose(),S.audioDispose?.(),await S.session.end()},onDetach:(S,w)=>g(`slot detached pool=${p} slot=${S.concurrencyKey} reason=${w}`),terminalOpenFailure:S=>S instanceof K&&X(S)});return c.set(p,{target:d,env:s}),a.set(p,f),f},h=async(d,p)=>{let m=c.get(p);if(m)try{let f=await o.poolTuningFor(d);y(d,p).retune({min:f?.min??m.env.min,max:f?.max??m.env.max,inFlightCap:f?.in_flight_cap??m.env.inFlightCap,idleGraceMs:f?.idle_grace_s!==void 0?f.idle_grace_s*1e3:m.env.idleGraceMs,warmWaitMs:f?.warm_wait_s!==void 0?f.warm_wait_s*1e3:void 0})}catch(f){g(`pool tuning refresh failed pool=${p} reason=${f instanceof Error?f.message:String(f)}`)}};return{async boot(){if(e.defaultApp===null)return;let d={appSlug:e.defaultApp};await y(d,L(d)).boot()},async sessionFor(d){let p=await o.resolveTargetFor(d),m=L(p),f=y(p,m);await h(p,m);let S=await f.acquire({timeoutMs:f.requestWaitMs}),w=l.get(S.entry)??[];return w.push(S),l.set(S.entry,w),{app:m,entry:S.entry,identity:ce(p)}},async warmFor(d){let p=await o.resolveTargetFor(d);await y(p,L(p)).boot()},end(d){let p=l.get(d)?.shift();p&&(l.get(d)?.length===0&&l.delete(d),p.release())},evict(d){for(let p of a.values())p.evict(d)},markSessionDead(d){for(let p of a.values())p.markSessionDead(d)},reap(){for(let[d,{target:p}]of c)h(p,d).then(()=>{let m=a.get(d);m&&m.reap()})},async pingReady(d){for(let p of a.values())if(await p.pingReady(d))return!0;return!1},stats(){return[...a.entries()].map(([d,p])=>({poolKey:d,...p.stats()}))},async drain(d){await Promise.all([...a.values()].map(p=>p.drain({timeoutMs:d})))},async close(){await Promise.all([...a.values()].map(d=>d.close()))}}}function Ke(e){return Be(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:He:be}async function C(e,o){let s=e.whenLive;if(typeof s!="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 s.call(e,{timeout:Ke(e.phase),signal:o})}async function Xe(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()}async function Oe(e){let o=e.phase?.name;if(o==="live"||o==="paused"){if(typeof e.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");e.detach();return}if(typeof e.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await e.end()}function x(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Mn(e,o=ee,s,i,a=B,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,h=new WeakMap,d=new WeakMap,p=n=>{let t=n.session.id;return typeof t=="string"&&t.length>0?t:null},m="lane",f=n=>{let t=_(n);if(!c||!t||t.app!==m)return null;let r=c.entryFor(t.key);if(!r)throw new R(`the lane behind this handle (${t.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:t.key,entry:r}},S=async n=>f(n)?.entry??(await e.sessionForHandle(n)).entry,w=n=>{let t=l.get(n);if(!t){let r={waiting:0,gone:new AbortController};d.set(n,r),t=(async()=>{if(await C(n.session,r.gone.signal),r.gone.signal.aborted)throw x(r.gone.signal);d.get(n)===r&&d.delete(n);let u=await Z(n.session,await o());return Object.assign(u,{sessionId:n.session.id})})(),l.set(n,t),t.then(u=>{l.get(n)===t&&(n.audioDispose=()=>u.dispose())},()=>{}),t.catch(()=>{l.get(n)===t&&l.delete(n)}),t.then(()=>{d.get(n)===r&&d.delete(n)},()=>{d.get(n)===r&&d.delete(n)})}return t},I=n=>{let t=h.get(n);return t||(t=(async()=>{let r=await w(n);return{appendInputAudio:(u,E)=>r.appendInputAudio(u,E),onOutputAudio:u=>r.onOutputAudio(u),sessionId:p(n)}})(),h.set(n,t),t.catch(()=>{h.get(n)===t&&h.delete(n)})),t},T=async(n,t,r,u=!1)=>{let E=()=>u?Oe(n.session):Xe(n.session);if(r?.aborted){let O=d.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await E().catch(()=>{}),x(r)}let b=t(n),P=d.get(n);return P!==void 0&&P.waiting++,r===void 0?b:new Promise((O,A)=>{let z=()=>{P!==void 0&&--P.waiting===0&&d.get(n)===P&&(P.gone.abort(),d.delete(n),l.delete(n),h.delete(n),E().catch(()=>{})),A(x(r))};r.addEventListener("abort",z,{once:!0});let Q=()=>r.removeEventListener("abort",z);b.then(U=>{Q(),O(U)},U=>{Q(),A(U)})})},F=async(n,t,r)=>{try{return await r}catch(u){throw(u instanceof R||u instanceof K&&X(u))&&(e.evict(n,t),u instanceof K&&s?.(n,u.kind==="never-live"?"never-live":"create-failed")),u}};return{createResponse:ge({sessionFor:c?async n=>{let t=await e.resolveTargetFor(n);if(t.sharedApp)try{let r=await c.sessionFor(n,t);return{app:r.app,entry:r.entry,identity:r.identity}}catch(r){if(r instanceof le)return i?i.sessionFor(n):e.sessionFor(n);if(r instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${r.name} ${r.code}: ${r.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw r}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>p(n),evict:(n,t)=>{c&&c.owns(t)?c.evict(t):i?i.evict(t):e.evict(n,t)},onAdmissionVerdict:(n,t,r)=>{X(r)&&(c&&c.owns(t)?c.evict(t):i?i.markSessionDead(t):e.evict(n,t),s?.(n,r.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,t)=>{try{await C(n.session);let r=pe(W(await n.responses.responses.create(t),n.gone),a);if(!i&&!c)return r;let u=n;return(async function*(){try{yield*r}catch(b){throw fe(b)&&(c&&c.owns(u)?c.evict(u):i&&(b instanceof R&&!b.bindingLost?i.markSessionDead(u):i.evict(u))),b}finally{c&&c.owns(u)?c.release(u):i?.end(u)}})()}catch(r){throw c&&c.owns(n)?c.release(n):i&&i.end(n),r}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,t)=>e.supportsImages(n,t),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,t)=>{let{app:r,entry:u}=await e.sessionFor(n);return await F(r,u,T(u,w,t))},openAudioOn:async(n,t,r,u)=>{let E=f(n);if(E){let A=E.entry.session;return Se(A)}let{app:b,entry:P}=await e.sessionForHandle(n);if(u&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;u({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let O=_(n)?.app.startsWith(N)??!1;return await F(b,P,T(P,I,t,O))},openTurnsOn:async function*(n,t){if(t?.aborted)throw x(t);let r=await S(n);yield*ie(r.session,t)},openVideoOn:async n=>{let t=f(n);if(t)return Pe(t.entry.session);let{entry:r}=await e.sessionForHandle(n),u=g.get(r);return u||(u=j(r.session),g.set(r,u)),u},openVideo:async n=>{let{entry:t}=await e.sessionFor(n),r=g.get(t);return r||(r=j(t.session),g.set(t,r)),r},openVideoOut:async n=>{let{entry:t}=await e.sessionFor(n),r=y.get(t);return r||(r=oe(t.session),y.set(t,r)),r},sessionHandle:async n=>{if(c){let t=await e.resolveTargetFor(n);if(t.sharedApp){let r=await c.sessionFor(n,t),u=p(r.entry);if(u===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return H(m,u)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:r,entry:u}=await e.dedicatedSessionFor(n);return H(r,ke(u))},releaseSessionHandle:n=>{let t=_(n);if(!t)return;if(t.app.startsWith(N)){(async()=>{let u=null;try{u=(await e.sessionForHandle(n)).entry}catch{return}await Oe(u.session).catch(()=>{}),await e.evict(t.app,u)})();return}if(!c||t.app!==m)return;let r=c.entryFor(t.key);r&&c.release(r)},endDedicatedSession:async n=>{let t=_(n);if(!t||!t.app.startsWith(N))return;let r=null;try{r=(await e.sessionForHandle(n)).entry}catch{return}if(typeof r.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let u=await r.session.end();return await e.evict(t.app,r),u},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:t,entry:r}=await e.sessionForHandle(n);await e.evict(t,r)},createResponseOn:async(n,t,r)=>{let u=await S(n);await C(u.session);let E=r!==void 0&&f(n)?new V({...u.session,consumerId:r},{sessionTag:r}):u.responses;return W(await E.responses.create(t),u.gone)},onSessionEnd:async(n,t)=>{let r=f(n);if(r)return r.entry.gone.onGone(P=>t({timeLeftMs:null,reason:P.message}));let{entry:u}=await e.sessionForHandle(n),E=u.session;if(typeof E.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let b=!1;return E.onPhase(P=>{if(b||!Je.has(P.name))return;b=!0;let O=E.endsAt??null;t({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}export{k as a,on as b,Tn as c,Fn as d,Rn as e,Nn as f,Mn as g};
@@ -1,4 +1,4 @@
1
- import{a as Wn,c as Vn,d as Fe,e as Tt,f as re,g as zn,h as Kn,i as Xn,j as Yn,k as Qn,l as Zn,m as er,n as tr,r as nr,t as rr,u as sr,v as ir,w as or,x as ar}from"./chunk-X5BLQXHK.js";import{a as sn,e as on}from"./chunk-64VO62LW.js";import{a as Te,b as ye,v as Oe}from"./chunk-5D7TVOAX.js";import{a as Gn,e as lt,f as Jn,i as J,j as Q,k as an,l as un}from"./chunk-C452ZIU5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as qs}from"crypto";import{WebSocketServer as Us}from"ws";var Bs=256,Ot=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Bs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},js="local",dt=n=>n.slice(0,120),Pt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Vn,dt(e.message));return}if(e instanceof Q){this.ws.close(Tt,dt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,dt(e.message));return}this.ws.close(Fe,dt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=zn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=tr(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=rr(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:nr);return}this.transcript.push(...sr(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=Qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Tt);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Tt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Yn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Kn]=Xn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(or(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=qs();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Zn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(er(e.timeLeftMs)),this.ws.close(Fe,dt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=ir(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=ar(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Hs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new De(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ur(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Us({noServer:!0}),s=new Ot;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Wn&&(a.on("error",()=>{}),(async()=>{let d=Hs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:js}}r.handleUpgrade(o,a,u,p=>{new Pt(p,c,s)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
1
+ import{a as Wn,c as Vn,d as Fe,e as Tt,f as re,g as zn,h as Kn,i as Xn,j as Yn,k as Qn,l as Zn,m as er,n as tr,r as nr,t as rr,u as sr,v as ir,w as or,x as ar}from"./chunk-X5BLQXHK.js";import{a as sn,e as on}from"./chunk-64VO62LW.js";import{a as Te,b as ye,v as Oe}from"./chunk-RX37QTWI.js";import{a as Gn,e as lt,f as Jn,i as J,j as Q,k as an,l as un}from"./chunk-C452ZIU5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as qs}from"crypto";import{WebSocketServer as Us}from"ws";var Bs=256,Ot=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Bs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},js="local",dt=n=>n.slice(0,120),Pt=class{constructor(e,t,r){this.ws=e;this.call=t;this.registry=r;this.clients=t.clients,this.scope=t.scope,e.on("message",s=>this.onMessage(s)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Vn,dt(e.message));return}if(e instanceof Q){this.ws.close(Tt,dt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,dt(e.message));return}this.ws.close(Fe,dt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=zn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(s=>this.fail(s));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:i}=tr(t.clientContent);this.transcript.push(...s),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=rr(t.realtimeInput);if(s.kind==="activityStart"||s.kind==="activityEnd"){this.onActivity(s.kind,r);return}if(s.kind==="text"){this.transcript.push({role:"user",content:s.text}),this.enqueue(()=>this.runTurn());return}if(s.kind==="video"){this.appendVideoFrame(s.jpegFrame);return}this.appendAudio(s.kind==="audio"?s.base64Pcm24k:nr);return}this.transcript.push(...sr(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=Qn(e),r=t.sessionResumption.handle;if(r!==null){let i=this.registry.get(this.scope,r);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Tt);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(r)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Tt);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(Yn(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[Kn]=Xn(o.codec)}}this.send({setupComplete:s}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(or(s))),r})(),this.audio.catch(r=>this.fail(r)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(r=>this.fail(r)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let r=qs();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Zn(r))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,r=>this.enqueue(()=>this.handleUpstreamEnd(r))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(er(e.timeLeftMs)),this.ws.close(Fe,dt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let r=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),s,i=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){s=l.response,i=!0;continue}let d=ir(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=ar(s);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Hs(n,e,t){let r=new Set;(u=>{if(typeof u=="string")u!==""&&r.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&r.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&r.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&r.add(o),r.size>1)throw new De(401,`contradictory credentials: ${r.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of r)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ur(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let r=new Us({noServer:!0}),s=new Ot;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Wn&&(a.on("error",()=>{}),(async()=>{let d=Hs(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:js}}r.handleUpgrade(o,a,u,p=>{new Pt(p,c,s)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
2
2
  Connection: close\r
3
3
  \r
4
4
  ${m}\r
@@ -1,4 +1,4 @@
1
- import{a as $e,b as Ot,c as Ct,e as xe,f as Nt,g as De}from"./chunk-LROCLDDN.js";import{A as Lt,B as It,C as At,D as Ut,E as Tt,b as it,d as at,i as dt,j as ut,l as pt,m as ht,n as gt,o as mt,p as yt,q as wt,r as bt,t as vt,u as ce,v as _t,w as St,x as kt,y as Et,z as Rt}from"./chunk-P2YVKUSQ.js";import{a as ot}from"./chunk-X5BLQXHK.js";import{a as xt,e as Dt}from"./chunk-VRNM6ZKU.js";import{a as Pt}from"./chunk-XGAF2NDT.js";import{a as lt,b as ae,c as ct,o as ft,p as le}from"./chunk-5D7TVOAX.js";import{a as $t,c as ee,e as He}from"./chunk-XNRPTMSL.js";import{a as nt}from"./chunk-Q3AIBMET.js";import{e as rt,j as oe,p as st,q as ie,r as Ne}from"./chunk-C452ZIU5.js";import{c as U}from"./chunk-YSFSRI3D.js";U();import{Counter as J,Gauge as de,Histogram as ue,Registry as An,collectDefaultMetrics as Un}from"@prometheus-io/client";import{createServer as Tn}from"http";var Os=9464,Ht="/metrics",fe="(other)",On="(none)",Pn=64,Cn=128,Nn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",vt,St,rt],$n=new Set(Nn);function xn(t){return $n.has(t)?t:fe}function Dn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?On:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,fe):(this.admitted.add(e),e):fe}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},he=class{registry=new An;modelLabel=new pe(Pn);orgLabel=new pe(Cn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new de({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new J({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new ue({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 ue({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new J({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new J({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new J({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of kt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new de({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"},Et()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Rt()/1e3)}}),this.labelCardinality=new de({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new J({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new de({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new ue({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new ue({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new J({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new J({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&Un({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=xn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?fe:e.method,status_class:Dn(e.status),stream:l,model:o,org:i}),this.duration.observe({lane:n,stream:l,model:o,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Mt(t){return Tn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ht){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ht}
1
+ import{a as $e,b as Ot,c as Ct,e as xe,f as Nt,g as De}from"./chunk-25PW2MQZ.js";import{A as Lt,B as It,C as At,D as Ut,E as Tt,b as it,d as at,i as dt,j as ut,l as pt,m as ht,n as gt,o as mt,p as yt,q as wt,r as bt,t as vt,u as ce,v as _t,w as St,x as kt,y as Et,z as Rt}from"./chunk-HZNYGJGF.js";import{a as ot}from"./chunk-X5BLQXHK.js";import{a as xt,e as Dt}from"./chunk-YC6TNAKY.js";import{a as Pt}from"./chunk-XGAF2NDT.js";import{a as lt,b as ae,c as ct,o as ft,p as le}from"./chunk-RX37QTWI.js";import{a as $t,c as ee,e as He}from"./chunk-XNRPTMSL.js";import{a as nt}from"./chunk-Q3AIBMET.js";import{e as rt,j as oe,p as st,q as ie,r as Ne}from"./chunk-C452ZIU5.js";import{c as U}from"./chunk-YSFSRI3D.js";U();import{Counter as J,Gauge as de,Histogram as ue,Registry as An,collectDefaultMetrics as Un}from"@prometheus-io/client";import{createServer as Tn}from"http";var Os=9464,Ht="/metrics",fe="(other)",On="(none)",Pn=64,Cn=128,Nn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",vt,St,rt],$n=new Set(Nn);function xn(t){return $n.has(t)?t:fe}function Dn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?On:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,fe):(this.admitted.add(e),e):fe}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},he=class{registry=new An;modelLabel=new pe(Pn);orgLabel=new pe(Cn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new de({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new J({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new ue({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 ue({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new J({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new J({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new J({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of kt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new de({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"},Et()),this.ledgerQueue.set({measure:"oldest_age_seconds"},Rt()/1e3)}}),this.labelCardinality=new de({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new J({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new de({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new ue({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new ue({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new J({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new J({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&Un({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=xn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?fe:e.method,status_class:Dn(e.status),stream:l,model:o,org:i}),this.duration.observe({lane:n,stream:l,model:o,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Mt(t){return Tn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ht){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ht}
2
2
  `);return}let s=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(s)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
3
3
  `);return}n.end()})})}U();import{createHash as Ft}from"crypto";import{createServer as Hn}from"http";var xs=9465,Mn="x-urun-key-id",Wn="x-urun-key-fingerprint",Fn="urun-ratelimit-bucket:",Bn="urun-ratelimit-tier:",Wt="anonymous",Kn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Gn(t){return Ft("sha256").update(`${Fn}${t}`).digest("hex")}function jn(t){return Ft("sha256").update(`${Bn}${t}`).digest("hex")}function Jn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return Kn.test(n)?n:null}function Bt(){return Hn((t,e)=>{let n=Jn(t.headers.authorization);e.setHeader(Mn,n===null?Wt:Gn(n)),e.setHeader(Wn,n===null?Wt:jn(n)),e.writeHead(200),e.end()})}U();import{createClientToken as zn,ClientTokenError as Kt}from"@urun-sh/core";import{createPublicKey as qn,verify as Vn}from"crypto";var Gt="urun-session-gateway",Yn="machine",Qn=3e5;function Jt(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var P=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},z=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},B=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function we(t){let e=(t??"").trim();if(e==="")throw new P("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 P("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Xn=60,Zn=6e4,er=4096;function tr(t){return t===401||t===403}var ne=class{constructor(e){this.opts=e;this.mint=e.mint??zn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new P("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<Zn)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let s,o;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Xn});s=i.orgId,o={...i.billingAudience!==void 0?{billingAudience:i.billingAudience}:{},...i.creditsAdmissionOk!==void 0?{creditsAdmissionOk:i.creditsAdmissionOk}:{},...i.creditsRefusalReason!==void 0?{creditsRefusalReason:i.creditsRefusalReason}:{}}}catch(i){throw i instanceof Kt&&i.status===402?(this.cache.delete(e),new z(i.code==="spend_cap_reached"||i.code==="insufficient_credits"?i.code:void 0)):i instanceof Kt&&tr(i.status)?(this.cache.delete(e),new P(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new B(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!s)throw new B(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=er){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:s,at:this.now(),...o}),{apiKey:e,orgId:s,credential:n,...o}}clear(){this.cache.clear()}};function te(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function jt(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var ge=class{constructor(e,n,r,s){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=s}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof B?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<Qn)return r.keys;let s=this.inFlight.get(e);if(s!==void 0)return s;let o=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,o);let i=await o;return this.entries.set(e,{keys:i,at:this.now()}),i}async keyFor(e,n){let r=await this.keys(e,!1),s=n===""?void 0:r.find(o=>o.kid===n&&jt(o));return s===void 0&&(r=await this.keys(e,!0),s=n===""?void 0:r.find(o=>o.kid===n&&jt(o))),s}};function zt(t,e,n){try{let r=qn({key:n,format:"jwk"});return Vn("RSA-SHA256",t,r,e)}catch{return!1}}var me=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new ge(e.fetchImpl??fetch,e.now??Date.now,n=>new B("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new P("malformed machine token");let o,i;try{o=te(n),i=te(r)}catch{throw new P("malformed machine token")}if(o.alg!=="RS256")throw new P(`machine token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let a=typeof o.kid=="string"?o.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new P(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(i.aud!==Gt)throw new P(`machine token audience must be ${Gt} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==Yn)throw new P(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let p=typeof i.org_id=="string"?i.org_id:"";if(p==="")throw new P("machine token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");let _=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,a);if(_===void 0)throw new P(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let A=Buffer.from(`${n}.${r}`,"ascii"),T=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!zt(A,T,_))throw new P("machine token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:p,credential:"machine"}}},nr="https://api.workos.com/sso/jwks/";function rr(t){return`${nr}${t.slice(t.lastIndexOf("/")+1)}`}var Me=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new ge(e.fetchImpl??fetch,this.now,n=>new B("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Jt(e))return!1;try{let n=te(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new P("malformed user token");let o,i;try{o=te(n),i=te(r)}catch{throw new P("malformed user token")}if(o.alg!=="RS256")throw new P(`user token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let a=typeof o.kid=="string"?o.kid:"",l=typeof i.iss=="string"?i.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new P(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let p=typeof i.org_id=="string"?i.org_id:"";if(p==="")throw new P("user token carries no org_id \u2014 no tenancy to route by");let d=typeof i.exp=="number"?i.exp:0;if(d<=Math.floor(this.now()/1e3))throw new P("user token is expired \u2014 re-authenticate and retry");let _=await this.cache.keyFor(rr(l),a);if(_===void 0)throw new P(`user token kid ${JSON.stringify(a)} is not in the WorkOS issuer's JWKS`);let A=Buffer.from(`${n}.${r}`,"ascii"),T=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!zt(A,T,_))throw new P("user token signature failed verification");if(d<=Math.floor(this.now()/1e3))throw new P("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:p,credential:"user"}}},ye=class{verifier;bindings;constructor(e){this.verifier=new Me({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new ne({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}})}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e),r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new P("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function We(t,e,n,r){if(Jt(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}U();var sr=8080,Fe="serve",Gs="0.0.0.0";function or(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function js(t=process.env){let e=(t.PORT??"").trim(),n=e===""?sr: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=ft(le(or(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),s=(t.URUN_API_URL??"").trim(),o=s?le(s,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=i?{catalogUrl:le(i,"URUN_CATALOG_URL"),anonKey:a}:null,p=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!p!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let _=p?{keyId:d,key:p}:void 0,A={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},T=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],c=T.filter((u,y)=>Object.values(A)[y]==="");if(c.length!==0&&c.length!==T.length)throw new Error(`${T.join(", ")} must be set together (or all left unset) \u2014 missing: ${c.join(", ")}, which would half-configure the lane plane`);let w=c.length===0?A:void 0,v={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},g=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],b=g.filter((u,y)=>Object.values(v)[y]==="");if(b.length!==0&&b.length!==g.length)throw new Error(`${g.join(", ")} must be set together (or all left unset) \u2014 missing: ${b.join(", ")}, which would half-configure the pooler cutover`);let E=b.length===0?v:void 0,h={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},f=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=f.filter((u,y)=>Object.values(h)[y]==="");if(S.length!==0&&S.length!==f.length)throw new Error(`${f.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let L=h.issuers.split(",").map(u=>u.trim()).filter(u=>u!=="");if(L.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let m=Number(h.tokenTtlS);if(S.length===0&&(!Number.isFinite(m)||m<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(h.tokenTtlS)}`);let I=S.length===0?{jwksBaseUrl:h.jwksBaseUrl,issuers:L,tokenTtlS:m}:void 0,O=(t.URUN_WORKOS_ISSUERS??"").trim(),$=O.split(",").map(u=>u.trim()).filter(u=>u!=="");if(O!==""&&$.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let u of $){let y;try{y=new URL(u)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(u)}`)}if(y.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${u}) \u2014 the issuer is the user rung's trust root`)}return{port:n,baseUrl:r,apiUrl:o,catalog:l,ledgerSigning:_,lane:w,pooler:E,machine:I,...$.length>0?{userIssuers:$}:{}}}U();import{createHash as ir,randomUUID as qt}from"crypto";var ar=512;function be(t){return`urun-inference-proxy-${ir("sha256").update(t).digest("hex").slice(0,32)}`}var ve=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let s=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;if(o===void 0)return s;let i=this.opts.lanes;return Object.assign(Object.create(s),{createResponse:async(a,l)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await s.createResponse(a,l);let p=`px_${qt()}`;return Ot(o,a,p,p)}})}build(e){if(this.opts.build){let o=this.opts.build(e);return o.decision&&this.ensureDecisionReaper(),{router:o.router,clients:this.label(o.clients,e,o.router),decision:o.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Fe,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:Ct(process.env,process.env.HOSTNAME)??void 0},r=xe(n),s=n.decisionPool?Nt(n,r):null;return s&&this.ensureDecisionReaper(),{router:r,clients:this.label(De(r,void 0,void 0,s??void 0,void 0,this.opts.lanes),e,r),decision:s??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=ar;){let s=this.tenants.entries().next();if(s.done)break;let[o,i]=s.value;this.tenants.delete(o),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let s=[r.router.closeAll().catch(o=>{n.push(String(o instanceof Error?o.message:o))})];r.decision&&s.push(r.decision.close().catch(o=>{n.push(String(o instanceof Error?o.message:o))})),await Promise.all(s)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Vt=512,lr=1024,Be=class extends Error{constructor(){super(`conversation capacity reached (${Vt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function cr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(ie))return{concurrencyKey:e};if(n.startsWith(ie)||n.startsWith(Ne))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(ie)||n.startsWith(Ne)||t.set(n,r)}}}function dr(t,e,n,r,s){let o=xe({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Fe,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...cr(r,s)});return{clients:De(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var _e=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let s={id:n,subject:r!==void 0?`${be(e.apiKey)}:live`:`${be(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,s):dr(this.opts,e,s,o,r);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n,r){let s=this.byCaller.get(e.apiKey);s===void 0&&(s=new Map,this.byCaller.set(e.apiKey,s));let o=s.get(n);if(o!==void 0)return s.delete(n),s.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,s.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Vt;){let e=!1;for(let[n,r]of this.byCaller){for(let[s,o]of r)if(!(o.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),o.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new Be}}dropHandleIndexFor(e,n){for(let[r,s]of this.byHandle)s.apiKey===e&&s.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,s=!1,o=()=>(r===null&&(r=this.attachEntry(e,qt(),n)),r),i={createResponse:(a,l)=>o().backhaul.clients.createResponse(a,l),catalogIdentity:a=>o().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let l=o().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(a)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:a=>o().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let l=o().backhaul.clients.dedicatedSessionHandle;return l===void 0?o().backhaul.clients.sessionHandle(a):l(a)},releaseSessionHandle:a=>o().backhaul.clients.releaseSessionHandle?.(a),endDedicatedSession:a=>o().backhaul.clients.endDedicatedSession?.(a),createResponseOn:(a,l,p)=>o().backhaul.clients.createResponseOn(a,l,p),onSessionEnd:(a,l)=>o().backhaul.clients.onSessionEnd(a,l)};return i.openAudio=async(a,l)=>{let p=o().backhaul.clients.openAudio;if(p===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return p(a,l)},i.openVideo=async a=>{let l=o().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(a)},i.openVideoOut=async a=>{let l=o().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(a)},i.supportsAudio=async a=>{let l=o().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(a)},i.supportsSpeech=async a=>{let l=o().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(a)},i.speechVoices=async a=>{let l=o().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(a)},i.speechSessionHandle=async a=>{let l=o().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(a)},i.openAudioOn=async(a,l,p)=>{let d=o().backhaul.clients.openAudioOn;if(d===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 d(a,l,p)},i.openVideoOn=async(a,l)=>{let p=o().backhaul.clients.openVideoOn;if(p===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return p(a,l)},i.openTurnsOn=(a,l)=>{let p=o().backhaul.clients.openTurnsOn;if(p===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return p(a,l)},i.evictSpeechSession=async a=>{let l=o().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(a)},i.supportsTranscription=async a=>{let l=o().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(a)},i.transcriptStreamFor=async a=>{let l=o().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(a)},i.listSpeechToTextModels=async()=>{let a=o().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=lr;){let p=this.byHandle.keys().next();if(p.done)break;this.byHandle.delete(p.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async a=>{let l=this.byHandle.get(a),p=l===void 0?void 0:this.byCaller.get(l.apiKey),d=l===void 0||p===void 0?void 0:p.get(l.conversationId);if(l===void 0||d===void 0||l.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 r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(s)return;s=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let s of r.values())e.push(s.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(s){n.push(String(s instanceof Error?s.message:s))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};U();var ur="/inference-ledger",fr=1e4,Se=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},je=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},M=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Je=class extends P{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},ze=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},pr=[["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",Ke],["output_minutes",Ke],["cost_nano_usd",Ke],["price_version",t=>t===null||typeof t=="string"]];function hr(t){for(let[e,n]of pr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function gr(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"}:hr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Ke(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Ge(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function mr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Yt(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 yr(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&&Yt(t.started_at,n.started_at)&&Yt(t.completed_at,n.completed_at)&&Ge(t.prompt_tokens,n.prompt_tokens)&&Ge(t.completion_tokens,n.completion_tokens)&&Ge(t.output_units,n.output_units)&&mr(t.output_minutes,n.output_minutes)}function wr(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
4
4
  `)}async function br(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",r,n.encode(wr(t)));return{signature:Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function vr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new M(`${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 M(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new M(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let s=n.cost_nano_usd;if(s!=null&&!(typeof s=="number"&&Number.isInteger(s)&&s>=0))throw new M(`${e} answered cost_nano_usd ${JSON.stringify(s)}, which is neither a non-negative integer nor null`);let o=p=>{if(!(p in n))throw new M(`${e} answered a row with no ${p} field: ${JSON.stringify(t)}`);let d=n[p];if(d===null)return null;if(typeof d!="string")throw new M(`${e} answered a non-string ${p}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new M(`${e} answered a BLANK ${p} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=o("price_version"),a=o("unpriced_reason"),l=s!=null;if(l&&(i===null||a!==null))throw new M(`${e} answered a PRICED row (cost_nano_usd ${String(s)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!l&&(i!==null||a===null))throw new M(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:s===void 0?null:s,price_version:i,unpriced_reason:a}}var ke=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${ur}`,s;try{s=this.opts.signing?JSON.stringify({...n,...await br(n,this.opts.signing)}):JSON.stringify(n)}catch(p){throw new M(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${p instanceof Error?p.message:String(p)}`)}let o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:s,signal:AbortSignal.timeout(fr)})}catch(p){throw new M(`the uRun ledger surface at ${r} could not be reached: ${p instanceof Error?p.message:String(p)}`)}if(o.status===409){let p=await o.text().catch(()=>""),d=gr(p);throw d.status==="found"&&yr(n,d.row)?new je(d.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.`):d.status==="not_in_this_org"?new Se(`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 Se(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${p.slice(0,400)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new Je("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(!o.ok){let p=await o.text().catch(_=>`<body unreadable: ${_ instanceof Error?_.message:String(_)}>`),d;try{let _=JSON.parse(p);if(_!==null&&typeof _=="object"&&"error"in _){let A=_.error;A!==null&&typeof A=="object"&&"code"in A&&(d=A.code)}}catch{}throw d==="ledger_signature_invalid"?new ze(`the uRun control plane refused the ledger row's SIGNATURE for inference_id ${n.inference_id} \u2014 the row was NOT recorded. The likeliest cause is on this pod: the signing key is misconfigured or was rotated out of step with the control plane (URUN_LEDGER_SIGNING_KEY / URUN_LEDGER_SIGNING_KEY_ID). The caller's own org key still authenticates fine \u2014 this refusal says nothing about it. Control plane said: `+p.slice(0,400)):new M(`the uRun ledger surface at ${r} answered HTTP ${o.status}: ${p.slice(0,400)}`)}let i;try{i=await o.json()}catch(p){throw new M(`the uRun ledger surface at ${r} answered a body that is not JSON: ${p instanceof Error?p.message:String(p)}`)}let a=i?.recorded;if(a===void 0)throw new M(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let l=vr(a,`the uRun ledger surface at ${r}`);if(l.inference_id!==n.inference_id)throw new M(`the uRun ledger surface at ${r} answered for inference_id ${l.inference_id} when asked about ${n.inference_id}`);return l}};U();import{createServer as ms}from"http";U();import{createCipheriv as _r,createDecipheriv as Sr,hkdfSync as kr,randomBytes as Er,randomUUID as Zt}from"crypto";import{resolve4 as Rr}from"dns/promises";U();var Qt="/realtime/openai.quic-relay";async function Xt(t){let e=await fetch(`${t.sfuBase}${Qt}${t.query}`,{method:"POST",headers:{"content-type":"application/json",authorization:t.upstreamHeaders.authorization??""},body:"{}"});if(e.status!==201){let o=await e.text().catch(()=>"");throw new Error(`quic relay ${t.sfuBase}${Qt} -> ${e.status} ${o}`)}let n=await e.json(),r=new URL(t.sfuBase).host,s=n.url??`https://${r}:${n.wtPort??4443}/wt`;return{status:201,body:{callId:n.callId,url:s,token:n.token,certHashes:n.certHashes},location:`/v1/realtime/calls/${n.callId}`}}var qe="/v1/realtime/calls",en="/v1/realtime/client_secrets",Lr="session-server-ts-pods.urun.svc.cluster.local",tn=8081,Ir="/realtime/openai.relay",Ar=262144,Ur=600;function nn(t){let e=t.secret===void 0?void 0:Buffer.from(kr("sha256",t.secret,"","urun realtime client secret",32)),n=t.mediaEdges??(async()=>Nr(await Rr(Lr))),r=(s,o,i,a)=>{s.writeHead(o,{"content-type":"application/json"}),s.end(JSON.stringify({error:{message:i,type:"invalid_request_error",...a?{code:a}:{}}}))};return async(s,o)=>{let i=new URL(s.url??"/","http://proxy");if(s.method!=="POST"||i.pathname!==qe&&i.pathname!==en)return!1;let a=await Or(s);if(a===null)return r(o,413,"request body too large"),!0;let l=(s.headers.authorization??"").replace(/^Bearer\s+/i,"");if(l.startsWith("ek_")){let g=e===void 0?null:Cr(e,l.slice(3));if(g===null)return r(o,401,"invalid or expired client secret","invalid_api_key"),!0;s.headers.authorization=`Bearer ${g}`}try{await t.authorize(s)}catch(g){let b=typeof g=="object"&&g!==null&&"status"in g&&typeof g.status=="number"?g.status:401;return r(o,b,g instanceof Error?g.message:String(g)),!0}if(i.pathname===en){if(e===void 0)return r(o,501,"client secrets are not configured on this proxy"),!0;let g=a.length===0?{}:JSON.parse(a.toString("utf8")),b=typeof g=="object"&&g!==null&&"session"in g?g.session:null,E=Math.floor(Date.now()/1e3)+Ur,h=(s.headers.authorization??"").replace(/^Bearer\s+/i,"");return o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({value:`ek_${Pr(e,h,E)}`,expires_at:E,session:b})),!0}if(i.searchParams.get("transport")==="quic"){let g=i.searchParams.get("model");if(g===null)return r(o,400,"model is required (?model=)"),!0;let b=`quic_${Zt().replaceAll("-","")}`,E=new URLSearchParams(i.searchParams);E.set("model",g),E.set("call_id",b);let h="no media edge resolved";for(let f of await n())try{let S=await Xt({sfuBase:`http://${f}:${tn}`,query:`?${E}`,upstreamHeaders:{authorization:s.headers.authorization??""}});return o.writeHead(201,{"content-type":"application/json",location:`${qe}/${S.body.callId}`}),o.end(JSON.stringify(S.body)),!0}catch(S){h=`${f}: ${String(S)}`}return r(o,502,`no media edge accepted the quic call (${h})`),!0}let{sdp:p,session:d}=await Tr(s.headers["content-type"]??"",a);if(p===void 0)return r(o,400,"the request carries no SDP offer (application/sdp body or multipart `sdp` field)"),!0;let _=typeof d=="object"&&d!==null&&"model"in d&&typeof d.model=="string"?d.model:void 0,A=i.searchParams.get("model")??_;if(A===void 0)return r(o,400,"model is required (?model= or session.model)"),!0;let T=`rtc_${Zt().replaceAll("-","")}`,c=new URLSearchParams(i.searchParams);c.set("model",A),c.set("call_id",T);let w=JSON.stringify({sdp:p,...d!==void 0?{session:d}:{}}),v="no media edge resolved";for(let g of await n()){let b;try{b=await fetch(`http://${g}:${tn}${Ir}?${c}`,{method:"POST",headers:{"content-type":"application/json",authorization:s.headers.authorization??""},body:w,signal:AbortSignal.timeout(1e4)})}catch(h){v=`${g}: ${String(h)}`;continue}let E=await b.text();if(b.status===201)return o.writeHead(201,{"content-type":"application/sdp",location:`${qe}/${T}`}),o.end(E),!0;if(b.status>=500||b.status===404||b.status===405||b.status===501){v=`${g}: ${b.status} ${E}`;continue}return r(o,b.status,E),!0}return r(o,503,`no media edge answered the offer (${v})`,"media_edge_unavailable"),!0}}async function Tr(t,e){if(t.startsWith("application/sdp"))return{sdp:e.toString("utf8")};if(!t.startsWith("multipart/form-data"))return{};let n=await new Response(new Uint8Array(e),{headers:{"content-type":t}}).formData(),r=n.get("sdp"),s=n.get("session");return{...typeof r=="string"?{sdp:r}:{},...typeof s=="string"?{session:JSON.parse(s)}:{}}}async function Or(t){let e=[],n=0;for await(let r of t){if(n+=r.length,n>Ar)return null;e.push(r)}return Buffer.concat(e)}function Pr(t,e,n){let r=Er(12),s=_r("aes-256-gcm",t,r),o=Buffer.concat([s.update(JSON.stringify({b:e,e:n}),"utf8"),s.final()]);return Buffer.concat([r,s.getAuthTag(),o]).toString("base64url")}function Cr(t,e){try{let n=Buffer.from(e,"base64url"),r=Sr("aes-256-gcm",t,n.subarray(0,12));r.setAuthTag(n.subarray(12,28));let s=JSON.parse(Buffer.concat([r.update(n.subarray(28)),r.final()]).toString("utf8"));if(typeof s!="object"||s===null||!("b"in s)||!("e"in s))return null;let{b:o,e:i}=s;return typeof o!="string"||typeof i!="number"?null:i>Date.now()/1e3?o:null}catch{return null}}function Nr(t){for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}U();import{SessionAllocationError as zr}from"@urun-sh/core";import{createWebsocketDocConnector as qr}from"@urun-sh/core/internal";import Vr from"ws";U();import{request as $r}from"http";var xr="/pooler/v1/lanes/pick",Dr="/pooler/v1/lanes/status",Hr=1e4,re=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function rn(t,e,n,r,s){return new Promise((o,i)=>{let a=new URL(n,t.baseUrl),l=r===void 0?void 0:Buffer.from(JSON.stringify(r)),p=$r({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...l===void 0?{}:{"content-type":"application/json","content-length":String(l.byteLength)}},timeout:s},d=>{let _=[];d.on("data",A=>_.push(A)),d.on("end",()=>{let A=Buffer.concat(_).toString("utf8"),T=null;try{T=A===""?null:JSON.parse(A)}catch{T=null}o({status:d.statusCode??0,json:T})}),d.on("error",A=>i(new $e(502,"pooler_unreachable",`the pooler channel failed: ${A.message}`)))});p.on("timeout",()=>{p.destroy(new re(`pooler lane surface timed out after ${s}ms (${e} ${n})`))}),p.on("error",d=>i(new $e(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),p.end(l)})}function sn(t,e,n,r){if(t===400&&Mr(e)?.code==="lane_target")return new ct(n,r);if(t===503)return new ae(n);let s=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${s}`)}function Mr(t){if(t===null||typeof t!="object")return null;let e=t.error;return e!==null&&typeof e=="object"?e:null}function on(t){return{async pick({pool:e,app:n,fn:r,sharedApp:s,model:o,holdMs:i=0}){let a=Math.min(Math.max(Math.trunc(i),0),xt),l=await rn(t,"POST",xr,{pool:e,app:n,fn:r,model:o,hold_ms:a,...s?{shared_app:!0}:{}},a+Hr);if(l.status!==200)throw sn(l.status,l.json,e,o);return(l.json?.lanes??[]).filter(d=>typeof d.lane_id=="string"&&d.lane_id!==""&&typeof d.host=="string"&&d.host!=="").map(d=>({laneId:d.lane_id,host:d.host}))},async status(){let e=await rn(t,"GET",Dr,void 0,5e3);if(e.status!==200)throw sn(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}U();import*as q from"yjs";import{SessionDocumentImpl as Wr}from"@urun-sh/core/internal";var Fr=3e4;function Br(t){return(e,n,r)=>{let s=t(e);q.applyUpdate(n,q.encodeStateAsUpdate(s));let o=a=>q.applyUpdate(s,a),i=a=>q.applyUpdate(n,a);return n.on("update",o),s.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",o),s.off("update",i)}}}}function Ve(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?Br(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,s=!1,o=d=>{if(s)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let _=r.get(d);return _||(_=new Wr(d,e,n),r.set(d,_)),_},i=new Map,a=d=>{if(s)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let _=i.get(d);if(!_){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);_=t.streamEndpoint(d),i.set(d,_)}return _},l=d=>{let _="llm-resp:";if(!d.startsWith(_))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${_}<rid>)`);async function*A(){let T=a(d);try{yield*T.messages()}finally{i.delete(d),await T.close()}}return{messages:()=>A(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return o(d)},stream:l,streamEndpoint:a,async end(){},async whenLive(d){let _=o("llm");if(_.synced===!0)return;let A=d?.timeout??t.whenLiveTimeoutMs??Fr;await new Promise((T,c)=>{let w=setTimeout(()=>{v(),c(new Error(`lane ${e} llm doc never synced within ${A}ms`))},A),v=_.onSynced(()=>{clearTimeout(w),d?.signal?.removeEventListener("abort",g),T()}),g=()=>{clearTimeout(w),v(),c(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",g,{once:!0})})},destroy(){s=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,_]of i)i.delete(d),_.close()}}}U();import Ee,{WebSocketServer as Kr}from"ws";import{ENVELOPE_KIND as dn,STREAM_END as Gr,StreamFragmentReassembler as jr}from"@urun-sh/core";var an="/stream/";function ln(t){if(!t.startsWith(an))return null;let e=t.slice(an.length),n=e.indexOf("/");if(n<=0||n===e.length-1||e.includes("/",n+1))return null;try{return{laneId:decodeURIComponent(e.slice(0,n)),name:decodeURIComponent(e.slice(n+1))}}catch{return null}}function Ie(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Re(t){if(t.byteLength<2)throw new Error(`envelope shorter than the 2-byte header (len=${t.byteLength})`);if(t[0]!==1)throw new Error(`bad envelope version ${t[0]}`);let e=t[1];if(e>dn.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var Le=class{reassembler=new jr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===Gr&&this.finish(),n}push(e){this.ended||e===void 0||(this.queue.push(e),this.wake?.(),this.wake=null)}finish(e){this.ended||(this.ended=!0,e&&(this.failure=e),this.wake?.(),this.wake=null)}get isEnded(){return this.ended}async*iterate(){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.failure)throw this.failure;if(this.ended)return;await new Promise(e=>{this.wake=e})}}},Qe=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,s=this.channels.get(r);return s||this.channels.set(r,s={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),s}deliver(e,n,r,s){let o=this.chan(e,n),i=[...o.peers].filter(a=>a!==r);if(i.length===0){let a=o.pending;a.bytes+s.byteLength>cn&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${cn} bytes)`))),a.list.push({envelope:s,producer:r}),a.bytes+=s.byteLength;return}for(let a of i)a.deliver(s)}attach(e,n,r){let s=this.chan(e,n);s.peers.add(r);let o=s.pending;if(o.list.length===0)return;let i=o.list.filter(a=>a.producer!==r);o.list=o.list.filter(a=>a.producer===r),o.bytes=o.list.reduce((a,l)=>a+l.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let s=`${e}::${n}`,o=this.channels.get(s);if(o){for(let i of[...o.peers])i===r&&o.peers.delete(i);o.peers.size===0&&o.pending.list.length===0&&this.channels.delete(s)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let s=this.channels.get(r);this.channels.delete(r);for(let o of s?.peers??[])o.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},cn=8*1024*1024,F=new Qe;function un(t,e){let n=new Le,r={send(s){F.deliver(t,e,r,s)},deliver(s){if(!n.isEnded){try{Re(s)}catch(o){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(o)}`);return}n.push(n.feed(s))}},messages:()=>n.iterate(),async close(){n.finish(),F.detach(t,e,r)}};return F.attach(t,e,r),r}function Jr(t,e){return{deliver(n){e?.();try{t.send(n,{binary:!0})}catch(r){console.warn(`[lane-stream] socket send failed: ${String(r)}`)}},close(n,r){try{t.close(n,r)}catch{}}}}function fn(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,s=new Ee(r,Ie(e)),o=new Le;return s.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Re(a)}catch(l){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(l)}`);return}o.push(o.feed(a))}),s.addEventListener("close",()=>{o.finish(new Error(`lane stream ${r} closed before END`))}),s.addEventListener("error",()=>{o.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Re(i),s.readyState!==Ee.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);s.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>o.iterate(),async close(){o.finish();try{s.close(1e3)}catch{}}}}function Ye(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",s=`${n}\r
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-C452ZIU5.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.47";var y=4141,A=g,M={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 O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}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 $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
1
+ import{h as m}from"./chunk-C452ZIU5.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.48";var y=4141,A=g,M={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 O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}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 $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of h)n[i]=a[i]}}var D=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&D.has(t)}function se(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function ae(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
3
3
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ue(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
4
4
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
@@ -1,2 +1,2 @@
1
- import{c as D}from"./chunk-5D7TVOAX.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
1
+ import{c as D}from"./chunk-RX37QTWI.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
2
2
  `)}return c=f,h=t(),f},y=()=>c===null||t()-h>=s;return{rows(){return y()?(u||(u=_().finally(()=>{u=null})),u):Promise.resolve(c)},close(){c=null,u=null}}}export{G as a,X as b,Y as c,J as d,ne as e};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{D as i,E as w,U as v,V as g,a as d,b as f,l as c}from"../chunk-2KN45E7P.js";import"../chunk-LROCLDDN.js";import"../chunk-CAR4AEQJ.js";import"../chunk-P2YVKUSQ.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-VRNM6ZKU.js";import"../chunk-XGAF2NDT.js";import{v as m,w as p}from"../chunk-5D7TVOAX.js";import"../chunk-XNRPTMSL.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
2
+ import{D as i,E as w,U as v,V as g,a as d,b as f,l as c}from"../chunk-O53WI5BK.js";import"../chunk-25PW2MQZ.js";import"../chunk-CAR4AEQJ.js";import"../chunk-HZNYGJGF.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import{a as S}from"../chunk-LM4E5YM2.js";import"../chunk-YC6TNAKY.js";import"../chunk-XGAF2NDT.js";import{v as m,w as p}from"../chunk-RX37QTWI.js";import"../chunk-XNRPTMSL.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{b as E,c as l}from"../chunk-YSFSRI3D.js";l();var O=E(S(),1);import o from"process";function T(){let r=null;return r=p({streams:o,note:n=>{r?.isDead("stderr")!==!0&&m(o.stderr,n)}}),r}async function $(){T();let r=w(o.env),{server:n,metricsServer:s,edgeIdentityServer:a,closeAll:P,closeWebSockets:I}=v(r);await new Promise((e,t)=>{n.once("error",t),n.listen(r.port,i,e)}),await new Promise((e,t)=>{s.once("error",t),s.listen(d,i,e)}),await new Promise((e,t)=>{a.once("error",t),a.listen(c,i,e)}),o.stdout.write(`inference-proxy listening on http://${i}:${r.port}/v1 (metrics http://${i}:${d}${f}, edge identity http://${i}:${c}, control plane ${r.baseUrl}, org API ${r.apiUrl}, catalog oracle ${r.catalog?"on":"off"})
3
3
  `);let u=async e=>{o.stdout.write(`inference-proxy: ${e} \u2014 draining
4
4
  `),await g(n,P,I),await new Promise(t=>s.close(()=>t())),await new Promise(t=>a.close(()=>t()))};await new Promise(e=>{o.once("SIGINT",()=>{u("SIGINT").finally(e)}),o.once("SIGTERM",()=>{u("SIGTERM").finally(e)})})}$().then(()=>o.exit(0),r=>{o.stderr.write(`inference-proxy: ${String(r instanceof Error?r.stack??r.message:r)}
5
5
  `),o.exit(1)});
@@ -1 +1 @@
1
- import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-2KN45E7P.js";import"../chunk-LROCLDDN.js";import"../chunk-CAR4AEQJ.js";import"../chunk-P2YVKUSQ.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-VRNM6ZKU.js";import"../chunk-XGAF2NDT.js";import"../chunk-5D7TVOAX.js";import"../chunk-XNRPTMSL.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};
1
+ import{A as x,B as v,C as m,D as y,E as B,F as H,G as P,H as u,I as G,J as U,K as F,L as X,M as Y,N as b,O as h,P as k,Q as K,R as V,S as j,T as W,U as q,a as r,b as o,c as t,d as E,e as n,f as _,g as a,h as T,i as O,j as i,k as s,l as I,m as p,n as A,o as R,p as S,q as N,r as C,s as D,t as L,u as M,v as d,w as f,x as l,y as c,z as g}from"../chunk-O53WI5BK.js";import"../chunk-25PW2MQZ.js";import"../chunk-CAR4AEQJ.js";import"../chunk-HZNYGJGF.js";import"../chunk-X5BLQXHK.js";import"../chunk-64VO62LW.js";import"../chunk-YC6TNAKY.js";import"../chunk-XGAF2NDT.js";import"../chunk-RX37QTWI.js";import"../chunk-XNRPTMSL.js";import"../chunk-Q3AIBMET.js";import"../chunk-PXV7QBSD.js";import"../chunk-7KRHHEKZ.js";import"../chunk-C452ZIU5.js";import{c as e}from"../chunk-YSFSRI3D.js";e();export{N as ANONYMOUS_KEY_ID,y as BIND_HOST,R as BUCKET_DOMAIN,O as BoundedLabel,f as ControlPlaneUnavailableError,X as ConversationBackhauls,F as ConversationCapacityError,v as DEFAULT_PORT,I as EDGE_IDENTITY_PORT,A as EDGE_KEY_FINGERPRINT_HEADER,p as EDGE_KEY_ID_HEADER,i as InferenceMetrics,Y as LEDGER_FUNCTION_PATH,b as LEDGER_WRITE_TIMEOUT_MS,V as LedgerClient,h as LedgerDuplicateError,k as LedgerSurfaceError,g as MAX_CACHED_KEYS,G as MAX_CONVERSATIONS,U as MAX_CONVERSATION_HANDLES,n as MAX_MODEL_LABELS,_ as MAX_ORG_LABELS,H as MAX_TENANTS,o as METRICS_PATH,r as METRICS_PORT,E as NO_MODEL_LABEL,c as ORG_BINDING_TTL_MS,t as OTHER_LABEL,x as OrgResolver,d as ProxyAuthError,W as READINESS_TIMEOUT_MS,j as READINESS_TTL_MS,m as SERVE_FUNCTION,S as TIER_DOMAIN,u as TenantRegistry,l as bearerFrom,L as bearerTokenOf,M as createEdgeIdentityServer,q as createHostedProxy,s as createMetricsServer,C as edgeBucketId,D as edgeTierFingerprint,a as laneOf,K as parseLedgerRecorded,B as resolveHostedConfig,T as statusClassOf,P as tenantSubject};