@urun-sh/openai 0.6.36 → 0.6.38

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 +1 @@
1
- import{j as d}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
1
+ import{j as d}from"./chunk-7AI75MPZ.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
@@ -0,0 +1,6 @@
1
+ import{c as w}from"./chunk-YSFSRI3D.js";w();import{randomUUID as Be}from"crypto";w();var p=class extends Error{},ve=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;function Re(n){if(typeof n!="string")return!1;let e=ve.exec(n);if(!e)return!1;let[,t,o,r,i,a,d]=e.map(Number);if(!Number.isFinite(Date.parse(n)))return!1;let s=new Date(Date.UTC(t,o-1,r,i,a,d));return s.getUTCFullYear()===t&&s.getUTCMonth()===o-1&&s.getUTCDate()===r&&s.getUTCHours()===i&&s.getUTCMinutes()===a&&s.getUTCSeconds()===d}function be(n){if(n===null||typeof n!="object")return null;let e=n.shared;if(e==null)return null;if(typeof e!="object")throw new p(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:t,endpoints:o,regions:r,compliance:i}=e;if(typeof t!="string"||t==="")throw new p(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(o))throw new p(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let a=o.map((d,s)=>{if(d===null||typeof d!="object")throw new p(`catalog shared endpoints[${s}] is not an object: ${JSON.stringify(d)}`);let l=d;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new p(`catalog shared endpoints[${s}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new p(`catalog shared endpoints[${s}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let u=(c,g)=>{if(l[c]!==void 0&&l[c]!==null&&!g)throw new p(`catalog shared endpoints[${s}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};u("ready",typeof l.ready=="boolean"),u("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),u("ready_since",Re(l.ready_since));for(let c of["model_id","variant"]){let g=l[c];if(g.includes(":"))throw new p(`catalog shared endpoints[${s}] has "${c}" containing ":" (${JSON.stringify(g)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return u("output_free",typeof l.output_free=="boolean"),l});if(r!=null&&(!Array.isArray(r)||!r.every(d=>typeof d=="string"&&d.length>0)))throw new p(`catalog "shared" block regions is malformed: ${JSON.stringify(r)}`);if(i!=null){let d=i;if(typeof i!="object"||typeof d.zdr!="boolean"||typeof d.hipaa!="boolean")throw new p(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let s of Object.keys(d))if(s!=="zdr"&&s!=="hipaa")throw new p(`catalog "shared" block compliance carries "${s}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return a.length===0?null:{shared_org_id:t,endpoints:a,...r!=null?{regions:r}:{},...i!=null?{compliance:i}:{}}}function S(n){return[...n.endpoints].sort((e,t)=>e.model_id.localeCompare(t.model_id)||e.variant.localeCompare(t.variant))}function Qe(n){let e=n.filter(r=>typeof r.shared_org_id=="string"&&r.shared_org_id!=="");if(e.length===0)return null;let t=e[0].shared_org_id,o=e.map((r,i)=>{let a=d=>new p(`catalog rows[${i}] (${r.model_id}:${r.variant}) shared row is malformed: ${d}`);if(r.shared_org_id!==t)throw a(`shared_org_id ${JSON.stringify(r.shared_org_id)} disagrees with ${JSON.stringify(t)}`);for(let d of["model_id","variant"]){let s=r[d];if(typeof s!="string"||s===""||s.includes(":"))throw a(`"${d}" ${JSON.stringify(s)} is empty or contains ":"`)}if(typeof r.app_slug!="string"||r.app_slug==="")throw a("no app_slug");if(typeof r.function!="string"||r.function==="")throw a("no function");if(r.app_id!==void 0&&r.app_id!==null&&(typeof r.app_id!="string"||r.app_id===""))throw a(`malformed app_id ${JSON.stringify(r.app_id)}`);return{model_id:r.model_id,variant:r.variant,app_slug:r.app_slug,app_id:r.app_id??null,function:r.function,...r.gpu_spec?{gpu_spec:r.gpu_spec}:{},...r.warm!==void 0&&r.warm!==null?{warm:r.warm}:{},...r.compat_default===!0?{compat_default:!0}:{},...r.output_free===!0?{output_free:!0}:{},...r.ready!==void 0&&r.ready!==null?{ready:r.ready}:{},...r.ready_runtimes!==void 0&&r.ready_runtimes!==null?{ready_runtimes:r.ready_runtimes}:{},...r.ready_since?{ready_since:r.ready_since}:{}}});return{shared_org_id:t,endpoints:o}}function D(n,e,t){let o=(e??"").trim();if(o==="")return null;let r=o,i=t,a=o.lastIndexOf(":");a>0&&(r=o.slice(0,a),i=o.slice(a+1));let d=n.endpoints.filter(l=>l.model_id===r);if(d.length===0)return null;if(i!==void 0){let l=d.find(u=>u.variant===i);return l?{shared_org_id:n.shared_org_id,endpoint:l}:null}if(d.length===1)return{shared_org_id:n.shared_org_id,endpoint:d[0]};let s=d.filter(l=>l.compat_default===!0);if(s.length!==1)throw new p(`shared model "${r}" has ${s.length} compat_default rows (exactly one required) among variants ${d.map(l=>l.variant).join(", ")}`);return{shared_org_id:n.shared_org_id,endpoint:s[0]}}async function Xe(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/catalog`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new p(`catalog read failed: GET ${t} \u2192 ${o.status}`);return be(await o.json())}w();function h(n){return n.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}w();var _=class extends Error{name="ModelPriceError"},j="per_million_input_tokens",U="per_million_output_tokens",Q="model_id,variant,unit,price_usd,effective_at,expires_at",Y={per_request:!0,per_minute:!0,per_output_unit:!0},Se=5e3;function $e(n,e){let t=typeof n=="number"?n:typeof n=="string"&&n.trim()!==""?Number(n):NaN;if(!Number.isFinite(t)||t<0)throw new _(`${e}: price_usd is not a non-negative number (${JSON.stringify(n)})`);return t}function X(n,e,t){let o=typeof n=="string"?Date.parse(n):NaN;if(!Number.isFinite(o))throw new _(`${e}: ${t} is not a parseable timestamp (${JSON.stringify(n)})`);return o}function Te(n,e,t){return n===null?null:X(n,e,t)}function ke(n,e){if(n===j)return"input";if(n===U)return"output";if(typeof n=="string"&&Object.hasOwn(Y,n))return null;throw new _(`${e}: unit ${JSON.stringify(n)} is neither a per-token rate (${j} | ${U}) nor a known GPU-time unit (${Object.keys(Y).join(" | ")}). Skipping it would publish no prices forever with no signal \u2014 if ENG-317 named the per-token units differently, teach this module the new names instead`)}function Pe(n,e){let t=n.reduce((r,i)=>i.effective_at>r.effective_at?i:r,n[0]),o=n.find(r=>r.effective_at===t.effective_at&&r.usd!==t.usd);return o?{reason:`two ${e} rates are effective at the same instant (${t.usd} and ${o.usd} USD/Mtok), so the winner would be read order \u2014 this model is served UNPRICED until one of them is expired; expire one of them`}:{rate:t}}function J(n,e){return`${n}\0${e}`}function xe(n){if(!Array.isArray(n))throw new _(`model_prices read is not an array: ${JSON.stringify(n)}`);let e=[];for(let t=0;t<n.length;t++){let o=n[t],r=`model_prices[${t}]`;if(o===null||typeof o!="object"||Array.isArray(o))throw new _(`${r} is not an object: ${JSON.stringify(o)}`);let i=o;for(let l of Q.split(","))if(!Object.hasOwn(i,l))throw new _(`${r} has no "${l}" column: ${JSON.stringify(i)}`);let a=ke(i.unit,r);if(a===null)continue;let d=i.model_id;if(typeof d!="string"||d==="")throw new _(`${r} has no model_id (${JSON.stringify(i)})`);let s=i.variant;if(!(s===null||typeof s=="string"&&s!==""))throw new _(`${r} has a non-string variant (${JSON.stringify(s)})`);e.push({model_id:d,variant:s,side:a,usd:$e(i.price_usd,r),effective_at:X(i.effective_at,r,"effective_at"),expires_at:Te(i.expires_at,r,"expires_at")})}return e}function Z(n,e=Date.now(),t){let o=new Map,r=new Map;for(let s of n){if(s.effective_at>e||s.expires_at!==null&&s.expires_at<=e)continue;let l=o.get(s.model_id);l||(l=new Map,o.set(s.model_id,l),r.set(s.model_id,new Map));let u=s.variant??"",c=l.get(u);c||(c={input:[],output:[]},l.set(u,c),r.get(s.model_id).set(u,s.variant)),c[s.side].push({effective_at:s.effective_at,usd:s.usd})}let i=[],a=[];for(let[s,l]of o){let u=l.get(""),c=(g,f,v)=>{let m=g&&g.length>0?g:u?.[f];if(!m||m.length===0)return null;let y=Pe(m,f);return"reason"in y?y:y.rate.usd===0?f==="output"&&v!==null&&t?.has(J(s,v))?y.rate:{reason:`the ${f} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:y.rate};for(let[g,f]of r.get(s)){let v=l.get(g),m=c(v?.input,"input",f),y=c(v?.output,"output",f);if(m!==null&&"reason"in m){a.push({model_id:s,variant:f,reason:m.reason});continue}if(y!==null&&"reason"in y){a.push({model_id:s,variant:f,reason:y.reason});continue}m===null||y===null||i.push({model_id:s,variant:f,pricing:{input:m.usd,output:y.usd}})}}let d=(s,l)=>s.model_id.localeCompare(l.model_id)||(s.variant===null?1:0)-(l.variant===null?1:0)||(s.variant??"").localeCompare(l.variant??"");return{prices:i.sort(d),refusals:a.sort(d)}}function E(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===e);if(o)return o.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===null);return r?r.pricing:null}var A={prices:[],refusals:[]};async function rt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${Q}&unit=in.(${t})`,{headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`},signal:AbortSignal.timeout(Se)});if(!o.ok)throw new Error(`model_prices fetch failed: ${o.status}`);return xe(await o.json())}w();var dt="/partners/openrouter/models",Ce={chat:!0,code:!0,agent:!0,vl:!0},ee={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ee(n){let e=n.toLowerCase();return Object.hasOwn(ee,e)?ee[e]:null}var te={"us-east-1":"US","us-east-2":"US","us-west-1":"US","us-west-2":"US","ca-central-1":"CA","ca-west-1":"CA","sa-east-1":"BR","eu-central-1":"DE","eu-central-2":"CH","eu-west-1":"IE","eu-west-2":"GB","eu-west-3":"FR","eu-north-1":"SE","eu-south-1":"IT","eu-south-2":"ES","af-south-1":"ZA","ap-east-1":"HK","ap-south-1":"IN","ap-south-2":"IN","ap-northeast-1":"JP","ap-northeast-2":"KR","ap-northeast-3":"JP","ap-southeast-1":"SG","ap-southeast-2":"AU","ap-southeast-3":"ID","ap-southeast-4":"AU","ap-southeast-5":"MY","ap-southeast-7":"TH","il-central-1":"IL","me-central-1":"AE","me-south-1":"BH"};function Ae(n,e){if(!n||n.length===0)return[];let t=[],o=[];for(let r of n){let i=Object.hasOwn(te,r)?te[r]:null;if(i===null){o.push(r);continue}t.some(d=>d.region===r)||t.push({country_code:i,region:r})}return o.length>0&&e(`urun openrouter doc: shared block region(s) ${o.join(", ")} have no country mapping \u2014 omitted from datacenters, never guessed`),t}var ne={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},re={2:"Llama2",3:"Llama3"};function Oe(n){if(!n)return null;let e=n.split("@")[0],t=e.indexOf("/"),o=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<o.length;r+=1){let i=o[r];if(Object.hasOwn(ne,i))return ne[i];let a=o[r+1];if(i==="llama"&&a!==void 0&&Object.hasOwn(re,a))return re[a];if(i==="phi"&&a!==void 0&&/^\d/.test(a))return"Phi"}return null}var Me=["context_length","max_model_len"];function Ie(n){let e=Me.map(t=>n.engine_args?.[t]).filter(t=>typeof t=="number"&&Number.isFinite(t)&&t>0);return e.length===0?null:e.every(t=>t===e[0])?e[0]:null}function N(n){let e=n.map(Ie),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function Ne(n){let e=n.engine_args?.reasoning_parser;return e==null||e===""?!1:typeof e=="string"?!0:null}function K(n){if(n.length===0)return null;let e=n.map(Ne),t=e[0];return t==null?null:e.every(o=>o===t)?t:null}function B(n,e){let t=e.filter(r=>r.serve_app_slug===n);return new Set(t.map(r=>r.model_id)).size===1?t:[]}function Le(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return O(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return O(o);let r=B(n,e);return r.length>0?O(r):null}function O(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e:Fe(n),matches:n}:null}function Fe(n){let e=n[0],t=o=>n.every(r=>(r[o]??void 0)===(e[o]??void 0))?e[o]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),updated_at:t("updated_at")}}var $=class extends Error{name="ModelCreatedError"};function T(n){if(n.length===0)return 0;let e=`${n[0].model_id}:${n[0].variant}`,t=n.map(u=>u.created_at??void 0);if(t.some(u=>u===void 0))throw new $(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let o=t[0];if(!t.every(u=>u===o))throw new $(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(t)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(r===null)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let i=Number(r[1]),a=Number(r[2]),d=Number(r[3]),s=Date.UTC(i,a-1,d),l=new Date(s);if(l.getUTCFullYear()!==i||l.getUTCMonth()!==a-1||l.getUTCDate()!==d)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 not a real calendar date`);return s/1e3}function b(n){let e={id:n.id,object:n.object,created:n.created,owned_by:n.owned_by,...n.context_length!==void 0?{context_length:n.context_length}:{},...n.pricing!==void 0?{pricing:n.pricing}:{},...n.voices!==void 0?{voices:n.voices}:{},...n.capabilities!==void 0?{capabilities:n.capabilities}:{}};return"image_modes"in n?{...e,image_modes:n.image_modes}:e}function L(n,e,t){let o=Le(n,e);if(!o)return b({id:n,object:"model",created:0,owned_by:"urun"});let{row:r,matches:i}=o,a=N(i),d=T(i),s=E(r.model_id,r.variant,t),l=se(r,i),u=K(i);return b({id:n,object:"model",created:d,owned_by:"urun",...a!==null?{context_length:a}:{},...s!==null?{pricing:s}:{},...l.published.length>0?{voices:[...l.published]}:{},...u!==null?{capabilities:{reasoning:u}}:{}})}var De=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function se(n,e){if((n.task??void 0)!=="tts")return{published:[],defect:null};let t=e.map(i=>i.engine_args?.voices),o=t[0];if(Array.isArray(o)&&o.length>0&&o.every(i=>typeof i=="string")&&t.every(i=>Array.isArray(i)&&i.length===o.length&&i.every((a,d)=>a===o[d])))return{published:[...o],defect:null};let r=t.some(i=>i!=null)?`the catalog's engine_args.voices for ${n.model_id}:${n.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return n.model_id==="qwen3-tts-customvoice"?{published:[...De],defect:r}:{published:[],defect:r}}function z(n){let e=n.length>0?O(n):null;return e===null?{published:[],defect:null}:se(e.row,e.matches)}function oe(n){let e=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/.exec(String(n));if(!e)throw new Error(`unrenderable per-token price: ${String(n)}`);let[,t="",o="",r=""]=e,i=t+o,a=t.length-6+(r===""?0:Number(r));return(a<=0?`0.${"0".repeat(-a)}${i}`:`${i.slice(0,a)}.${i.slice(a).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function ie(n){return{input:[{type:"prompt",unit:"token",cost_usd:oe(n.input)}],output:[{type:"completion",unit:"token",cost_usd:oe(n.output)}]}}function je(n,e,t,o){if(e.length===0)return null;let r=O(e);if(!r)return null;let{row:i,matches:a}=r;if(!i.task||Ce[i.task]!==!0)return null;let d=N(a),s=E(i.model_id,i.variant,t),l=Oe(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:T(a),quantization:Ee(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&s!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...s?{pricing:ie(s).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...s?{pricing:ie(s).output}:{}}],...o.datacenters.length>0?{datacenters:o.datacenters}:{},...o.compliance?{compliance:o.compliance}:{}}}function ae(n,e,t,o){let r=o??(l=>console.warn(l.trimEnd())),i=n?S(n):[];if(i.length>0){let l=i.filter(u=>u.ready===void 0);if(l.length===i.length)r("urun openrouter doc: readiness seam absent from shared block; declaring every endpoint not ready");else if(l.length>0){let u=l.map(c=>`${c.model_id}:${c.variant}`).join(", ");r(`urun openrouter doc: readiness seam partially deployed \u2014 endpoints ${u} carry no ready field and are declared not ready`)}}let a={datacenters:Ae(n?.regions,r),compliance:n?.compliance??null},d=[],s=new Set;for(let l of i){let u=`${l.model_id}:${l.variant}`;if(s.has(u))continue;s.add(u);let c=je(l,e.filter(g=>g.model_id===l.model_id&&g.variant===l.variant),t,a);c&&d.push(c)}return{data:d}}w();var le={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_eager_end:!0,turn_resumed:!0},k=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function de(n){let e=n.t;if(typeof e!="string"||!(e in le))throw new k(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(le).join(", ")}`);let t={kind:e};return typeof n.delta=="string"&&(t.text=n.delta),typeof n.start_ms=="number"&&Number.isFinite(n.start_ms)&&(t.startMs=n.start_ms),t}function Ue(n){if(typeof n=="string"){let e;try{e=JSON.parse(n)}catch(t){throw new k(`the "stt" transcript lane delivered a string payload that is not valid JSON (${t instanceof Error?t.message:String(t)})`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new k(`the "stt" transcript lane delivered a JSON string that is not an object (${JSON.stringify(e)})`);return de(e)}if(n===null||typeof n!="object"||Array.isArray(n))throw new k(`the "stt" transcript lane delivered a non-object payload (${Array.isArray(n)?"array":typeof n}) \u2014 transcript events are {"t":\u2026,"delta":\u2026,"start_ms":\u2026} objects (or their JSON serialization)`);return de(n)}function ue(n){return n.reason instanceof Error?n.reason:new Error("the turn-lane consumer aborted")}async function Je(n,e){return e.aborted?"aborted":await new Promise(t=>{let o=!1,r=a=>{o||(o=!0,e.removeEventListener("abort",i),t(a))},i=()=>r("aborted");e.addEventListener("abort",i,{once:!0}),n.then(()=>r("pulled"),()=>r("pulled"))})}function pt(n,e){let t=n.stream("stt");if(typeof t.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*o(){let r=t.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw ue(e);let i=r.next();if(e!==void 0&&await Je(i,e)==="aborted")throw i.catch(()=>{}),ue(e);let a=await i;if(a.done)return;yield Ue(a.value)}}finally{let i=r.return?.();i&&i.catch(()=>{})}}return o()}var bt="https://api.urun.sh/v1",P=class extends Error{},I=class extends Error{},G="urs1.";function ce(n,e){return G+Buffer.from(JSON.stringify([n,e]),"utf8").toString("base64url")}function pe(n){if(!n.startsWith(G))return null;try{let e=JSON.parse(Buffer.from(n.slice(G.length),"base64url").toString("utf8"));if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{app:e[0],key:e[1]}}catch{}return null}async function St(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/apps`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}function ge(n){if(n.length===0)return[];if(!n.every(t=>(t.task??void 0)==="image"))return[];let e=Ve(n);return e===null?[]:[e]}function ze(n){if(n==null)return null;if(typeof n!="object"||Array.isArray(n))return process.stderr.write(`[serving-pool] skipping malformed engine_args.pool (not an object): ${JSON.stringify(n)}
2
+ `),null;let e={},t=[["min",0],["max",1],["in_flight_cap",1],["idle_grace_s",0],["warm_wait_s",1]],o=!1;for(let[r,i]of t){let a=n[r];if(a==null)continue;let d=typeof a=="number"?a:typeof a=="string"?Number.parseInt(a,10):NaN;if(!Number.isInteger(d)||d<i){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(r)}=${JSON.stringify(a)})
3
+ `),o=!0;break}e[r]=d}return o||Object.keys(e).length===0?null:e}function He(n,e){if(n.length===0)return null;let t;return e.modelId&&(t=n.find(o=>o.model_id===e.modelId&&(!e.variant||o.variant===e.variant))),t||(t=n.find(o=>o.serve_app_slug===e.appSlug||h(`${o.model_id}-${o.variant}`)===e.appSlug||h(o.model_id)===e.appSlug)),t?ze(t.engine_args?.pool):null}function H(n,e,t,o,r){if(!r)throw new p(`shared model "${n}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||t===void 0)throw new p(`shared model "${n}" resolved without a catalog id + variant to join on`);let i=o.filter(a=>a.model_id===e&&a.variant===t);if(i.length===0)throw new p(`shared model "${n}" names endpoint ${e}:${t} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function fe(n,e){if(!e.every(r=>(r.task??void 0)==="image"))return[];let t=e.map(r=>r.engine_args?.expects_image),o=t[0];if(typeof o!="boolean"||!t.every(r=>r===o))throw new p(`shared image model "${n}" does not vouch an explicit image mode: its ${e.length} model_catalog row(s) carry engine_args.expects_image ${JSON.stringify(t)} \u2014 the shared lane requires a boolean (false = pure text-to-image generation, true = edit) and refuses to silently default to edit`);return[o===!1?"generation":"edit"]}var we="shared:",he="speech:",qe="realtime:";function q(n){return n.sharedApp?we+n.appSlug:n.appSlug}function me(n){return typeof n.modelId=="string"&&typeof n.variant=="string"?{kind:"catalog",model_id:n.modelId,variant:n.variant}:{kind:"not-a-catalog-model",model:n.appSlug}}function V(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return t;let o=e.filter(i=>h(i.model_id)===n);return new Set(o.map(i=>i.variant)).size===1?o:[]}function Ge(n){let e=n.engine_args?.expects_image;return e==null?"edit":e===!1?"generation":e===!0?"edit":null}function Ve(n){let e=n.map(Ge),t=e[0];return t!=null&&e.every(o=>o===t)?t:null}var We={stt:"stt",tts:"tts"};function R(n){if(n.length===0)return null;let e=n[0].task??void 0,t=n.every(r=>(r.task??void 0)===e),o=e===void 0?void 0:We[e];return o!==void 0?t?o:null:t&&n.every(r=>r.engine_args?.realtime===!0)?"decision":null}function _e(n,e){let t=V(n,e);return t.length>0?t:B(n,e)}function M(n,e){return _e(n.appSlug,e)}function Ye(n){let e=n.map(o=>o.engine_args?.transcript_stream).filter(o=>o!=null);if(e.length===0)return"stt";let t=e[0];if(typeof t!="string"||t.length===0||!e.every(o=>o===t))throw new p(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return t}var F=6e4,ye=class{constructor(e){this.opts=e}opts;pool=new Map;apps={current:null};rows={current:null};shared={current:null};async swr(e,t,o){let r=e.current;return r&&Date.now()-r.at<o?r.value:r?(r.refreshing||(r.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{r.refreshing=void 0}})()),r.value):(e.current={at:Date.now(),value:await t()},e.current.value)}seed(e,t){this.pool.set(e,Promise.resolve(t))}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??F):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??F):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??F):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??F;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let t=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:t},t}async pricesForListing(e){let t;try{t=await this.priceRows()}catch(r){if(r instanceof _)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
4
+ `),A}let o=Z(t,Date.now(),e);for(let r of o.refusals)this.warn(`urun /v1/models: refusing to price ${r.model_id}:${r.variant??"*"} \u2014 ${r.reason}
5
+ `);return o}outputFreeKeys(e){let t=new Set;if(!e)return t;for(let o of e.endpoints)o.output_free===!0&&t.add(J(o.model_id,o.variant));return t}warn(e){(this.opts.warn??(o=>console.warn(o.trimEnd())))(e)}servable(e){return e.filter(t=>t.serves==="openai"&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=this.opts.defaultApp,t=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())r.startsWith(we)||r.startsWith(he)||t.add(r);let o=[...t].filter(r=>r!==e).sort();return e===null?o:[e,...o]}async noDefaultApp(e){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new P(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${o}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${o}`)}async sharedLane(e){if(!this.opts.shared)return null;let t=await this.sharedBlock();if(!t)return null;let o=D(t,e);if(o)return o;let r=e.lastIndexOf(":"),i=r>0?e.slice(0,r):e,a=r>0?e.slice(r+1):void 0,d=h(i),s=t.endpoints.filter(c=>h(c.model_id)===d&&(a===void 0||c.variant===a)),l=new Set(s.map(c=>c.model_id)),u=[...l][0];return u===void 0||l.size!==1?null:D(t,u,a)}async resolveTarget(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):{appSlug:o};let r=h(t);if(r===o)return{appSlug:o};let i=await this.sharedLane(t);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:i.shared_org_id,gpuSpec:i.endpoint.gpu_spec??void 0,appId:i.endpoint.app_id??void 0};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let a=await this.deployedApps(),d=this.servable(a);if(d.includes(r))return{appSlug:r};let s=d.filter(u=>u.startsWith(`${r}-`));if(s.length===1)return{appSlug:s[0]};if(s.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${s.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=a.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(l)throw new P(`model "${t}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let d=(await this.opts.listCatalog()).find(s=>t===s.model_id||t===`${s.model_id}:${s.variant}`||r===h(s.model_id)||r===h(`${s.model_id}-${s.variant}`));if(d)throw new P(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${d.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):{appSlug:o}}async catalogIdentityFor(e){let t=me(await this.resolveTarget(e));return t.kind==="catalog"?{model_id:t.model_id,variant:t.variant}:null}async poolTuningFor(e){return He(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return q(await this.resolveTarget(e))}async sessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,q(t))}async resolveTargetFor(e){return this.resolveTarget(e)}async speechSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,he+q(t))}async dedicatedSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,qe+Be())}async evictHandle(e){let t=pe(e);if(!t)return;let o=this.pool.get(t.app);if(!o)return;let r=await o.then(i=>i,()=>null);r!==null&&await this.evict(t.app,r)}async acquire(e,t){let o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(e,t)),this.pool.set(t,o),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o,identity:me(e)}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(e);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(e){let{app:t,entry:o}=await this.sessionFor(e);return{app:t,handle:ce(t,this.keyOf(o))}}async speechHandleFor(e){let{app:t,entry:o}=await this.speechSessionFor(e);return{app:t,handle:ce(t,this.keyOf(o))}}async sessionForHandle(e){let t=pe(e);if(!t)throw new I(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,i=this.pool.get(o),a=i?await i.then(d=>d,()=>null):null;if(a===null)throw new I(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(a)!==r)throw new I(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:a}}async evict(e,t){let o=this.pool.get(e);!o||await o.then(i=>i,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[o,r]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=o.rows,a=o.ok?r:A;o.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
6
+ `);let s=(t?S(t):[]).map(l=>{let u=i.filter(W=>W.model_id===l.model_id&&W.variant===l.variant),c=N(u),g=T(u),f=K(u),v=E(l.model_id,l.variant,a),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?s:[...e.map(l=>L(l,i,a)),...s]}}async openRouterModels(){let e=await this.sharedBlock(),[t,o]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return ae(e,t,o,r=>this.warn(r))}async supportsImages(e,t){let o=await this.resolveTarget(e),r=await this.catalogRows();if(o.sharedApp){let i=H(String(e),o.modelId,o.variant,r,this.opts.listCatalog!==null);return fe(`${o.modelId}:${o.variant}`,i).includes(t)}return ge(V(o.appSlug,r)).includes(t)}async supportsAudio(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))!==null:R(M(t,o))!==null}async supportsSpeech(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="tts":R(M(t,o))==="tts"}async supportsTranscription(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="stt":R(M(t,o))==="stt"}async transcriptStreamFor(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):M(t,o);return Ye(r)}async speechVoices(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):M(t,o);return z(r)}async imageModelList(){let e=await this.catalogRows(),t=A,o=[];for(let i of await this.availableIds()){let a=ge(V(i,e));a.length!==0&&o.push(b({...L(i,e,t),image_modes:a}))}let r=await this.sharedBlock();if(r)for(let i of S(r)){let a=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),d=fe(`${i.model_id}:${i.variant}`,a);if(d.length===0)continue;let s=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(a),owned_by:"urun",image_modes:d});o.push(s)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=A,o=[];for(let i of await this.availableIds())R(_e(i,e))==="stt"&&o.push(L(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let a=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(a)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(a),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,Qe as b,Xe as c,rt as d,dt as e,$ as f,pt as g,bt as h,P as i,I as j,ce as k,pe as l,St as m,He as n,he as o,qe as p,q,me as r,ye as s};
@@ -1,4 +1,4 @@
1
- import{h as m}from"./chunk-6K7NOPD5.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.36";var y=4141,R=g,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
1
+ import{h as m}from"./chunk-7AI75MPZ.js";import{c as h}from"./chunk-YSFSRI3D.js";h();import w from"os";import U from"path";import{fileURLToPath as _}from"url";import{format as S}from"util";var g="0.6.38";var y=4141,R=g,J={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function P(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function B(e,t,n){let r={...e,...P(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function K(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(u=>u==="-m"||u==="--model"||u.startsWith("--model=")),i=n[0]==="exec",d=s.includes("--skip-git-repo-check"),p=i&&!d?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function M(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function F(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function H(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=_(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function V(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function X(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function z(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function c(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function Q(e){let t=N(c(e,"URUN_BASE_URL")),n=c(e,"URUN_ORG_ID"),r=c(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let d=(e.URUN_API_KEY??"").trim();if(d){let p=(e.URUN_GATEWAY_URL??"").trim(),u=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:d,gatewayUrl:u}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function N(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function Z(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:R}}function I(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var k=250;async function A(e,t=k){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:d}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof d!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:d}}catch{return null}}var v=2e3;async function O(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function ee(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await A(n);if(o!==null&&I(o,t)){let s=await O(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function te(e,t=w.homedir()){return U.join(t,".urun","logs",`compat-proxy-${e}.log`)}var l=["log","info","warn","error","debug","trace"];function ne(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...d)=>e.write(i,...d);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(l.map(i=>[i,n[i]]));for(let i of l)n[i]=(...d)=>{e.write(`${S(...d)}
2
2
  `)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of l)n[i]=a[i]}}var j=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&j.has(t)}function re(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function oe(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
3
3
  `)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ie(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
4
4
  `)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
@@ -0,0 +1,2 @@
1
+ import{a as V}from"./chunk-CAR4AEQJ.js";import{f as ne,g as N,h as oe,i as te}from"./chunk-YOFTYCYH.js";import{c as j,f as G,g as B,p as q}from"./chunk-6M5JK4YC.js";import{a as se,b as U}from"./chunk-5MH6NSR2.js";import{a as T}from"./chunk-4NMMWAKD.js";import{b as K,c as J,d as X,g as Q,j as R,k as M,l as D,m as z,p as Y,q as b,r as Z,s as ee}from"./chunk-7AI75MPZ.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as x,createClientToken as de,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ee,DEFAULT_WHEN_LIVE_TIMEOUT_MS as le,isWakingPhase as ve,SessionFailedError as Ae}from"@urun-sh/core";A();import{SessionFailedError as ge}from"@urun-sh/core";var C=2;function we(e){let i=e?.type;return i==="response.created"||i==="response.in_progress"}function ye(e){let i=e?.type;return i==="response.completed"||i==="error"}function ae(e){return async function(c,l){let f=await e.sessionFor(c.model);return(async function*(){for(let d=1;d<=C;d++){let{app:w,entry:g,identity:S}=d===1?f:await e.sessionFor(c.model);l?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let s=!1,a=!1;try{let u=await e.createStream(g,c);for await(let m of u){if(ye(m)&&(s=!0),we(m)){if(d>1)continue}else a=!0;yield m}}catch(u){if(u instanceof ge&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(d<C&&!a){await e.evict(w,g);continue}throw u}if(s)return;if(d<C&&!a){await e.evict(w,g);continue}return}})()}}import{randomUUID as pe}from"crypto";A();import{encodeStreamEnvelope as he}from"@urun-sh/core";var Se="audio";function ce(e){let i=e.streamEndpoint(Se);return{sessionId:e.id,appendInputAudio(c){let l=Buffer.from(c,"base64");l.byteLength!==0&&i.send(he(new Uint8Array(l)))},onOutputAudio(){return()=>{}}}}var Oe=0,be=4,Ie=4;function Qe(e,i){let c=(d,w)=>{let g=(e[d]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${d} must be a positive integer (got ${JSON.stringify(e[d])})`);return S},l=(e.URUN_DECISION_POOL_MIN??"").trim();if(l==="0")return null;let f=l?Number.parseInt(l,10):Oe;if(!Number.isInteger(f)||f<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let r=c("URUN_DECISION_POOL_MAX",Math.max(f,be));return{min:f,max:r,idleGraceMs:3e4,inFlightCap:c("URUN_DECISION_POOL_INFLIGHT_CAP",Ie),replicaId:(e.URUN_REPLICA_ID??"").trim()||i||"proxy"}}function ze(e){let i=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!i)return N;let c=Number.parseInt(i,10);if(!Number.isInteger(c)||c<=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 c*1e3}function $(e,i,c,l){let f=e[c];if(typeof f!="function")throw new Error(`app "${i}" has no function "${c}" (set URUN_FUNCTION)`);let r=l?f(void 0,l):f();if(typeof r.end!="function")throw new Error(`app "${i}" function "${c}" returned a session without end()`);return r}function ue(e,i,c,l){let{baseUrl:f,orgId:r,auth:d}=e,w=i.fnName??e.fnName,g=e.sessionStartOptions?.(c),S=l||g||i.sharedApp?{...i.sharedApp?{sharedApp:!0}:{},...g,...l}:void 0,s=y=>({session:y,responses:new T(y),gone:se(y,c)});if(d.lane==="jwt"){let y=x(i.appSlug,{baseUrl:f,orgId:r,jwt:d.jwt});return s($(y,i.appSlug,w,S))}if(d.lane==="machine"){let{machineToken:y,gatewayUrl:k}=d,I=(typeof e.subject=="function"?e.subject():e.subject)??pe(),n=x(i.appSlug,{baseUrl:f,orgId:r,getAccessToken:async()=>(await de(y,{baseUrl:k,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:I,...i.sharedApp?{sharedApp:!0}:{}})).token});return s($(n,i.appSlug,w,S))}let{apiKey:a,gatewayUrl:u}=d,m=(typeof e.subject=="function"?e.subject():e.subject)??pe(),h=x(i.appSlug,{baseUrl:f,orgId:r,getAccessToken:async()=>(await de(a,{baseUrl:u,expiresIn:300,allowedFunctions:[`${i.appSlug}/${w}`],subject:m,...i.sharedApp?{sharedApp:!0}:{}})).token});return s($(h,i.appSlug,w,S))}function fe(e){let i=e.session.id;if(typeof i!="string"||i.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 i}function me(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let i=e.status.error?.httpStatus,c=e.status.error?.code;return i===410||i===409&&(c==="cancelled"||c==="expired")?!0:c==="client_ended"}var _e=new Set(["error","paused"]);function Ye(e){let{auth:i,catalog:c}=e,l=null,f=(d,w)=>{let g=ue(e,d,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{l?.evict(w,g)}),g},r=new ee({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:f,closeSession:async d=>{if(d.gone.dispose(),e.release==="detach"){if(typeof d.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');d.session.detach();return}await d.session.end()},listApps:i.lane==="api-key"?()=>z({apiUrl:e.apiUrl,apiKey:i.apiKey}):null,listCatalog:e.catalogRows??(c?()=>V(c):null),listPrices:c?()=>X(c):null,shared:i.lane==="api-key"?()=>J({apiUrl:e.apiUrl,apiKey:i.apiKey}):i.lane==="machine"&&e.catalogRows?async()=>{let d=await e.catalogRows();return K(d)}:null,sessionKey:fe});return l=r,e.defaultApp!==null&&r.seed(e.defaultApp,f({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),r}function Ze(e,i){let c=e.decisionPool;if(!c)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let l=c.replicaId??"proxy",f=new Map,r=new Map,d=new Map,w=s=>{process.stderr.write(`[decision-pool] ${s}
2
+ `)},g=(s,a)=>{let u=f.get(a);if(u)return u;let m=new ne({min:c.min,max:c.max,idleGraceMs:c.idleGraceMs,inFlightCap:c.inFlightCap,replicaId:l,openSlot:async h=>{let y=ue(e,s,a,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>m.markSessionDead(y)),await L(y.session),w(`slot attached pool=${a} slot=${h.concurrencyKey} session=${y.session.id??"(no id)"}`),y},closeSlot:async h=>{h.gone.dispose(),await h.session.end()},onDetach:(h,y)=>w(`slot detached pool=${a} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof Ae&&me(h)});return r.set(a,{target:s,env:c}),f.set(a,m),m},S=async(s,a)=>{let u=r.get(a);if(u)try{let m=await i.poolTuningFor(s);g(s,a).retune({min:m?.min??u.env.min,max:m?.max??u.env.max,inFlightCap:m?.in_flight_cap??u.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:u.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){w(`pool tuning refresh failed pool=${a} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let s={appSlug:e.defaultApp};await g(s,b(s)).boot()},async sessionFor(s){let a=await i.resolveTargetFor(s),u=b(a),m=g(a,u);await S(a,u);let h=await m.acquire({timeoutMs:m.requestWaitMs}),y=d.get(h.entry)??[];return y.push(h),d.set(h.entry,y),{app:u,entry:h.entry,identity:Z(a)}},async warmFor(s){let a=await i.resolveTargetFor(s);await g(a,b(a)).boot()},end(s){let a=d.get(s)?.shift();a&&(d.get(s)?.length===0&&d.delete(s),a.release())},evict(s){for(let a of f.values())a.evict(s)},markSessionDead(s){for(let a of f.values())a.markSessionDead(s)},reap(){for(let[s,{target:a}]of r)S(a,s).then(()=>{let u=f.get(s);u&&u.reap()})},async pingReady(s){for(let a of f.values())if(await a.pingReady(s))return!0;return!1},stats(){return[...f.entries()].map(([s,a])=>({poolKey:s,...a.stats()}))},async drain(s){await Promise.all([...f.values()].map(a=>a.drain({timeoutMs:s})))},async close(){await Promise.all([...f.values()].map(s=>s.close()))}}}function Le(e){return ve(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?le:Ee:le}async function L(e,i){let c=e.whenLive;if(typeof c!="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 c.call(e,{timeout:Le(e.phase),signal:i})}async function H(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}function _(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function en(e,i=B,c,l,f=N,r){let d=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,s=new WeakMap,a=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},u="lane",m=n=>{let o=D(n);if(!r||!o||o.app!==u)return null;let t=r.entryFor(o.key);if(!t)throw new R(`the lane behind this handle (${o.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:o.key,entry:t}},h=async n=>m(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=d.get(n);if(!o){let t={waiting:0,gone:new AbortController};s.set(n,t),o=(async()=>{if(await L(n.session,t.gone.signal),t.gone.signal.aborted)throw _(t.gone.signal);s.get(n)===t&&s.delete(n);let p=await j(n.session,await i());return Object.assign(p,{sessionId:n.session.id})})(),d.set(n,o),o.catch(()=>{d.get(n)===o&&d.delete(n)}),o.then(()=>{s.get(n)===t&&s.delete(n)},()=>{s.get(n)===t&&s.delete(n)})}return o},k=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:p=>t.appendInputAudio(p),onOutputAudio:p=>t.onOutputAudio(p),sessionId:a(n)}})(),S.set(n,o),o.catch(()=>{S.get(n)===o&&S.delete(n)})),o},I=async(n,o,t)=>{if(t?.aborted){let E=s.get(n);throw(d.get(n)===void 0||E!==void 0&&E.waiting===0)&&await H(n.session),_(t)}let p=o(n),P=s.get(n);return P!==void 0&&P.waiting++,t===void 0?p:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&s.get(n)===P&&(P.gone.abort(),s.delete(n),d.delete(n),S.delete(n),H(n.session).catch(()=>{})),v(_(t))};t.addEventListener("abort",O,{once:!0});let W=()=>t.removeEventListener("abort",O);p.then(F=>{W(),E(F)},F=>{W(),v(F)})})};return{createResponse:ae({sessionFor:r?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return l?l.sessionFor(n):e.sessionFor(n)}:l?n=>l.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>a(n),evict:(n,o)=>{r&&r.owns(o)?r.evict(o):l?l.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{me(t)&&(r&&r.owns(o)?r.evict(o):l?l.markSessionDead(o):e.evict(n,o),c?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await L(n.session);let t=oe(U(await n.responses.responses.create(o),n.gone),f);if(!l&&!r)return t;let p=n;return(async function*(){try{yield*t}catch(E){throw te(E)&&(r&&r.owns(p)?r.evict(p):l&&(E instanceof R?l.markSessionDead(p):l.evict(p))),E}finally{r&&r.owns(p)?r.release(p):l?.end(p)}})()}catch(t){throw r&&r.owns(n)?r.release(n):l&&l.end(n),t}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,o)=>e.supportsImages(n,o),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,o)=>{let{entry:t}=await e.sessionFor(n);return await I(t,y,o)},openAudioOn:async(n,o,t)=>{let p=m(n);if(p){let E=p.entry.session;return ce(E)}let{entry:P}=await e.sessionForHandle(n);return await I(P,k,o)},openTurnsOn:async function*(n,o){if(o?.aborted)throw _(o);let t=await h(n);yield*Q(t.session,o)},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=G(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=q(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(r){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await r.sessionFor(n,o),p=a(t.entry);if(p===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return M(u,p)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:t,entry:p}=await e.dedicatedSessionFor(n);return M(t,fe(p))},releaseSessionHandle:n=>{let o=D(n);if(!o)return;if(o.app.startsWith(Y)){(async()=>{let p=null;try{p=(await e.sessionForHandle(n)).entry}catch{return}await H(p.session).catch(()=>{}),await e.evict(o.app,p)})();return}if(!r||o.app!==u)return;let t=r.entryFor(o.key);t&&r.release(t)},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:o,entry:t}=await e.sessionForHandle(n);await e.evict(o,t)},createResponseOn:async(n,o,t)=>{let p=await h(n);await L(p.session);let P=t!==void 0&&m(n)?new T({...p.session,consumerId:t},{sessionTag:t}):p.responses;return U(await P.responses.create(o),p.gone)},onSessionEnd:async(n,o)=>{let t=m(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:p}=await e.sessionForHandle(n),P=p.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(v=>{if(E||!_e.has(v.name))return;E=!0;let O=P.endsAt??null;o({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{Qe as a,ze as b,Ye as c,Ze as d,en as e};
@@ -1,4 +1,4 @@
1
- import{a as Dn,c as Un,d as $e,e as It,f as te,g as Bn,h as jn,i as Hn,j as Jn,k as Gn,l as Wn,m as Vn,n as zn,r as Kn,t as Xn,u as Yn,v as Qn,w as Zn,x as er}from"./chunk-3JWYIKHM.js";import{a as rn}from"./chunk-6M5JK4YC.js";import{s as Oe}from"./chunk-KXKTXZKG.js";import{a as qn,e as ut,f as Nn,i as U,j as Q}from"./chunk-6K7NOPD5.js";import{c as P}from"./chunk-YSFSRI3D.js";P();import{randomUUID as Ts}from"crypto";import{WebSocketServer as Ps}from"ws";var Cs=256,Et=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Cs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Ms="local",lt=n=>n.slice(0,120),Ot=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 U){this.ws.close(Un,lt(e.message));return}if(e instanceof Q){this.ws.close(It,lt(e.message));return}if(e instanceof te){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close($e,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Bn(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 te(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:o}=zn(t.clientContent);this.transcript.push(...s),o&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Xn(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:Kn);return}this.transcript.push(...Yn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new te("setup may only be sent once, as the first client message");let t=Gn(e),r=t.sessionResumption.handle;if(r!==null){let o=this.registry.get(this.scope,r);if(!o)throw new te("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",It);if(o.model!==t.model)throw new te(`sessionResumption.handle was issued for model "${o.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 te("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!==o.proxyHandle)throw new te(`sessionResumption.handle named pooled session "${o.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`,It);this.unsubscribeEnd=await this.clients.onSessionEnd(o.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...o.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let o=this.clients.openVideoOut;if(o){let i=await o.call(this.clients,t.model),a=i.onOutputFrame(l=>this.send(Jn(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[jn]=Hn(i.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 te("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new te("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",$e);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Zn(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 te("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new te("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",$e);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 te(`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 te("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 te("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=Ts();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Wn(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(Vn(e.timeLeftMs)),this.ws.close($e,lt(`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,o=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new te(`upstream error: ${JSON.stringify(l)}`,$e);if(l.type==="response.completed"){s=l.response,o=!0;continue}let d=Qn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!o)throw new te("upstream produced no response.completed event",$e);let{messages:i,assistantItems:a}=er(s);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Fe=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Ls(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 o=n.headers.authorization;typeof o=="string"&&o.startsWith("Bearer ")&&o.length>7&&r.add(o.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Fe(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&&i!==void 0&&i!=="")throw new Fe(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 Fe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function tr(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 Ps({noServer:!0}),s=new Et;n.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Dn&&(a.on("error",()=>{}),(async()=>{let d=Ls(i,l,t),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Fe(401,"invalid local proxy api key");c={clients:e.clients,scope:Ms}}r.handleUpgrade(i,a,u,p=>{new Ot(p,c,s)})})().catch(d=>{let c=502;(d instanceof Fe||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",f=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
1
+ import{a as Dn,c as Un,d as $e,e as It,f as te,g as Bn,h as jn,i as Hn,j as Jn,k as Gn,l as Wn,m as Vn,n as zn,r as Kn,t as Xn,u as Yn,v as Qn,w as Zn,x as er}from"./chunk-3JWYIKHM.js";import{a as rn}from"./chunk-6M5JK4YC.js";import{s as Oe}from"./chunk-B26FENQ3.js";import{a as qn,e as ut,f as Nn,i as U,j as Q}from"./chunk-7AI75MPZ.js";import{c as P}from"./chunk-YSFSRI3D.js";P();import{randomUUID as Ts}from"crypto";import{WebSocketServer as Ps}from"ws";var Cs=256,Et=class{snapshots=new Map;store(e,t,r){for(this.snapshots.set(`${e}\0${t}`,r);this.snapshots.size>Cs;){let s=this.snapshots.keys().next().value;this.snapshots.delete(s)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Ms="local",lt=n=>n.slice(0,120),Ot=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 U){this.ws.close(Un,lt(e.message));return}if(e instanceof Q){this.ws.close(It,lt(e.message));return}if(e instanceof te){this.ws.close(e.closeCode,lt(e.message));return}this.ws.close($e,lt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Bn(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 te(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let r=this.config;if(t.kind==="clientContent"){let{items:s,turnComplete:o}=zn(t.clientContent);this.transcript.push(...s),o&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let s=Xn(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:Kn);return}this.transcript.push(...Yn(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new te("setup may only be sent once, as the first client message");let t=Gn(e),r=t.sessionResumption.handle;if(r!==null){let o=this.registry.get(this.scope,r);if(!o)throw new te("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",It);if(o.model!==t.model)throw new te(`sessionResumption.handle was issued for model "${o.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 te("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!==o.proxyHandle)throw new te(`sessionResumption.handle named pooled session "${o.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`,It);this.unsubscribeEnd=await this.clients.onSessionEnd(o.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript=[...o.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript.push(...t.systemItems);this.config=t;let s={};if(t.videoOut){let o=this.clients.openVideoOut;if(o){let i=await o.call(this.clients,t.model),a=i.onOutputFrame(l=>this.send(Jn(l))),u=i.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},s[jn]=Hn(i.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 te("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new te("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",$e);return this.audio=(async()=>{let r=await t.call(this.clients,e.model);return this.detachAudio=r.onOutputAudio(s=>this.send(Zn(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 te("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new te("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",$e);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 te(`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 te("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 te("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=Ts();this.registry.store(this.scope,r,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(r),this.send(Wn(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(Vn(e.timeLeftMs)),this.ws.close($e,lt(`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,o=!1;for await(let u of r){if(t.interrupted)break;let l=u;if(l.type==="error")throw new te(`upstream error: ${JSON.stringify(l)}`,$e);if(l.type==="response.completed"){s=l.response,o=!0;continue}let d=Qn(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!o)throw new te("upstream produced no response.completed event",$e);let{messages:i,assistantItems:a}=er(s);this.transcript.push(...a);for(let u of i)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},Fe=class extends Error{constructor(t,r){super(r);this.status=t;this.name="UpgradeAuthError"}status};function Ls(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 o=n.headers.authorization;typeof o=="string"&&o.startsWith("Bearer ")&&o.length>7&&r.add(o.slice(7));let i=e.searchParams.get("key")??void 0;if(i!==void 0&&i!==""&&r.add(i),r.size>1)throw new Fe(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&&i!==void 0&&i!=="")throw new Fe(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 Fe(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function tr(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 Ps({noServer:!0}),s=new Et;n.on("upgrade",(i,a,u)=>{let l=new URL(i.url??"/","http://localhost");l.pathname===Dn&&(a.on("error",()=>{}),(async()=>{let d=Ls(i,l,t),c;if(e.authenticate)c=await e.authenticate(d,i);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new Fe(401,"invalid local proxy api key");c={clients:e.clients,scope:Ms}}r.handleUpgrade(i,a,u,p=>{new Ot(p,c,s)})})().catch(d=>{let c=502;(d instanceof Fe||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",f=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
  ${f}\r
@@ -61,4 +61,4 @@ data: ${JSON.stringify({type:"error",error:{type:"api_error",message:A.message}}
61
61
 
62
62
  `):c.write(`data: ${JSON.stringify({error:{message:A.message,type:"upstream_error",code:v}})}
63
63
 
64
- `)),c.end()})}}function Fl(n){let{clients:e,apiKey:t}=n,r=Oi(Qi(n)),s=wr(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),o=mn(r,{resolver:xs(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),i=r.close.bind(r);return r.close=(a=>(s.close(),o(),i(a))),tr(r,{clients:e,apiKey:t}),r}P();var Ie=(n,e)=>Object.assign(new Error(e),{status:n}),ta='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ln=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Mn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof U?Ie(404,t.message):t}};async function Es(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ie(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ta}`);if(s==="transcription")throw Ie(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(!p)throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(p!=="stt")throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let o=await Mn(n,t.stt),i=await Mn(n,e),a=await Mn(n,t.tts),u=await n.openAudioOn(o,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,na({clients:n,chatHandle:i,ttsHandle:a,chatModel:e,companions:t},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(o,p)}catch(f){throw f instanceof Q?Ln("stt",t.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Os(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var tn=class extends Error{};async function*na(n,e,t,r){let{clients:s,chatHandle:o,ttsHandle:i,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,k=null,S=[],y=null,g=new Promise((I,w)=>{t&&t.addEventListener("abort",()=>w(new tn),{once:!0})}),h=()=>f||t?.aborted===!0,_=async I=>{if(h())return;let w;try{w=await s.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(N){throw N instanceof Q?Ln("tts",u.tts,N):N}let C=w[Symbol.asyncIterator]();k=C;try{for(;;){let N=C.next(),q;try{q=await Promise.race([N,g])}catch(B){if(N.catch(()=>{}),B instanceof tn)return;throw B}if(q.done)return;let K=q.value;if(K.type==="error"){let B=K.error&&typeof K.error.message=="string"?K.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${B}`)}if(K.type==="response.completed")return}}finally{k===C&&(k=null)}},v=async()=>{for(;S.length>0&&!h();){let I=S.shift();await _(I)}},A=I=>{if(I===""||h()||(S.push(I),y!==null))return;let w=v();y=w,w.then(()=>{y===w&&(y=null)},C=>{y===w&&(y=null),m??=C})},b=()=>{f=!0,S.length=0;let I=k;if(k=null,I){let w=I.return?.();w&&w.catch(()=>{})}},R=async()=>{for(;S.length>0||y!==null;){let I=y;if(I===null){await _(S.shift());continue}await I}},O=p?new it({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>A(I)):null,x=null;try{let I;try{I=await s.createResponseOn(o,d)}catch(w){throw w instanceof Q?Ln("chat",a,w):w}for await(let w of I){if(h())return;let C=w;if(C.type==="error"){yield w;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield w,O?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){O?.flush(),yield w;continue}if(C.type==="response.completed"){x=w.response;continue}}O?.flush(),O?.dispose(),p&&await R(),x!==null&&(yield{type:"response.completed",response:x})}finally{O?.dispose(),b();try{if(m instanceof Q)throw m}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function sa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function oa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}var ia='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function aa(n,e,t,r){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await n.supportsAudio(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(!s){let d=null;if(n.realtimeCompanionsFor)try{d=await n.realtimeCompanionsFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!==null)return await Es(n,e,d,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let d;try{d=await n.transcriptStreamFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ia}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=await n.sessionHandle(e)}catch(d){throw d instanceof le?ce(503,d.message):d}let a=`conn_${ra()}`,u={audio:await n.openAudioOn(i,t,a)},l={clients:{createResponse:async d=>await n.createResponseOn(i,d,a)},voice:s,audioSession:u};return o&&(l.turns=d=>n.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),n.releaseSessionHandle&&(l.release=()=>n.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function xs(n,e,t){let r=Os(n,t);return{resolve:async(s,o)=>{if(e!==void 0){let i=s.headers.authorization,a=typeof i=="string"?i.trim():"",u=a.startsWith("Bearer ")?a.slice(7).trim():"";if(u===""||u!==e)throw ce(401,"invalid local proxy api key")}return aa(r,sa(s),o,oa(s))}}}export{Et as a,tr as b,pa as c,ke as d,le as e,nr as f,$s as g,ba as h,ka as i,_o as j,wr as k,pt as l,pn as m,mn as n,Os as o,sa as p,oa as q,aa as r,xs as s,os as t,ee as u,zu as v,Rn as w,tl as x,nl as y,rl as z,sl as A,ol as B,As as C,Qi as D,Fl as E};
64
+ `)),c.end()})}}function Fl(n){let{clients:e,apiKey:t}=n,r=Oi(Qi(n)),s=wr(r,{clients:e,apiKey:t,statusOf:n.statusOf,operatorLog:n.operatorLog}),o=mn(r,{resolver:xs(e,t,n.realtimeCompanions),operatorLog:n.operatorLog}),i=r.close.bind(r);return r.close=(a=>(s.close(),o(),i(a))),tr(r,{clients:e,apiKey:t}),r}P();var Ie=(n,e)=>Object.assign(new Error(e),{status:n}),ta='"transcription" (a transcription session), or no intent at all (the realtime voice session)',Ln=(n,e,t)=>new Q(`the composite ${n} leg (model ${JSON.stringify(e??"(default)")}) is gone: ${t instanceof Error?t.message:String(t)}`),Mn=async(n,e)=>{try{return await n.sessionHandle(e)}catch(t){throw t instanceof U?Ie(404,t.message):t}};async function Es(n,e,t,r,s){if(s!==void 0&&s!=="transcription")throw Ie(400,`intent ${JSON.stringify(s)} is not supported on this realtime lane \u2014 accepted values: ${ta}`);if(s==="transcription")throw Ie(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt); the composite lane is the realtime voice session over a chat row`);if(!n.openAudioOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openAudioOn) to open the stt and tts legs' native audio bridges pinned to their pooled sessions \u2014 refusing loudly rather than binding a legless composite");if(!n.openTurnsOn)throw Ie(501,"a composite realtime lane needs a router-backed client (openTurnsOn) to open the stt leg's own turn/transcript lane (the stt named stream) pinned to its pooled session \u2014 refusing loudly rather than binding a transcript-less composite");if(n.supportsTranscription){let p;try{p=await n.supportsTranscription(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(!p)throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} is not a transcription (stt) model \u2014 the composite realtime lane refuses a pairing whose transcription leg cannot transcribe`)}if(n.transcriptStreamFor){let p;try{p=await n.transcriptStreamFor(t.stt)}catch(f){throw f instanceof U?Ie(404,f.message):f}if(p!=="stt")throw Ie(501,`the configured stt companion ${JSON.stringify(t.stt)} overrides engine_args.transcript_stream with ${JSON.stringify(p)} \u2014 this lane consumes the engine's own transcripts from the platform's default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}let o=await Mn(n,t.stt),i=await Mn(n,e),a=await Mn(n,t.tts),u=await n.openAudioOn(o,r),l=await n.openAudioOn(a,r),d=null,c={clients:{createResponse:p=>{let f=new AbortController;return d=f,na({clients:n,chatHandle:i,ttsHandle:a,chatModel:e,companions:t},p,f.signal,()=>{d===f&&(d=null)})}},cancelActiveTurn:()=>{let p=d;d=null,p?.abort(new Error("response.cancel"))},voice:!0,audioSession:{audio:{appendInputAudio:p=>{u.appendInputAudio(p)},onOutputAudio:p=>l.onOutputAudio(p),sessionId:l.sessionId}},turns:async function*(p){try{yield*n.openTurnsOn(o,p)}catch(f){throw f instanceof Q?Ln("stt",t.stt,f):f}},composite:!0};return e!==void 0&&(c.model=e),c}function Os(n,e){return Object.assign(Object.create(n),{realtimeCompanionsFor:e??(async()=>null)})}var tn=class extends Error{};async function*na(n,e,t,r){let{clients:s,chatHandle:o,ttsHandle:i,chatModel:a,companions:u}=n;if(t?.aborted){r?.();return}let{output_modalities:l,...d}=e,c=e.output_modalities,p=!Array.isArray(c)||c.includes("audio"),f=!1,m=null,k=null,S=[],y=null,g=new Promise((I,w)=>{t&&t.addEventListener("abort",()=>w(new tn),{once:!0})}),h=()=>f||t?.aborted===!0,_=async I=>{if(h())return;let w;try{w=await s.createResponseOn(i,{model:u.tts,input:[{role:"user",content:[{type:"input_text",text:I}]}],stream:!1,...u.voice!==void 0?{voice:u.voice}:{}})}catch(N){throw N instanceof Q?Ln("tts",u.tts,N):N}let C=w[Symbol.asyncIterator]();k=C;try{for(;;){let N=C.next(),q;try{q=await Promise.race([N,g])}catch(B){if(N.catch(()=>{}),B instanceof tn)return;throw B}if(q.done)return;let K=q.value;if(K.type==="error"){let B=K.error&&typeof K.error.message=="string"?K.error.message:"the synthesis turn failed";throw new Error(`the composite tts leg (model ${JSON.stringify(u.tts)}) errored: ${B}`)}if(K.type==="response.completed")return}}finally{k===C&&(k=null)}},v=async()=>{for(;S.length>0&&!h();){let I=S.shift();await _(I)}},A=I=>{if(I===""||h()||(S.push(I),y!==null))return;let w=v();y=w,w.then(()=>{y===w&&(y=null)},C=>{y===w&&(y=null),m??=C})},b=()=>{f=!0,S.length=0;let I=k;if(k=null,I){let w=I.return?.();w&&w.catch(()=>{})}},R=async()=>{for(;S.length>0||y!==null;){let I=y;if(I===null){await _(S.shift());continue}await I}},O=p?new it({flushMaxChars:120,flushMaxMs:250,sentenceFlush:!0},I=>A(I)):null,x=null;try{let I;try{I=await s.createResponseOn(o,d)}catch(w){throw w instanceof Q?Ln("chat",a,w):w}for await(let w of I){if(h())return;let C=w;if(C.type==="error"){yield w;return}if(C.type==="response.output_text.delta"&&typeof C.delta=="string"){yield w,O?.push(C.delta);continue}if(C.type==="response.function_call_arguments.delta"){O?.flush(),yield w;continue}if(C.type==="response.completed"){x=w.response;continue}}O?.flush(),O?.dispose(),p&&await R(),x!==null&&(yield{type:"response.completed",response:x})}finally{O?.dispose(),b();try{if(m instanceof Q)throw m}finally{r?.()}}}var ce=(n,e)=>Object.assign(new Error(e),{status:n});function sa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("model")?.trim();return t===""?void 0:t}function oa(n){let t=new URL(n.url??"/","http://localhost").searchParams.get("intent")?.trim();return t===""?void 0:t}var ia='"transcription" (a transcription session), or no intent at all (the realtime voice session)';async function aa(n,e,t,r){if(!n.supportsAudio)throw ce(501,"the realtime lane needs a router-backed client (supportsAudio) to gate audio modality \u2014 hand-built clients without the catalog oracle are refused, never allowed silently");let s;try{s=await n.supportsAudio(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(!s){let d=null;if(n.realtimeCompanionsFor)try{d=await n.realtimeCompanionsFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!==null)return await Es(n,e,d,t,r);throw ce(404,`model ${JSON.stringify(e??"(default)")} is not audio-capable (no audio-capable catalog row: task is neither stt nor tts, and no explicit engine_args.realtime vouch) \u2014 this realtime lane serves only audio-capable models; chat models ride /v1/chat/completions`)}if(!n.openAudioOn)throw ce(501,"an audio-capable model needs a router-backed client (openAudioOn) to open its native session audio bridge pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a voiceless session");let o=!1;if(n.supportsTranscription)try{o=await n.supportsTranscription(e)}catch(d){throw d instanceof U?ce(404,d.message):d}if(o&&!n.openTurnsOn)throw ce(501,"a transcription-capable (stt) model needs a router-backed client (openTurnsOn) to open the engine\u2019s own turn/transcript lane (the stt named stream) pinned to the connection\u2019s pooled session \u2014 refusing loudly rather than binding a transcript-less transcription session");if(o&&n.transcriptStreamFor){let d;try{d=await n.transcriptStreamFor(e)}catch(c){throw c instanceof U?ce(404,c.message):c}if(d!=="stt")throw ce(501,`model ${JSON.stringify(e??"(default)")} overrides engine_args.transcript_stream with ${JSON.stringify(d)} \u2014 this lane consumes the engine\u2019s own transcripts from the platform\u2019s default "${"stt"}" stream and refuses loudly rather than listen on a stream the engine does not write`)}if(r!==void 0&&r!=="transcription")throw ce(400,`intent ${JSON.stringify(r)} is not supported on this realtime lane \u2014 accepted values: ${ia}`);if(r==="transcription"&&!o)throw ce(400,`model ${JSON.stringify(e??"(default)")} cannot serve the transcription intent \u2014 the transcription intent needs an stt model (the catalog task is not stt)`);let i;try{i=n.dedicatedSessionHandle?await n.dedicatedSessionHandle(e):await n.sessionHandle(e)}catch(d){throw d instanceof le?ce(503,d.message):d}let a=`conn_${ra()}`,u={audio:await n.openAudioOn(i,t,a)},l={clients:{createResponse:async d=>await n.createResponseOn(i,d,a)},voice:s,audioSession:u};return o&&(l.turns=d=>n.openTurnsOn(i,d)),r==="transcription"&&(l.intent="transcription"),n.releaseSessionHandle&&(l.release=()=>n.releaseSessionHandle(i)),e!==void 0&&(l.model=e),l}function xs(n,e,t){let r=Os(n,t);return{resolve:async(s,o)=>{if(e!==void 0){let i=s.headers.authorization,a=typeof i=="string"?i.trim():"",u=a.startsWith("Bearer ")?a.slice(7).trim():"";if(u===""||u!==e)throw ce(401,"invalid local proxy api key")}return aa(r,sa(s),o,oa(s))}}}export{Et as a,tr as b,pa as c,ke as d,le as e,nr as f,$s as g,ba as h,ka as i,_o as j,wr as k,pt as l,pn as m,mn as n,Os as o,sa as p,oa as q,aa as r,xs as s,os as t,ee as u,zu as v,Rn as w,tl as x,nl as y,rl as z,sl as A,ol as B,As as C,Qi as D,Fl as E};
@@ -0,0 +1,23 @@
1
+ import{a as vt,c as Pe,d as _t,e as Te}from"./chunk-UQV3ZXCW.js";import{A as gt,B as mt,C as yt,D as wt,b as Qe,d as Ze,e as W,j as et,k as tt,m as rt,n as ot,o as st,p as it,q as at,r as lt,t as ct,u as ne,v as dt,w as ut,x as ft,y as pt,z as ht}from"./chunk-YOFTYCYH.js";import{a as Xe}from"./chunk-3JWYIKHM.js";import{a as bt}from"./chunk-5MH6NSR2.js";import{l as nt,m as te}from"./chunk-B26FENQ3.js";import{a as St,c as Y,e as Ne}from"./chunk-KKCUIOL4.js";import{a as ze}from"./chunk-4NMMWAKD.js";import{b as Ve,d as Le}from"./chunk-GX243AIV.js";import{e as Ye,j as ee,n as qe,o as Ae,p as Ce}from"./chunk-7AI75MPZ.js";import{c as L}from"./chunk-YSFSRI3D.js";L();import{Counter as F,Gauge as re,Histogram as oe,Registry as ln,collectDefaultMetrics as cn}from"@prometheus-io/client";import{createServer as dn}from"http";var to=9464,kt="/metrics",se="(other)",un="(none)",fn=64,pn=128,hn=["/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",ct,ut,Ye],gn=new Set(hn);function mn(t){return gn.has(t)?t:se}function yn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var ie=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?un:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,se):(this.admitted.add(e),e):se}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ae=class{registry=new ln;modelLabel=new ie(fn);orgLabel=new ie(pn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new re({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 F({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 oe({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 oe({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 F({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 F({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 F({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 ft)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new re({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"},pt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},ht()/1e3)}}),this.labelCardinality=new re({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 F({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 re({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 oe({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 oe({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 F({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 F({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&cn({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=mn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,i=this.modelLabel.of(e.model,r),s=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let g=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?se:e.method,status_class:yn(e.status),stream:g,model:i,org:s}),this.duration.observe({lane:n,stream:g,model:i,org:s},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:i,org:s},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:i}),e.delivered||this.undelivered.inc({lane:n,model:i})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Et(t){return dn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==kt){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${kt}
2
+ `);return}let o=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(o)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
3
+ `);return}n.end()})})}L();import{createHash as Lt}from"crypto";import{createServer as wn}from"http";var io=9465,bn="x-urun-key-id",vn="x-urun-key-fingerprint",_n="urun-ratelimit-bucket:",Sn="urun-ratelimit-tier:",Rt="anonymous",kn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function En(t){return Lt("sha256").update(`${_n}${t}`).digest("hex")}function Rn(t){return Lt("sha256").update(`${Sn}${t}`).digest("hex")}function Ln(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 At(){return wn((t,e)=>{let n=Ln(t.headers.authorization);e.setHeader(bn,n===null?Rt:En(n)),e.setHeader(vn,n===null?Rt:Rn(n)),e.writeHead(200),e.end()})}L();import{createClientToken as An,ClientTokenError as Cn}from"@urun-sh/core";import{createPublicKey as Pn,verify as Tn}from"crypto";var Ct="urun-session-gateway",Nn="machine",Un=3e5;function In(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},q=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},D=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function de(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 On=60,xn=6e4,$n=4096;function Dn(t){return t===401||t===403}var le=class{constructor(e){this.opts=e;this.mint=e.mint??An,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.cache.get(e);if(n&&this.now()-n.at<xn)return{apiKey:e,orgId:n.orgId,credential:"api-key",...n.billingAudience!==void 0?{billingAudience:n.billingAudience}:{},...n.creditsAdmissionOk!==void 0?{creditsAdmissionOk:n.creditsAdmissionOk}:{},...n.creditsRefusalReason!==void 0?{creditsRefusalReason:n.creditsRefusalReason}:{}};let r,o;try{let i=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:On});r=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 Cn&&Dn(i.status)?(this.cache.delete(e),new P("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new D("the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the API key against the control plane at ${this.opts.gatewayUrl}: ${i instanceof Error?i.message:String(i)}`)}if(!r)throw new D("the control plane verified the API key but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)");if(this.cache.size>=$n){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}return this.cache.set(e,{orgId:r,at:this.now(),...o}),{apiKey:e,orgId:r,credential:"api-key",...o}}clear(){this.cache.clear()}};function Pt(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var ce=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now}opts;fetchImpl;now;jwks=null;inFlight=null;async jwksKeys(e){if(!e&&this.jwks!==null&&this.now()-this.jwks.at<Un)return this.jwks.keys;if(this.inFlight!==null)return this.inFlight;this.inFlight=(async()=>{let r=`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,o;try{o=await this.fetchImpl(r,{signal:AbortSignal.timeout(3e3)})}catch(s){throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`could not fetch the machine issuer's JWKS at ${r}: ${s instanceof Error?s.message:String(s)}`)}if(!o.ok)throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered HTTP ${o.status}`);let i;try{let s=await o.json();if(!Array.isArray(s.keys))throw new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered no "keys" array`);i=s.keys}catch(s){throw s instanceof D?s:new D("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",`the machine issuer's JWKS at ${r} answered a body that is not JSON`)}return i})().finally(()=>{this.inFlight=null});let n=await this.inFlight;return this.jwks={keys:n,at:this.now()},n}async verify(e){let[n,r,o]=e.split(".");if(n===void 0||r===void 0||o===void 0)throw new P("malformed machine token");let i,s;try{i=Pt(n),s=Pt(r)}catch{throw new P("malformed machine token")}if(i.alg!=="RS256")throw new P(`machine token alg must be RS256 (got ${JSON.stringify(i.alg??null)})`);let a=typeof i.kid=="string"?i.kid:"",g=typeof s.iss=="string"?s.iss:"";if(g===""||!this.opts.issuers.includes(g))throw new P(`machine token issuer is not one this endpoint accepts (${JSON.stringify(g)})`);if(s.aud!==Ct)throw new P(`machine token audience must be ${Ct} (got ${JSON.stringify(s.aud??null)})`);if(s.token_use!==Nn)throw new P(`bearer is a ${JSON.stringify(String(s.token_use??""))} token, not a machine token`);let d=typeof s.org_id=="string"?s.org_id:"";if(d==="")throw new P("machine token carries no org_id \u2014 no tenancy to route by");if((typeof s.exp=="number"?s.exp:0)<=Math.floor(this.now()/1e3))throw new P("machine token is expired \u2014 re-mint and retry");let m=u=>u.kty==="RSA"&&u.n!==void 0&&u.e!==void 0,l=await this.jwksKeys(!1),p=a===""?void 0:l.find(u=>u.kid===a&&m(u));if(p===void 0&&(l=await this.jwksKeys(!0),p=a===""?void 0:l.find(u=>u.kid===a&&m(u))),p===void 0)throw new P(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let R=Buffer.from(`${n}.${r}`,"ascii"),E=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),y=!1;try{let u=Pn({key:p,format:"jwk"});y=Tn("RSA-SHA256",R,u,E)}catch{y=!1}if(!y)throw new P("machine token signature failed verification");return{apiKey:e,orgId:d,credential:"machine"}}};function Ue(t,e,n){return n!==null&&In(t)?n.verify(t):e.resolve(t)}L();var Hn=8080,Ie="serve",go="0.0.0.0";function Mn(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function mo(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Hn: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=nt(te(Mn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),i=o?te(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,s=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!s!=!!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 g=s?{catalogUrl:te(s,"URUN_CATALOG_URL"),anonKey:a}:null,d=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),c=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!d!=!!c)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let m=d?{keyId:c,key:d}:void 0,l={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},p=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],R=p.filter((w,k)=>Object.values(l)[k]==="");if(R.length!==0&&R.length!==p.length)throw new Error(`${p.join(", ")} must be set together (or all left unset) \u2014 missing: ${R.join(", ")}, which would half-configure the lane plane`);let E=R.length===0?l:void 0,y={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},u=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],h=u.filter((w,k)=>Object.values(y)[k]==="");if(h.length!==0&&h.length!==u.length)throw new Error(`${u.join(", ")} must be set together (or all left unset) \u2014 missing: ${h.join(", ")}, which would half-configure the pooler cutover`);let v=h.length===0?y:void 0,_={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},b=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],N=b.filter((w,k)=>Object.values(_)[k]==="");if(N.length!==0&&N.length!==b.length)throw new Error(`${b.join(", ")} must be set together (or all left unset) \u2014 missing: ${N.join(", ")}, which would half-configure the machine-identity rung`);let $=_.issuers.split(",").map(w=>w.trim()).filter(w=>w!=="");if($.length===0&&N.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 f=Number(_.tokenTtlS);if(N.length===0&&(!Number.isFinite(f)||f<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(_.tokenTtlS)}`);let S=N.length===0?{jwksBaseUrl:_.jwksBaseUrl,issuers:$,tokenTtlS:f}:void 0;return{port:n,baseUrl:r,apiUrl:i,catalog:g,ledgerSigning:m,lane:E,pooler:v,machine:S}}L();import{createHash as zn,randomUUID as It}from"crypto";L();import{request as Fn}from"http";var Wn="/pooler/v1/inference",G=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterSeconds=i;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Gn=t=>{if(typeof t.instructions=="string"&&t.instructions!=="")return t.instructions;let e=t.messages?.find(n=>n.role==="system"||n.role==="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content)},Kn=t=>{let e=t.messages?.find(n=>n.role!=="system"&&n.role!=="developer");if(e!==void 0)return typeof e.content=="string"?e.content:JSON.stringify(e.content);if(typeof t.input=="string")return t.input;if(Array.isArray(t.input)){let n=t.input.find(r=>{if(r===null||typeof r!="object"||!("role"in r))return!0;let o=r.role;return o!=="system"&&o!=="developer"});if(n===void 0)return;if(typeof n=="string")return n;if(n!==null&&typeof n=="object"&&"content"in n){let r=n.content;return typeof r=="string"?r:JSON.stringify(r)}return JSON.stringify(n)}},Nt=t=>new Promise((e,n)=>{let r=[];t.on("data",o=>r.push(o)),t.on("end",()=>e(Buffer.concat(r).toString("utf8"))),t.on("error",n)}),Bn=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await Nt(t.body));if(r!==null&&typeof r=="object"&&"error"in r){let o=r.error;o!==null&&typeof o=="object"&&"code"in o&&typeof o.code=="string"&&(e=o.code),o!==null&&typeof o=="object"&&"message"in o&&typeof o.message=="string"&&(n=o.message)}}catch{}return new G(t.status,e,n,t.retryAfterSeconds)};async function jn(t,e,n,r,o){let i=new URL(`${t.baseUrl.replace(/\/+$/,"")}${Wn}`),s=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Gn(e),firstMessage:Kn(e)}});return new Promise((a,g)=>{let d=Fn({hostname:i.hostname,port:i.port===""?void 0:Number(i.port),path:`${i.pathname}${i.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(s))}},c=>{let m=Number(c.headers["retry-after"]??"");a({status:c.statusCode??0,retryAfterSeconds:Number.isFinite(m)?m:void 0,body:c})});d.on("error",c=>g(new G(502,"pooler_unreachable",`the pooler channel failed: ${c.message}`))),d.end(s)})}var Tt=t=>{if(!t.startsWith("data: "))return null;let e=t.slice(6).trim();if(e===""||e==="[DONE]")return null;let n;try{n=JSON.parse(e)}catch{return null}if(n===null||typeof n!="object")return null;let r=n;if(r.t===void 0&&r.error!==null&&typeof r.error=="object"){let o=r.error.code;return{t:"error",code:typeof o=="string"?o:null,body:r}}return r};async function*Jn(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
4
+
5
+ `);if(o===-1)break;let i=e.slice(0,o);e=e.slice(o+2);let s=Tt(i);s!==null&&(yield s)}let n=Tt(e);n!==null&&(yield n)}async function Ut(t,e,n,r){let o=Ve(e,n,r),i=o.model??"";if(i==="")throw new G(400,"missing_model","the pooler submit requires a model");let s=await jn(t,o,n,i,e.stream===!0);if(s.status>=400)throw await Bn(s);let a=e.stream===!0?Le(n,Jn(s)):await Vn(s,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Vn(t,e){let n=await Nt(t.body),r=null;try{let i=JSON.parse(n);i!==null&&typeof i=="object"&&(r=i)}catch{r=null}if(r===null)throw new G(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Le(e,(async function*(){yield o})())}var Yn=512;function Oe(t){return`urun-inference-proxy-${zn("sha256").update(t).digest("hex").slice(0,32)}`}var ue=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),i=this.opts.pooler;if(i===void 0)return o;let s=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,g)=>{if(s!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)try{return await o.createResponse(a,g)}catch(m){if(!(m instanceof W))throw m}let d=`px_${It()}`;return Ut(i,a,d,d)}})}build(e){if(this.opts.build){let i=this.opts.build(e);return i.decision&&this.ensureDecisionReaper(),{router:i.router,clients:this.label(i.clients,e,i.router),decision:i.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ie,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken: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:vt(process.env,process.env.HOSTNAME)??void 0},r=Pe(n),o=n.decisionPool?_t(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Te(r,void 0,void 0,o??void 0,void 0,this.opts.lanes),e,r),decision:o??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=Yn;){let o=this.tenants.entries().next();if(o.done)break;let[i,s]=o.value;this.tenants.delete(i),s.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(i=>{n.push(String(i instanceof Error?i.message:i))})];r.decision&&o.push(r.decision.close().catch(i=>{n.push(String(i instanceof Error?i.message:i))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Ot=512,qn=1024,fe=class extends Error{constructor(){super(`conversation capacity reached (${Ot} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function Xn(t){return{sessionStartOptions:e=>{if(e.startsWith(Ae)||e.startsWith(Ce))return;let n=t.get(e);return n===void 0?void 0:{sessionId:n}},onSessionOpen:(e,n)=>{e.startsWith(Ae)||e.startsWith(Ce)||t.set(e,n)}}}function Qn(t,e,n,r){let o=Pe({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ie,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken: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",...Xn(r)});return{clients:Te(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var pe=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n){let r={id:n,subject:`${Oe(e.apiKey)}:live:${n}`},o=new Map,i=this.opts.build?this.opts.build(e,r):Qn(this.opts,e,r,o);return{id:n,backhaul:i,attachments:0,nativeRefs:o}}attachEntry(e,n){let r=this.byCaller.get(e.apiKey);r===void 0&&(r=new Map,this.byCaller.set(e.apiKey,r));let o=r.get(n);if(o!==void 0)return r.delete(n),r.set(n,o),o.attachments+=1,o;this.evictOverflow();let i=this.build(e,n);return i.attachments=1,r.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>=Ot;){let e=this.byCaller.keys().next();if(e.done)throw new fe;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[i,s]of r)if(!(s.attachments>0)){r.delete(i),this.dropHandleIndexFor(n,i),s.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new fe;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e){let n=null,r=!1,o=()=>(n===null&&(n=this.attachEntry(e,It())),n),i={createResponse:(s,a)=>o().backhaul.clients.createResponse(s,a),catalogIdentity:s=>o().backhaul.clients.catalogIdentity(s),servingAppSlug:s=>{let a=o().backhaul.clients.servingAppSlug;if(a===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return a(s)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:s=>o().backhaul.clients.sessionHandle(s),dedicatedSessionHandle:s=>{let a=o().backhaul.clients.dedicatedSessionHandle;return a===void 0?o().backhaul.clients.sessionHandle(s):a(s)},releaseSessionHandle:s=>o().backhaul.clients.releaseSessionHandle?.(s),createResponseOn:(s,a,g)=>o().backhaul.clients.createResponseOn(s,a,g),onSessionEnd:(s,a)=>o().backhaul.clients.onSessionEnd(s,a)};return i.openAudio=async(s,a)=>{let g=o().backhaul.clients.openAudio;if(g===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return g(s,a)},i.openVideo=async s=>{let a=o().backhaul.clients.openVideo;if(a===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return a(s)},i.openVideoOut=async s=>{let a=o().backhaul.clients.openVideoOut;if(a===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return a(s)},i.supportsAudio=async s=>{let a=o().backhaul.clients.supportsAudio;if(a===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return a(s)},i.supportsSpeech=async s=>{let a=o().backhaul.clients.supportsSpeech;if(a===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return a(s)},i.speechVoices=async s=>{let a=o().backhaul.clients.speechVoices;if(a===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return a(s)},i.speechSessionHandle=async s=>{let a=o().backhaul.clients.speechSessionHandle;if(a===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return a(s)},i.openAudioOn=async(s,a,g)=>{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(s,a,g)},i.openTurnsOn=(s,a)=>{let g=o().backhaul.clients.openTurnsOn;if(g===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 g(s,a)},i.evictSpeechSession=async s=>{let a=o().backhaul.clients.evictSpeechSession;if(a===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return a(s)},i.supportsTranscription=async s=>{let a=o().backhaul.clients.supportsTranscription;if(a===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return a(s)},i.transcriptStreamFor=async s=>{let a=o().backhaul.clients.transcriptStreamFor;if(a===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return a(s)},i.listSpeechToTextModels=async()=>{let s=o().backhaul.clients.listSpeechToTextModels;if(s===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return s()},{clients:i,bindResumeHandle:s=>{let a=n;if(a===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=qn;){let g=this.byHandle.keys().next();if(g.done)break;this.byHandle.delete(g.value)}this.byHandle.set(s,{apiKey:e.apiKey,conversationId:a.id})},clientsForResume:async s=>{let a=this.byHandle.get(s),g=a===void 0?void 0:this.byCaller.get(a.apiKey),d=a===void 0||g===void 0?void 0:g.get(a.conversationId);if(a===void 0||d===void 0||a.apiKey!==e.apiKey)throw new ee("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return n=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(r)return;r=!0;let s=n;n=null,s!==null&&(s.attachments-=1,!(s.attachments>0)&&await s.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};L();var Zn="/inference-ledger",er=1e4,he=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},De=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},U=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},He=class extends P{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Me=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},tr=[["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",xe],["output_minutes",xe],["cost_nano_usd",xe],["price_version",t=>t===null||typeof t=="string"]];function nr(t){for(let[e,n]of tr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function rr(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"}:nr(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function xe(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function $e(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function or(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function xt(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 sr(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&&xt(t.started_at,n.started_at)&&xt(t.completed_at,n.completed_at)&&$e(t.prompt_tokens,n.prompt_tokens)&&$e(t.completion_tokens,n.completion_tokens)&&$e(t.output_units,n.output_units)&&or(t.output_minutes,n.output_minutes)}function ir(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
6
+ `)}async function ar(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e.key),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(ir(t)));return{signature:Array.from(new Uint8Array(o),s=>s.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function lr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new U(`${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 U(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new U(`${e} answered a row with no cost_nano_usd field: ${JSON.stringify(t)}`);let o=n.cost_nano_usd;if(o!=null&&!(typeof o=="number"&&Number.isInteger(o)&&o>=0))throw new U(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let i=d=>{if(!(d in n))throw new U(`${e} answered a row with no ${d} field: ${JSON.stringify(t)}`);let c=n[d];if(c===null)return null;if(typeof c!="string")throw new U(`${e} answered a non-string ${d}: ${JSON.stringify(c)}`);if(!/[^\s]/.test(c))throw new U(`${e} answered a BLANK ${d} (${JSON.stringify(c)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return c},s=i("price_version"),a=i("unpriced_reason"),g=o!=null;if(g&&(s===null||a!==null))throw new U(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}`);if(!g&&(s!==null||a===null))throw new U(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(s)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:s,unpriced_reason:a}}var ge=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Zn}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await ar(n,this.opts.signing)}):JSON.stringify(n)}catch(d){throw new U(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${d instanceof Error?d.message:String(d)}`)}let i;try{i=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(er)})}catch(d){throw new U(`the uRun ledger surface at ${r} could not be reached: ${d instanceof Error?d.message:String(d)}`)}if(i.status===409){let d=await i.text().catch(()=>""),c=rr(d);throw c.status==="found"&&sr(n,c.row)?new De(c.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):c.status==="not_in_this_org"?new he(`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 he(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${c.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${d.slice(0,400)}`)}if(i.status===401||i.status===403)throw await i.text().catch(()=>{}),new He("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(!i.ok){let d=await i.text().catch(m=>`<body unreadable: ${m instanceof Error?m.message:String(m)}>`),c;try{let m=JSON.parse(d);if(m!==null&&typeof m=="object"&&"error"in m){let l=m.error;l!==null&&typeof l=="object"&&"code"in l&&(c=l.code)}}catch{}throw c==="ledger_signature_invalid"?new Me(`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: `+d.slice(0,400)):new U(`the uRun ledger surface at ${r} answered HTTP ${i.status}: ${d.slice(0,400)}`)}let s;try{s=await i.json()}catch(d){throw new U(`the uRun ledger surface at ${r} answered a body that is not JSON: ${d instanceof Error?d.message:String(d)}`)}let a=s?.recorded;if(a===void 0)throw new U(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let g=lr(a,`the uRun ledger surface at ${r}`);if(g.inference_id!==n.inference_id)throw new U(`the uRun ledger surface at ${r} answered for inference_id ${g.inference_id} when asked about ${n.inference_id}`);return g}};L();import{createServer as Fr}from"http";L();import{createWebsocketDocConnector as mr}from"@urun-sh/core/internal";import yr from"ws";L();import*as K from"yjs";import{SessionDocumentImpl as cr}from"@urun-sh/core/internal";var dr=3e4;function ur(t){return(e,n,r)=>{let o=t(e);K.applyUpdate(n,K.encodeStateAsUpdate(o));let i=a=>K.applyUpdate(o,a),s=a=>K.applyUpdate(n,a);return n.on("update",i),o.on("update",s),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",i),o.off("update",s)}}}}function Fe(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?ur(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,i=c=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let m=r.get(c);return m||(m=new cr(c,e,n),r.set(c,m)),m},s=new Map,a=c=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let m=s.get(c);if(!m){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${c}"`);m=t.streamEndpoint(c),s.set(c,m)}return m},g=c=>{let m="llm-resp:";if(!c.startsWith(m))throw new Error(`lane session exposes no stream "${c}" \u2014 only the llm reply lanes (${m}<rid>)`);async function*l(){let p=a(c);try{yield*p.messages()}finally{s.delete(c),await p.close()}}return{messages:()=>l(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(c){return i(c)},stream:g,streamEndpoint:a,async end(){},async whenLive(c){let m=i("llm");if(m.synced===!0)return;let l=c?.timeout??t.whenLiveTimeoutMs??dr;await new Promise((p,R)=>{let E=setTimeout(()=>{y(),R(new Error(`lane ${e} llm doc never synced within ${l}ms`))},l),y=m.onSynced(()=>{clearTimeout(E),c?.signal?.removeEventListener("abort",u),p()}),u=()=>{clearTimeout(E),y(),R(c?.signal?.reason instanceof Error?c.signal.reason:new Error("aborted"))};c?.signal?.addEventListener("abort",u,{once:!0})})},destroy(){o=!0;for(let c of r.values())c.dispose();r.clear();for(let[c,m]of s)s.delete(c),m.close()}}}L();import me,{WebSocketServer as fr}from"ws";import{ENVELOPE_KIND as Ft,STREAM_END as pr,StreamFragmentReassembler as hr}from"@urun-sh/core";var $t="/stream/";function Dt(t){if(!t.startsWith($t))return null;let e=t.slice($t.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 be(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function ye(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>Ft.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var we=class{reassembler=new hr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===pr&&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})}}},Ge=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let i=this.chan(e,n),s=[...i.peers].filter(a=>a!==r);if(s.length===0){let a=i.pending;(a.list.length>=Ht||a.bytes+o.byteLength>Mt)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Ht} frames / ${Mt} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of s)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let i=o.pending;if(i.list.length===0)return;let s=i.list.filter(a=>a.producer!==r);i.list=i.list.filter(a=>a.producer===r),i.bytes=i.list.reduce((a,g)=>a+g.envelope.byteLength,0);for(let{envelope:a}of s)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,i=this.channels.get(o);if(i){for(let s of[...i.peers])s===r&&i.peers.delete(s);i.peers.size===0&&i.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let i of o?.peers??[])i.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")}}},Ht=256,Mt=8*1024*1024,H=new Ge;function Wt(t,e){let n=new we,r={send(o){H.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{ye(o)}catch(i){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(i)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),H.detach(t,e,r)}};return H.attach(t,e,r),r}function gr(t){return{deliver(e){try{t.send(e,{binary:!0})}catch(n){console.warn(`[lane-stream] socket send failed: ${String(n)}`)}},close(e,n){try{t.close(e,n)}catch{}}}}function Gt(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new me(r,be(e)),i=new we;return o.addEventListener("message",s=>{let a=new Uint8Array(s.data);try{ye(a)}catch(g){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(g)}`);return}i.push(i.feed(a))}),o.addEventListener("close",()=>{i.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{i.finish(new Error(`lane stream ${r} socket error`))}),{send(s){if(ye(s),o.readyState!==me.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(s,{binary:!0})},deliver(s){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>i.iterate(),async close(){i.finish();try{o.close(1e3)}catch{}}}}function We(t,e,n){let r=e===401?"Unauthorized":e===404?"Not Found":"Bad Request",o=`${n}\r
7
+ `;t.end(`HTTP/1.1 ${e} ${r}\r
8
+ Connection: close\r
9
+ Content-Type: text/plain; charset=utf-8\r
10
+ Content-Length: ${Buffer.byteLength(o)}\r
11
+ \r
12
+ ${o}`)}function Kt(t,e){let n=e.heartbeatMs??3e4,r=new fr({noServer:!0,handleProtocols:(d,c)=>{let m=Dt(new URL(c.url??"/","http://localhost").pathname);if(!m)return!1;let l=be(m.name);return d.has(l)?l:!1}}),o=new Map,i=new Set,s=!1,a=(d,c,m,l)=>{let p={client:m,upstream:l,laneId:d,name:c};i.add(p);let R=E=>{if(i.delete(p)){console.warn(`[lane-stream] ${d}/${c}: host-affinity pump torn down (${E})`);for(let y of[m,l])try{(y.readyState===me.OPEN||y.readyState===me.CONNECTING)&&y.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let E=(y,u)=>{let h=!0;y.on("pong",()=>{h=!0});let v=setInterval(()=>{if(!h){console.warn(`[lane-stream] ${d}/${c}: pong timeout on ${u} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${u} dial never sends a close)`),clearInterval(v);try{y.terminate()}catch{}R(`${u} pong timeout`);return}h=!1;try{y.ping()}catch{}},n);v.unref?.();let _=()=>clearInterval(v);y.once("close",_),y.once("error",_)};E(m,"client"),E(l,"host")}m.on("message",E=>{try{l.send(E,{binary:!0})}catch(y){R(`upstream send failed: ${String(y)}`)}}),l.on("message",E=>{try{m.send(E,{binary:!0})}catch(y){R(`client send failed: ${String(y)}`)}}),m.on("close",()=>R("client socket closed")),m.on("error",()=>R("client socket error")),l.on("close",()=>R("host socket closed")),l.on("error",()=>R("host socket error"))},g=(d,c,m)=>{let l;try{l=new URL(d.url??"/","http://localhost")}catch{We(c,400,"malformed upgrade URL");return}c.on("error",()=>c.destroy());let p=Dt(l.pathname);p&&(s||c.destroyed||(async()=>{let R=l.searchParams.get("token")??"",E=null;try{E=R===""?null:await e.verifyToken(R,p.laneId,p.name)}catch{E=null}if(E===null){We(c,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let y=await e.hostOf(p.laneId).catch(()=>null);if(y&&y!==e.selfAddress)try{let u=await e.podToPodDial(p.laneId,p.name,y);r.handleUpgrade(d,c,m,h=>{a(p.laneId,p.name,h,u)});return}catch(u){console.warn(`[lane-stream] ${p.laneId}/${p.name}: host dial to ${y} failed (${String(u)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(d,c,m,y=>{let u=gr(y);if(o.set(y,u),H.attach(p.laneId,p.name,u),n>0){let v=!0;y.on("pong",()=>{v=!0});let _=setInterval(()=>{if(!v){console.warn(`[lane-stream] ${p.laneId}/${p.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(_),y.terminate();return}v=!1;try{y.ping()}catch{}},n);_.unref?.();let b=()=>clearInterval(_);y.once("close",b),y.once("error",b)}y.on("message",v=>{let _=new Uint8Array(v);try{ye(_)}catch(b){console.warn(`[lane-stream] ${p.laneId}/${p.name}: dropped malformed envelope: ${String(b)}`);return}H.deliver(p.laneId,p.name,u,_),_[1]===Ft.END&&H.detach(p.laneId,p.name,u)});let h=()=>{o.delete(y),H.detach(p.laneId,p.name,u)};y.on("close",h),y.on("error",h)})})().catch(()=>{c.destroyed||We(c,500,"lane stream upgrade failed")}))};return t.on("upgrade",g),{async close(){s=!0,t.off("upgrade",g),H.clear();for(let d of o.values())d.close(1001,"lane stream host shutting down");o.clear();for(let d of i)for(let c of[d.client,d.upstream])try{c.close(1001,"lane stream host shutting down")}catch{}i.clear()}}}function wr(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new Ze(`the shared lane target (app slug "${t.appSlug}") carries no canonical app id (apps.id) \u2014 the catalog edge function that served its block predates the app_id seam; deploy the catalog publisher and edge function before this proxy (ENG-520). No slug-derived pool fallback exists: a hyphenated slug mints a ghost queue no scheduler drains.`);return`${e}.${t.appId}.${t.fnName??""}`}function Bt(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,i=new Map,s=(l,p,R,E,y)=>{let u=R?b=>Wt(l,b):b=>Gt(l,b,{hostUrl:`ws://${E}/stream/${l}`,token:()=>Y(l,t.tokenSecret,void 0,void 0,y)}),h=R?Fe({laneId:l,roomDoc:b=>t.roomDoc(l,b),streamEndpoint:u}):Fe({laneId:l,streamEndpoint:u,connector:mr({serverUrl:`ws://${E}/doc`,sessionId:l,token:()=>Y(l,t.tokenSecret,void 0,void 0,y),WebSocketPolyfill:yr})}),v=R?a(l):bt(h,`lane:${l}`,{armOnFirstSync:!0}),_={session:h,responses:new ze(h,{sessionTag:null}),gone:v,goneWatch:v,laneId:l,pool:p,inFlight:0,laneSession:h,self:R,host:E??""};return n.set(l,_),v.onGone(()=>g(_)),_},a=l=>{let p=null,R=!1,E=new Set,y=h=>{if(!p){p=h;for(let v of[...E])v(h);E.clear()}},u=t.hostedSignal?.(l,h=>{if(h){R=!0;return}R&&y(new ee(`the lane ${l} is gone: its runtime doc connection closed and no new one arrived \u2014 the occupant released the lane or died. The entry is evicted; the next pick re-reads the registry (or re-demands).`))});return{gone:()=>p,onGone(h){return p?(h(p),()=>{}):(E.add(h),()=>E.delete(h))},dispose(){u?.(),E.clear()}}},g=l=>{d(l)&&(n.delete(l.laneId),r.delete(l.laneId),l.goneWatch?.dispose(),H.forgetLane(l.laneId))},d=l=>{let p=l.laneId;return typeof p=="string"&&n.get(p)===l},c=(l,p)=>{throw t.metrics?.observeLane503Fast(p??""),i.set(l,e()),new W(l)},m=async(l,p)=>{let R=wr(p);o.add(R);let E=e();try{let y=await t.laneWarmWaitMsFor?.(l,p)??t.laneColdWakeDefaultMs??0,u=await t.plane.pick({pool:R,model:l,holdMs:y});t.metrics?.observeLaneReady(l??"",u.length);let v=u.map(b=>({laneId:b.laneId,self:b.host===t.selfAddress,host:b.host})).sort((b,N)=>b.self!==N.self?b.self?-1:1:(r.get(b.laneId)??0)-(r.get(N.laneId)??0))[0];v||c(R,l);let _=n.get(v.laneId);return _?.goneWatch?.gone()&&(g(_),_=void 0),_&&(_.pool!==R||_.self!==v.self||_.host!==v.host)&&(g(_),_=void 0),_||(_=s(v.laneId,R,v.self,v.host,p.sharedOrgId??void 0)),_.inFlight+=1,r.set(v.laneId,(r.get(v.laneId)??0)+1),{app:R,entry:_,identity:{kind:"catalog",model_id:p.modelId??l??"",variant:p.variant??""}}}finally{t.metrics?.observeLanePick(l??"",e()-E)}};return{sessionFor(l,p){return m(l,p)},release(l){d(l)&&(l.inFlight=Math.max(0,l.inFlight-1),r.set(l.laneId,l.inFlight))},owns(l){return d(l)},entryFor(l){return n.get(l)??null},evict(l){d(l)&&(l.gone.dispose(),n.delete(l.laneId),r.set(l.laneId,0),l.laneSession.destroy())},async status(){let l=[...new Set([...o,...[...n.values()].map(E=>E.pool)])].sort(),p=await t.plane.status().catch(()=>[]),R=new Map(br(p));return Promise.all(l.map(async E=>{let y=R.get(E)??{pool:E,lanes:[],lastDemandAt:null};return{pool:E,lanes:y.lanes,lastDemandAt:y.lastDemandAt,local:[...n.values()].filter(u=>u.pool===E).map(u=>({laneId:u.laneId,inFlight:u.inFlight,self:u.self,host:u.host})),lastRefusalAt:i.get(E)??null}}))},async close(){for(let l of n.values())l.gone.dispose(),l.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(l=>({pool:l.pool,laneId:l.laneId,inFlight:l.inFlight}))}}}function br(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}L();import{request as vr}from"http";var _r="/pooler/v1/lanes/pick",Sr="/pooler/v1/lanes/status",kr=1e4;function jt(t,e,n,r,o){return new Promise((i,s)=>{let a=new URL(n,t.baseUrl),g=r===void 0?void 0:Buffer.from(JSON.stringify(r)),d=vr({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...g===void 0?{}:{"content-type":"application/json","content-length":String(g.byteLength)}},timeout:o},c=>{let m=[];c.on("data",l=>m.push(l)),c.on("end",()=>{let l=Buffer.concat(m).toString("utf8"),p=null;try{p=l===""?null:JSON.parse(l)}catch{p=null}i({status:c.statusCode??0,json:p})}),c.on("error",s)});d.on("timeout",()=>{d.destroy(new Error(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),d.on("error",s),d.end(g)})}function Jt(t,e,n){if(t===503)return new W(n);let r=e!==null&&typeof e=="object"&&typeof e.error=="object"?JSON.stringify(e.error):`status ${t}`;return new Error(`the pooler lane surface refused the pick: ${r}`)}function Vt(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=await jt(t,"POST",_r,{pool:e,model:n,hold_ms:r},r+kr);if(o.status!==200)throw Jt(o.status,o.json,e);return(o.json?.lanes??[]).filter(s=>typeof s.lane_id=="string"&&s.lane_id!==""&&typeof s.host=="string"&&s.host!=="").map(s=>({laneId:s.lane_id,host:s.host}))},async status(){let e=await jt(t,"GET",Sr,void 0,5e3);if(e.status!==200)throw Jt(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}L();import{WebSocketServer as xr}from"ws";L();import*as Yt from"yjs";import*as J from"y-protocols/sync";import*as M from"y-protocols/awareness";import*as C from"lib0/encoding";import*as V from"lib0/decoding";import*as qt from"lib0/map";import Rr from"lodash.debounce";L();var zt=()=>{};var Lr=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Ar=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,Cr=0,Pr=1;var Tr=process.env.GC!=="false"&&process.env.GC!=="0",Nr=process.env.YPERSISTENCE,ve=null;if(typeof Nr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var j=new Map,_e=0,Be=1,Ur=(t,e,n)=>{let r=C.createEncoder();C.writeVarUint(r,_e),J.writeUpdate(r,t);let o=C.toUint8Array(r);n.conns.forEach((i,s)=>X(n,s,o))},Ke=class extends Yt.Doc{constructor(e){super({gc:Tr}),this.name=e,this.conns=new Map,this.awareness=new M.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:i},s)=>{let a=r.concat(o,i);if(s!==null){let c=this.conns.get(s);c!==void 0&&(r.forEach(m=>{c.add(m)}),i.forEach(m=>{c.delete(m)}))}let g=C.createEncoder();C.writeVarUint(g,Be),C.writeVarUint8Array(g,M.encodeAwarenessUpdate(this.awareness,a));let d=C.toUint8Array(g);this.conns.forEach((c,m)=>{X(this,m,d)})};this.awareness.on("update",n),this.on("update",Ur),!1}},je=(t,e=!0)=>qt.setIfUndefined(j,t,()=>{let n=new Ke(t);return n.gc=e,ve!==null&&ve.bindState(t,n),j.set(t,n),n}),Ir=(t,e,n)=>{try{let r=C.createEncoder(),o=V.createDecoder(n);switch(V.readVarUint(o)){case _e:C.writeVarUint(r,_e),J.readSyncMessage(o,r,e,t),C.length(r)>1&&X(e,t,C.toUint8Array(r));break;case Be:{M.applyAwarenessUpdate(e.awareness,V.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},B=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),M.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&ve!==null&&(ve.writeState(t.name,t).then(()=>{t.destroy()}),j.delete(t.name))}e.close()},X=(t,e,n)=>{e.readyState!==Cr&&e.readyState!==Pr&&B(t,e);try{e.send(n,r=>{r!=null&&B(t,e)})}catch{B(t,e)}},Or=3e4,Xt=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=je(n,r);o.conns.set(t,new Set),t.on("message",a=>Ir(t,o,new Uint8Array(a)));let i=!0,s=setInterval(()=>{if(!i)o.conns.has(t)&&B(o,t),clearInterval(s);else if(o.conns.has(t)){i=!1;try{t.ping()}catch{B(o,t),clearInterval(s)}}},Or);t.on("close",()=>{B(o,t),clearInterval(s)}),t.on("pong",()=>{i=!0});{let a=C.createEncoder();C.writeVarUint(a,_e),J.writeSyncStep1(a,o),X(o,t,C.toUint8Array(a));let g=o.awareness.getStates();if(g.size>0){let d=C.createEncoder();C.writeVarUint(d,Be),C.writeVarUint8Array(d,M.encodeAwarenessUpdate(o.awareness,Array.from(g.keys()))),X(o,t,C.toUint8Array(d))}}};var Je="/doc/",Zt=30,$r=1e4,Qt="llm";function Dr(t){if(!t.startsWith(Je))return null;let e=t.slice(Je.length),n=e.indexOf("/");return n<=0||n===e.length-1||e.includes("/",n+1)?null:{laneId:e.slice(0,n),docName:e.slice(n+1)}}function Q(t,e,n){let r=e===401?"Unauthorized":e===403?"Forbidden":e===404?"Not Found":"Internal Server Error",o=`${n}\r
13
+ `;t.end(`HTTP/1.1 ${e} ${r}\r
14
+ Connection: close\r
15
+ Content-Type: text/plain; charset=utf-8\r
16
+ Content-Length: ${Buffer.byteLength(o)}\r
17
+ \r
18
+ ${o}`)}function en(t,e){let n=new xr({noServer:!0}),r=new Set,o=new Map,i=new Map,s=u=>o.get(`${u}/${Qt}`)??0,a=u=>i.get(u)??0,g=new Map,d=new Map,c=new Set,m=new Set,l=!1,p=(u,h,v)=>{let _=s(u)>0,b=a(u),N=b>0,$=`${u}/${h}`,f=o.get($)??0;v>0?o.set($,v):o.delete($);let S=b+v-f;S>0?i.set(u,S):i.delete(u);let w=s(u)>0,k=S>0;if(_!==w){w?R(u):E(u);for(let A of g.get(u)??[])A(w)}N&&!k&&queueMicrotask(()=>{let A=`${u}/`;for(let[T,x]of[...j.entries()])!T.startsWith(A)||x.conns.size>0||(j.delete(T),x.destroy())})},R=u=>{if(!e.hostRegistry||d.has(u))return;let h=()=>{e.hostRegistry?.setHost(u,e.selfAddress).catch(()=>{})};h();let v=setInterval(h,$r);v.unref?.(),d.set(u,v)},E=u=>{let h=d.get(u);h&&(clearInterval(h),d.delete(u)),e.hostRegistry&&e.hostRegistry.delHost(u,e.selfAddress).catch(()=>{})},y=(u,h,v)=>{let _;try{_=new URL(u.url??"/","http://localhost")}catch{Q(h,400,"malformed upgrade URL");return}h.on("error",()=>h.destroy()),h.on("close",()=>m.delete(h));let b=Dr(_.pathname);if(!b){if(_.pathname.startsWith(Je)){Q(h,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}m.add(h);return}c.add(h);let N=!1;(async()=>{let $=_.searchParams.get("token")??"",f=null;try{f=$===""?null:await e.verifyToken($,b.laneId,b.docName)}catch{f=null}if(f===null){Q(h,401,"invalid or missing lane doc token");return}let S=f;if(S.tenant!==void 0&&e.laneTenantOf){let w=null;try{w=await e.laneTenantOf(b.laneId)}catch{w=null}if(w==null||w==="")e.onLaneTenantMissing?.();else if(S.tenant!==w){Q(h,403,"lane doc token org does not match the lane record");return}}l||h.destroyed||(N=!0,n.handleUpgrade(u,h,v,w=>{c.delete(h),r.add(w),w.on("close",()=>r.delete(w));let k=S.scope===St||S.scope===void 0&&typeof S.app=="string"&&typeof S.fn=="string"&&S.aud==="sfu";if(k){let T=`${b.laneId}/${b.docName}`,x=(o.get(T)??0)+1;p(b.laneId,b.docName,x),x>1&&b.docName===Qt&&e.hostRegistry?.setHost(b.laneId,e.selfAddress).catch(()=>{})}w.on("close",()=>{if(!k)return;let T=`${b.laneId}/${b.docName}`;p(b.laneId,b.docName,Math.max(0,(o.get(T)??1)-1))}),Xt(w,u,{docName:`${b.laneId}/${b.docName}`,gc:!0})}))})().catch(()=>{!N&&!h.destroyed&&Q(h,500,"lane doc upgrade failed")}).finally(()=>c.delete(h))};return t.on("upgrade",y),{async close(){l=!0,t.off("upgrade",y);for(let h of[...d.keys()])E(h);await new Promise(h=>{if(r.size===0&&c.size===0){h();return}let v=r.size+c.size,_=()=>{v-=1,v<=0&&h()};for(let b of r)b.once("close",_);for(let b of c)b.once("close",_);for(let b of r)b.close(1001,"lane doc host shutting down");for(let b of c)b.destroy()}),o.clear(),i.clear(),g.clear()},roomDoc(u,h){return je(`${u}/${h}`,!0)},isHosted(u){return s(u)>0},onHostedChange(u,h){let v=g.get(u);return v||(v=new Set,g.set(u,v)),v.add(h),h(s(u)>0),()=>{v.delete(h)}}}}import Wr from"ws";L();var Hr="urun:catalog:v1";function tn(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,i=null,s=async()=>{let g=await t.redis.hgetall(Hr),d=[];for(let c of Object.values(g))try{d.push(JSON.parse(c))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
19
+ `)}return r=d,o=n(),d},a=()=>r===null||n()-o>=e;return{rows(){return a()?(i||(i=s().finally(()=>{i=null})),i):Promise.resolve(r)},close(){r=null,i=null}}}import Gr from"ioredis";L();var Se="/inference-usage",nn=25e3;var Mr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function rn(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Mr.has(t.name)?t.name:"Error",n=t.cause?.code;return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(n)?`${e} (${n})`:e}var ke=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Se}`,o;try{o=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({inference_ids:n}),signal:AbortSignal.timeout(nn)})}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) could not be reached within ${nn}ms: ${rn(s)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new P("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let s=await o.text().catch(()=>null),a=s===null?"body unreadable":`${s.length}-character body`;throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} (${a})`)}let i;try{i=await o.json()}catch(s){throw new ne(`the uRun usage surface (POST ${Se}) answered HTTP ${o.status} with a body that is not JSON: ${rn(s)}`)}return dt(i,this.opts.onRejectedRow)}};var Kr=5e3,Br=1e3,jr=1500,Jr=3e3,Vr="/api/client-tokens";function Ee(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function on(t,e,n,r){Ee(t,e,{error:{message:n,type:r}})}async function zr(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${Vr}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Jr)});return r.status===404?{ready:!1,detail:`${n} answered 404 \u2014 this is not a uRun control plane`}:r.status>=500?{ready:!1,detail:`${n} answered HTTP ${r.status}`}:{ready:!0,detail:`${n} answered HTTP ${r.status}`}}catch(r){return{ready:!1,detail:`${n} unreachable: ${r instanceof Error?r.message:String(r)}`}}}function Bs(t){let e=t.resolver??new le({gatewayUrl:t.baseUrl}),n=t.machine?new ce({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new ae(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,i=null,s=(()=>{if(!t.lane)return null;if(!t.pooler)throw new Error("the lane plane requires the pooler cutover (URUN_POOLER_URL + URUN_POOLER_TOKEN) \u2014 the lane registry reads and the dispatch-queue demand live in the pooler; a proxy replica no longer picks lanes or enqueues demand itself");let f=new Gr(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),S=tn({redis:f});return{registry:Bt({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Vt({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(k,A)=>o?.onHostedChange(k,A)??(()=>()=>{}),roomDoc:(k,A)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(k,A)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(k,A)=>S.rows().then(T=>{let x=qe(T,A);return x?.warm_wait_s!==void 0?x.warm_wait_s*1e3:void 0})}),catalog:S,redis:f}})(),a=t.registry??new ue({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry,pooler:t.pooler}),g=t.probeControlPlane??(()=>zr(t.baseUrl)),d=async()=>{let f=null;for(let k of a.decisionPools()){f=k;break}if(!f)return null;let S=f.stats();if(S.some(k=>k.draining))return{ok:!1,detail:"decision pool draining"};if(S.every(k=>k.attached===0&&k.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let w=await f.pingReady(jr);return{ok:w,detail:w?"a decision slot answered its session ping":"no decision slot answered its session ping"}},c=t.usageClient??new ke({apiUrl:t.apiUrl}),m=t.ledgerClient??new ge({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),l=process.env.URUN_SHARED_ORG_ID?.trim(),p=process.env.URUN_SHARED_ORG_API_KEY?.trim();l&&p&&(async()=>{try{await a.decisionWarmerFor({orgId:l,apiKey:p})?.warmFor(yt)}catch(f){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(f instanceof Error?f.message:f)}
20
+ `)}})();let R=async f=>Ue(de(f.headers.authorization),e,n),E=async f=>{let S=await R(f);if(S.billingAudience==="platform"&&S.creditsAdmissionOk===!1){let w=S.creditsRefusalReason;throw new q(w==="spend_cap_reached"||w==="insufficient_credits"?w:void 0)}return S},y=f=>f instanceof P?{status:f.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:f instanceof q?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...f.code!==void 0?{code:f.code}:{}}:f instanceof D?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:f.detail}:null,u=wt({clients:async f=>a.clientsFor(await E(f)),usage:{authorize:f=>de(f.headers.authorization),lookup:(f,S)=>c.lookup(f,S)},statusOf:y,...t.requestLog?{requestLog:t.requestLog}:{},observe:f=>r.observe(f),ledger:{write:(f,S)=>m.write(de(f.headers.authorization),S),observe:f=>r.observeLedger(f),...t.ledgerLog?{report:t.ledgerLog}:{}}}),h=null,v=null,_=Fr((f,S)=>{let w=new URL(f.url??"/","http://localhost");(async()=>{if(f.method==="GET"&&w.pathname==="/healthz"){Ee(S,200,{ok:!0});return}if(f.method==="GET"&&w.pathname==="/readyz"){let T=Date.now();if((!h||T-h.at>=Kr)&&(h={at:T,...await g()}),!v||T-v.at>=Br){let z=await d();v=z===null?{at:T,ok:!0,detail:null}:{at:T,ok:z.ok,detail:z.detail}}let x=(h?.ready??!1)&&v.ok,Z=v.detail===null?h?.detail??"control plane not yet probed":`${h?.detail??"control plane not yet probed"}; ${v.detail}`;Ee(S,x?200:503,{ok:x,control_plane:Z});return}if(f.method==="GET"&&w.pathname==="/lanez"){Ee(S,200,{pools:s?await s.registry.status():null});return}let k=w.pathname==="/v1"||w.pathname.startsWith("/v1/"),A=w.pathname.startsWith("/partners/");if(!k&&!A){on(S,404,`no route for ${f.method} ${w.pathname} \u2014 this endpoint serves the OpenAI-compatible /v1 surface, the partner adapter surface (/partners/...), the WS upgrade paths (/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent and /v1/realtime), plus /healthz, /readyz and /lanez`,"invalid_request_error");return}u(f,S)})().catch(k=>{if(!S.headersSent){on(S,500,String(k instanceof Error?k.message:k),"proxy_error");return}S.end()})}),b=t.conversations??new pe({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:s?null:t.catalog,catalogRows:s?()=>s.catalog.rows():void 0,lanes:s?.registry}),N=[Qe(_,{authenticate:async f=>{let S=await Ue(f,e,n),w=b.connectionFor(S);return{clients:w.clients,scope:Oe(S.apiKey),onBindResumeHandle:w.bindResumeHandle,clientsForResume:w.clientsForResume,release:w.release}}}),tt(_,{clients:async f=>a.clientsFor(await E(f)),statusOf:y}).close,ot(_,{resolver:{resolve:async(f,S)=>{let w=await E(f),k=b.connectionFor(w),A;try{A=await lt(st(k.clients,t.realtimeCompanions),it(f),S,at(f))}catch(x){throw k.release().catch(()=>{}),x}let T=A.release;return{...A,release:async()=>{await T?.(),await k.release()}}}}})];if(t.lane&&s){let f=t.lane,S=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=en(_,{verifyToken:(k,A)=>Ne(k,A,f.tokenSecret,void 0,S),selfAddress:f.selfAddress,laneTenantOf:k=>s.redis.get(`lane_tenant:${k}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:S,hostRegistry:{setHost:(k,A)=>s.redis.eval("local cur = redis.call('get', KEYS[1]) if cur == false or cur == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) end return 0",1,`lane_hosts:${k}`,A,String(Zt)),delHost:k=>s.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${k}`,f.selfAddress)}}),i=Kt(_,{verifyToken:(k,A)=>Ne(k,A,f.tokenSecret,void 0,S),selfAddress:f.selfAddress,hostOf:async k=>{let A=await s.redis.get(`lane_hosts:${k}`);return A&&A.trim()!==""?A.trim():null},podToPodDial:(k,A,T)=>new Promise((x,Z)=>{(async()=>{let z=await s.redis.get(`lane_tenant:${k}`),sn=Y(k,f.tokenSecret,void 0,void 0,z||void 0),an=`ws://${T}/stream/${encodeURIComponent(k)}/${encodeURIComponent(A)}?token=${encodeURIComponent(sn)}`,Re=new Wr(an,be(A));Re.once("open",()=>x(Re)),Re.once("error",Z)})().catch(Z)})});let w=s;N.push(async()=>{await o.close(),await i.close(),await w.registry.close(),w.redis.quit().catch(()=>{})})}_.on("upgrade",(f,S)=>{let w=new URL(f.url??"/","http://localhost");w.pathname===Xe||w.pathname===et||w.pathname===rt||o!==null&&w.pathname.startsWith("/doc/")||i!==null&&w.pathname.startsWith("/stream/")||S.destroyed||(S.write(`HTTP/1.1 404 Not Found\r
21
+ Connection: close\r
22
+ \r
23
+ no WS route for ${w.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),S.destroy())});let $=async()=>{for(let f of N)await f();await b.detachAll()};return{server:_,metricsServer:Et(r),metrics:r,edgeIdentityServer:At(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:$}}async function js(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await gt()||mt(),await e()}export{to as a,kt as b,se as c,un as d,fn as e,pn as f,mn as g,yn as h,ie as i,ae as j,Et as k,io as l,bn as m,vn as n,_n as o,Sn as p,Rt as q,En as r,Rn as s,Ln as t,At as u,P as v,D as w,de as x,xn as y,$n as z,le as A,Hn as B,Ie as C,go as D,mo as E,Yn as F,Oe as G,ue as H,Ot as I,qn as J,fe as K,pe as L,Zn as M,er as N,he as O,U as P,lr as Q,ge as R,Kr as S,Jr as T,Bs as U,js as V};
@@ -306,6 +306,14 @@ declare class ModelRouter<S> {
306
306
  identity: TurnCatalogIdentity;
307
307
  }>;
308
308
 
309
+ dedicatedSessionFor(model: string | undefined): Promise<{
310
+ app: string;
311
+ entry: S;
312
+ identity: TurnCatalogIdentity;
313
+ }>;
314
+
315
+ evictHandle(handle: string): Promise<void>;
316
+
309
317
  private acquire;
310
318
  private keyOf;
311
319
 
@@ -602,6 +610,8 @@ interface ProxyClients {
602
610
 
603
611
  releaseSessionHandle?(handle: string): void;
604
612
 
613
+ dedicatedSessionHandle?(model: string | undefined): Promise<string>;
614
+
605
615
  speechSessionHandle?(model: string | undefined): Promise<string>;
606
616
 
607
617
  evictSpeechSession?(handle: string): Promise<void>;