@urun-sh/openai 0.6.38 → 0.6.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-B26FENQ3.js → chunk-BWYY4IPR.js} +1 -1
- package/dist/chunk-G5VRFFBE.js +64 -0
- package/dist/chunk-G7CSAISC.js +1 -0
- package/dist/{chunk-7AI75MPZ.js → chunk-HPUX2H65.js} +6 -6
- package/dist/{chunk-5MH6NSR2.js → chunk-L4QBHSVY.js} +1 -1
- package/dist/chunk-L6CT7ZVO.js +23 -0
- package/dist/chunk-PT5N7AY7.js +2 -0
- package/dist/{chunk-3JWYIKHM.js → chunk-QTHFMDZY.js} +1 -1
- package/dist/chunk-Z3QCHKJB.js +1 -0
- package/dist/{composite-ClDE3ViI.d.ts → composite-B--rGI5m.d.ts} +8 -2
- package/dist/{composite-F94H40CD.d.cts → composite-B-F2J0NK.d.cts} +40 -2
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +2 -2
- package/dist/gemini-live.d.ts +2 -2
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +48 -48
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +46 -46
- package/dist/hosted/index.d.cts +3 -3
- package/dist/hosted/index.d.ts +3 -3
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +55 -55
- package/dist/pooler/bin.cjs +7 -7
- package/dist/pooler/bin.js +25 -25
- package/dist/proxy/cli.cjs +51 -51
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +26 -26
- package/dist/proxy/index.d.cts +35 -5
- package/dist/proxy/index.d.ts +11 -5
- package/dist/proxy/index.js +1 -1
- package/dist/{translator-Ddd65sXR.d.ts → translator-BqpmZ-vh.d.ts} +1 -1
- package/dist/{translator-CO8W_hmJ.d.cts → translator-Dox25ky9.d.cts} +1 -1
- package/dist/{video-out-BsuLqlID.d.cts → video-out-DnCKUUO2.d.cts} +13 -0
- package/dist/{video-out-Cawtm7SF.d.ts → video-out-REmiQMBJ.d.ts} +7 -0
- package/package.json +3 -3
- package/dist/chunk-6M5JK4YC.js +0 -1
- package/dist/chunk-UQV3ZXCW.js +0 -2
- package/dist/chunk-YOFTYCYH.js +0 -64
- package/dist/chunk-ZA2LMA3I.js +0 -23
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as p}from"./chunk-YSFSRI3D.js";p();import{Queue as x}from"bullmq";import{randomUUID as R}from"crypto";var P=3e4,v=60,S=1e3,E=12e4;function y(r){let c;try{c=JSON.parse(r)}catch{return null}if(typeof c!="object"||c===null||!("proxy_url"in c))return null;let u=c;return typeof u.proxy_url!="string"||u.proxy_url===""?null:{proxy_url:u.proxy_url,occupant_id:typeof u.occupant_id=="string"?u.occupant_id:"",capacity:typeof u.capacity=="number"?u.capacity:0,heartbeat_ms:typeof u.heartbeat_ms=="number"?u.heartbeat_ms:0}}function q(r){let c=r.now??Date.now,u=new Map,m=new Map,g=new Map,_=new Map,f=new Set,L=e=>{let n=u.get(e);return n||(n=r.queueFor?.(e)??h(e),u.set(e,n)),n},h=e=>{let n=r.redis,o=new x(e,{prefix:"bull:dispatch",connection:n});return{add:(i,d,a)=>o.add(i,d,a),reassertWaiting:async i=>{let a=(await o.getJobs(["waiting"])).filter(t=>t.data?.session_kind==="lane").sort((t,s)=>t.timestamp-s.timestamp);if(a.length===0)return{found:0};for(let t of a)try{await t.updateData({...t.data,demand_reaffirmed_at_ms:i,...r.mintRuntimeToken?{runtime_token:r.mintRuntimeToken(String(t.data.session_id))}:{}})}catch{}for(let t of a.slice(1))try{await t.remove()}catch{}return{found:a.length}},close:()=>o.close()}},b=async e=>{let n=await r.redis.hgetall(`lanes:${e}`),o=[];for(let[a,t]of Object.entries(n)){let s=y(t);s&&s.proxy_url===r.docHostUrl&&o.push(a)}if(o.length===0)return[];let i=await r.redis.mget(...o.map(a=>`lane_hosts:${a}`)),d=[];return o.forEach((a,t)=>{let s=i[t];s&&d.push({laneId:a,host:s})}),d},k=async(e,n)=>{let o=m.get(e)??0,i=c();if(i-o<P)return;m.set(e,i);let d=L(e);if((await d.reassertWaiting(c()).catch(s=>{throw m.delete(e),s})).found>0){_.set(n??"",(_.get(n??"")??0)+1),r.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:n});return}let t=`lane-${R().replaceAll("-","")}`;await d.add("session",{session_id:t,logical_id:t,incarnation:i,session_kind:"lane",lane_id:t,session_server_url:r.docHostUrl,proxy_url:r.docHostUrl,session_idle_timeout_seconds:v,thread_key:"lane",demand_reaffirmed_at_ms:c(),...r.mintRuntimeToken?{runtime_token:r.mintRuntimeToken(t)}:{}},{jobId:`${t}#${i}`,attempts:3}),g.set(n??"",(g.get(n??"")??0)+1),r.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:n})};return{async pick({pool:e,model:n,holdMs:o=0}){f.add(e);let i=async()=>{try{await k(e,n)}catch(s){m.delete(e),r.onEvent?.({kind:"lane_demand_failed",pool:e,model:n,reason:s instanceof Error?s.message:String(s)})}},d=async()=>{try{return await b(e)}catch{return[]}},a=await d();if(a.length>0)return a;await i();let t=c()+o;for(;c()<t;){if(await new Promise(s=>setTimeout(s,S)),a=await d(),a.length>0)return a;await i()}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async n=>{let o=[];try{let i=await r.redis.hgetall(`lanes:${n}`),d=Object.keys(i),a=d.length===0?[]:await r.redis.mget(...d.map(s=>`lane_hosts:${s}`)),t=c();o=d.map((s,D)=>{let w=i[s],l=w===void 0?null:y(w);return{laneId:s,occupantId:l?.occupant_id??"",capacity:l?.capacity??0,heartbeatAgeMs:l===null?null:t-l.heartbeat_ms,advertisedHere:l?.proxy_url===r.docHostUrl,hosted:!!a[D]}})}catch{}return{pool:n,lanes:o,lastDemandAt:m.get(n)??null}}))},demandCounters(){return[...new Set([...g.keys(),..._.keys()])].sort().map(n=>({model:n,enqueued:g.get(n)??0,reaffirmed:_.get(n)??0}))},async close(){await Promise.all([...u.values()].map(e=>e.close().catch(()=>{}))),u.clear()}}}export{E as a,q as b};
|
|
@@ -1,6 +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
|
|
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(
|
|
4
|
-
`),
|
|
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,
|
|
6
|
-
`);let
|
|
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,s,d]=e.map(Number);if(!Number.isFinite(Date.parse(n)))return!1;let a=new Date(Date.UTC(t,o-1,r,i,s,d));return a.getUTCFullYear()===t&&a.getUTCMonth()===o-1&&a.getUTCDate()===r&&a.getUTCHours()===i&&a.getUTCMinutes()===s&&a.getUTCSeconds()===d}function be(n){if(n===null||typeof n!="object")return null;let e=n.shared;if(e==null)return null;if(typeof e!="object")throw new p(`catalog "shared" block is ${typeof e}, expected an object`);let{shared_org_id:t,endpoints:o,regions:r,compliance:i}=e;if(typeof t!="string"||t==="")throw new p(`catalog "shared" block has no shared_org_id: ${JSON.stringify(e)}`);if(!Array.isArray(o))throw new p(`catalog "shared" block endpoints is not an array: ${JSON.stringify(e)}`);let s=o.map((d,a)=>{if(d===null||typeof d!="object")throw new p(`catalog shared endpoints[${a}] is not an object: ${JSON.stringify(d)}`);let l=d;for(let c of["model_id","variant","app_slug","function"])if(typeof l[c]!="string"||l[c].length===0)throw new p(`catalog shared endpoints[${a}] (${JSON.stringify(l)}) has no valid "${c}"`);if(l.app_id!==void 0&&l.app_id!==null&&(typeof l.app_id!="string"||l.app_id===""))throw new p(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "app_id": ${JSON.stringify(l.app_id)}`);let u=(c,g)=>{if(l[c]!==void 0&&l[c]!==null&&!g)throw new p(`catalog shared endpoints[${a}] (${l.model_id}:${l.variant}) carries a malformed "${c}": ${JSON.stringify(l[c])}`)};u("ready",typeof l.ready=="boolean"),u("ready_runtimes",typeof l.ready_runtimes=="number"&&Number.isInteger(l.ready_runtimes)&&l.ready_runtimes>=0),u("ready_since",Re(l.ready_since));for(let c of["model_id","variant"]){let g=l[c];if(g.includes(":"))throw new p(`catalog shared endpoints[${a}] has "${c}" containing ":" (${JSON.stringify(g)}) \u2014 the external identity <model_id>:<variant> would be unparseable (resolveSharedModel splits at the LAST colon); platform catalog defect`)}return u("output_free",typeof l.output_free=="boolean"),l});if(r!=null&&(!Array.isArray(r)||!r.every(d=>typeof d=="string"&&d.length>0)))throw new p(`catalog "shared" block regions is malformed: ${JSON.stringify(r)}`);if(i!=null){let d=i;if(typeof i!="object"||typeof d.zdr!="boolean"||typeof d.hipaa!="boolean")throw new p(`catalog "shared" block compliance is malformed (operator-declared zdr + hipaa booleans required): ${JSON.stringify(i)}`);for(let a of Object.keys(d))if(a!=="zdr"&&a!=="hipaa")throw new p(`catalog "shared" block compliance carries "${a}" beyond the declared zdr/hipaa contract: ${JSON.stringify(i)}`)}return s.length===0?null:{shared_org_id:t,endpoints:s,...r!=null?{regions:r}:{},...i!=null?{compliance:i}:{}}}function S(n){return[...n.endpoints].sort((e,t)=>e.model_id.localeCompare(t.model_id)||e.variant.localeCompare(t.variant))}function Qe(n){let e=n.filter(r=>typeof r.shared_org_id=="string"&&r.shared_org_id!=="");if(e.length===0)return null;let t=e[0].shared_org_id,o=e.map((r,i)=>{let s=d=>new p(`catalog rows[${i}] (${r.model_id}:${r.variant}) shared row is malformed: ${d}`);if(r.shared_org_id!==t)throw s(`shared_org_id ${JSON.stringify(r.shared_org_id)} disagrees with ${JSON.stringify(t)}`);for(let d of["model_id","variant"]){let a=r[d];if(typeof a!="string"||a===""||a.includes(":"))throw s(`"${d}" ${JSON.stringify(a)} is empty or contains ":"`)}if(typeof r.app_slug!="string"||r.app_slug==="")throw s("no app_slug");if(typeof r.function!="string"||r.function==="")throw s("no function");if(r.app_id!==void 0&&r.app_id!==null&&(typeof r.app_id!="string"||r.app_id===""))throw s(`malformed app_id ${JSON.stringify(r.app_id)}`);return{model_id:r.model_id,variant:r.variant,app_slug:r.app_slug,app_id:r.app_id??null,function:r.function,...r.gpu_spec?{gpu_spec:r.gpu_spec}:{},...r.warm!==void 0&&r.warm!==null?{warm:r.warm}:{},...r.compat_default===!0?{compat_default:!0}:{},...r.output_free===!0?{output_free:!0}:{},...r.ready!==void 0&&r.ready!==null?{ready:r.ready}:{},...r.ready_runtimes!==void 0&&r.ready_runtimes!==null?{ready_runtimes:r.ready_runtimes}:{},...r.ready_since?{ready_since:r.ready_since}:{}}});return{shared_org_id:t,endpoints:o}}function D(n,e,t){let o=(e??"").trim();if(o==="")return null;let r=o,i=t,s=o.lastIndexOf(":");s>0&&(r=o.slice(0,s),i=o.slice(s+1));let d=n.endpoints.filter(l=>l.model_id===r);if(d.length===0)return null;if(i!==void 0){let l=d.find(u=>u.variant===i);return l?{shared_org_id:n.shared_org_id,endpoint:l}:null}if(d.length===1)return{shared_org_id:n.shared_org_id,endpoint:d[0]};let a=d.filter(l=>l.compat_default===!0);if(a.length!==1)throw new p(`shared model "${r}" has ${a.length} compat_default rows (exactly one required) among variants ${d.map(l=>l.variant).join(", ")}`);return{shared_org_id:n.shared_org_id,endpoint:a[0]}}async function Xe(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/catalog`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new p(`catalog read failed: GET ${t} \u2192 ${o.status}`);return be(await o.json())}w();function h(n){return n.toLowerCase().replace(/[^\p{L}\p{N}-]/gu,"-").replace(/^-+|-+$/g,"")}w();var _=class extends Error{name="ModelPriceError"},j="per_million_input_tokens",U="per_million_output_tokens",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 s=ke(i.unit,r);if(s===null)continue;let d=i.model_id;if(typeof d!="string"||d==="")throw new _(`${r} has no model_id (${JSON.stringify(i)})`);let a=i.variant;if(!(a===null||typeof a=="string"&&a!==""))throw new _(`${r} has a non-string variant (${JSON.stringify(a)})`);e.push({model_id:d,variant:a,side:s,usd:$e(i.price_usd,r),effective_at: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 a of n){if(a.effective_at>e||a.expires_at!==null&&a.expires_at<=e)continue;let l=o.get(a.model_id);l||(l=new Map,o.set(a.model_id,l),r.set(a.model_id,new Map));let u=a.variant??"",c=l.get(u);c||(c={input:[],output:[]},l.set(u,c),r.get(a.model_id).set(u,a.variant)),c[a.side].push({effective_at:a.effective_at,usd:a.usd})}let i=[],s=[];for(let[a,l]of o){let u=l.get(""),c=(g,f,v)=>{let m=g&&g.length>0?g:u?.[f];if(!m||m.length===0)return null;let y=Pe(m,f);return"reason"in y?y:y.rate.usd===0?f==="output"&&v!==null&&t?.has(J(a,v))?y.rate:{reason:`the ${f} rate in force is zero, which publishes as "free" and would top :cheapest routing \u2014 this model is served UNPRICED; delete the row if the model is not token-priced, or set a real rate`}:y.rate};for(let[g,f]of r.get(a)){let v=l.get(g),m=c(v?.input,"input",f),y=c(v?.output,"output",f);if(m!==null&&"reason"in m){s.push({model_id:a,variant:f,reason:m.reason});continue}if(y!==null&&"reason"in y){s.push({model_id:a,variant:f,reason:y.reason});continue}m===null||y===null||i.push({model_id:a,variant:f,pricing:{input:m.usd,output:y.usd}})}}let d=(a,l)=>a.model_id.localeCompare(l.model_id)||(a.variant===null?1:0)-(l.variant===null?1:0)||(a.variant??"").localeCompare(l.variant??"");return{prices:i.sort(d),refusals:s.sort(d)}}function O(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===e);if(o)return o.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===null);return r?r.pricing:null}var E={prices:[],refusals:[]};async function rt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${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 Oe(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 Ee(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 Ae(n){if(!n)return null;let e=n.split("@")[0],t=e.indexOf("/"),o=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<o.length;r+=1){let i=o[r];if(Object.hasOwn(ne,i))return ne[i];let s=o[r+1];if(i==="llama"&&s!==void 0&&Object.hasOwn(re,s))return re[s];if(i==="phi"&&s!==void 0&&/^\d/.test(s))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 A(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return A(o);let r=B(n,e);return r.length>0?A(r):null}function A(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e: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]),s=Number(r[2]),d=Number(r[3]),a=Date.UTC(i,s-1,d),l=new Date(a);if(l.getUTCFullYear()!==i||l.getUTCMonth()!==s-1||l.getUTCDate()!==d)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 not a real calendar date`);return a/1e3}function b(n){let e={id:n.id,object:n.object,created:n.created,owned_by:n.owned_by,...n.context_length!==void 0?{context_length:n.context_length}:{},...n.pricing!==void 0?{pricing:n.pricing}:{},...n.voices!==void 0?{voices:n.voices}:{},...n.capabilities!==void 0?{capabilities:n.capabilities}:{}};return"image_modes"in n?{...e,image_modes:n.image_modes}:e}function 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,s=N(i),d=T(i),a=O(r.model_id,r.variant,t),l=se(r,i),u=K(i);return b({id:n,object:"model",created:d,owned_by:"urun",...s!==null?{context_length:s}:{},...a!==null?{pricing:a}:{},...l.published.length>0?{voices:[...l.published]}:{},...u!==null?{capabilities:{reasoning:u}}:{}})}var De=["Vivian","Serena","Uncle_Fu","Dylan","Eric","Ryan","Aiden","Ono_Anna","Sohee"];function 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((s,d)=>s===o[d])))return{published:[...o],defect:null};let r=t.some(i=>i!=null)?`the catalog's engine_args.voices for ${n.model_id}:${n.variant} could not be vouched (empty, malformed, or not an identical non-empty string array on every GPU placement)`:null;return n.model_id==="qwen3-tts-customvoice"?{published:[...De],defect:r}:{published:[],defect:r}}function z(n){let e=n.length>0?A(n):null;return e===null?{published:[],defect:null}: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,s=t.length-6+(r===""?0:Number(r));return(s<=0?`0.${"0".repeat(-s)}${i}`:`${i.slice(0,s)}.${i.slice(s).padEnd(1,"0")}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function 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=A(e);if(!r)return null;let{row:i,matches:s}=r;if(!i.task||Ce[i.task]!==!0)return null;let d=N(s),a=O(i.model_id,i.variant,t),l=Ae(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:T(s),quantization:Oe(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...a?{pricing:ie(a).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...a?{pricing:ie(a).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 s={datacenters:Ee(n?.regions,r),compliance:n?.compliance??null},d=[],a=new Set;for(let l of i){let u=`${l.model_id}:${l.variant}`;if(a.has(u))continue;a.add(u);let c=je(l,e.filter(g=>g.model_id===l.model_id&&g.variant===l.variant),t,s);c&&d.push(c)}return{data:d}}w();var 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=s=>{o||(o=!0,e.removeEventListener("abort",i),t(s))},i=()=>r("aborted");e.addEventListener("abort",i,{once:!0}),n.then(()=>r("pulled"),()=>r("pulled"))})}function pt(n,e){let t=n.stream("stt");if(typeof t.messages!="function")throw new Error("openSessionTurnLane: session.stream('stt') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the engine's own turn/transcript lane");async function*o(){let r=t.messages()[Symbol.asyncIterator]();try{for(;;){if(e!==void 0&&e.aborted)throw ue(e);let i=r.next();if(e!==void 0&&await Je(i,e)==="aborted")throw i.catch(()=>{}),ue(e);let s=await i;if(s.done)return;yield Ue(s.value)}}finally{let i=r.return?.();i&&i.catch(()=>{})}}return o()}var bt="https://api.urun.sh/v1",P=class extends Error{},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 s=n[r];if(s==null)continue;let d=typeof s=="number"?s:typeof s=="string"?Number.parseInt(s,10):NaN;if(!Number.isInteger(d)||d<i){process.stderr.write(`[serving-pool] skipping engine_args.pool (malformed ${String(r)}=${JSON.stringify(s)})
|
|
3
|
+
`),o=!0;break}e[r]=d}return o||Object.keys(e).length===0?null:e}function He(n,e){if(n.length===0)return null;let t;return e.modelId&&(t=n.find(o=>o.model_id===e.modelId&&(!e.variant||o.variant===e.variant))),t||(t=n.find(o=>o.serve_app_slug===e.appSlug||h(`${o.model_id}-${o.variant}`)===e.appSlug||h(o.model_id)===e.appSlug)),t?ze(t.engine_args?.pool):null}function H(n,e,t,o,r){if(!r)throw new p(`shared model "${n}" cannot be gated: no catalog oracle is configured, and a shared endpoint's modality must come from the model's OWN model_catalog row \u2014 never a default`);if(e===void 0||t===void 0)throw new p(`shared model "${n}" resolved without a catalog id + variant to join on`);let i=o.filter(s=>s.model_id===e&&s.variant===t);if(i.length===0)throw new p(`shared model "${n}" names endpoint ${e}:${t} but the catalog has no model_catalog row for it \u2014 the shared block cannot vouch a modality from nothing`);return i}function 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;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,t,o){let r=e.current;return r&&Date.now()-r.at<o?r.value:r?(r.refreshing||(r.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{r.refreshing=void 0}})()),r.value):(e.current={at:Date.now(),value:await t()},e.current.value)}seed(e,t){this.snapshotMintId(t),this.pool.set(e,Promise.resolve(t))}snapshotMintId(e){try{let t=this.keyOf(e),o=e;this.mintedIds.has(o)||this.mintedIds.set(o,t)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??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
|
+
`),E}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,s=r>0?e.slice(r+1):void 0,d=h(i),a=t.endpoints.filter(c=>h(c.model_id)===d&&(s===void 0||c.variant===s)),l=new Set(a.map(c=>c.model_id)),u=[...l][0];return u===void 0||l.size!==1?null:D(t,u,s)}async resolveTarget(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):{appSlug:o};let r=h(t);if(r===o)return{appSlug:o};let i=await this.sharedLane(t);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:i.shared_org_id,gpuSpec:i.endpoint.gpu_spec??void 0,appId:i.endpoint.app_id??void 0};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let s=await this.deployedApps(),d=this.servable(s);if(d.includes(r))return{appSlug:r};let a=d.filter(u=>u.startsWith(`${r}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=s.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(l)throw new P(`model "${t}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let d=(await this.opts.listCatalog()).find(a=>t===a.model_id||t===`${a.model_id}:${a.variant}`||r===h(a.model_id)||r===h(`${a.model_id}-${a.variant}`));if(d)throw new P(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${d.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):{appSlug:o}}async catalogIdentityFor(e){let t=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.then(r=>this.snapshotMintId(r),()=>{}),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),s=i?await i.then(d=>d,()=>null):null;if(s===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(s)!==r&&this.mintedIds.get(s)!==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:s}}async evict(e,t){let o=this.pool.get(e);!o||await o.then(i=>i,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[o,r]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=o.rows,s=o.ok?r:E;o.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
|
|
6
|
+
`);let a=(t?S(t):[]).map(l=>{let u=i.filter(W=>W.model_id===l.model_id&&W.variant===l.variant),c=N(u),g=T(u),f=K(u),v=O(l.model_id,l.variant,s),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>L(l,i,s)),...a]}}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=E,o=[];for(let i of await this.availableIds()){let s=ge(V(i,e));s.length!==0&&o.push(b({...L(i,e,t),image_modes:s}))}let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),d=fe(`${i.model_id}:${i.variant}`,s);if(d.length===0)continue;let a=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(s),owned_by:"urun",image_modes:d});o.push(a)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds())R(_e(i,e))==="stt"&&o.push(L(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(s)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(s),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,Qe as b,Xe as c,rt as d,dt as e,$ as f,pt as g,bt as h,P as i,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 +1 @@
|
|
|
1
|
-
import{j as d}from"./chunk-
|
|
1
|
+
import{j as d}from"./chunk-HPUX2H65.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,23 @@
|
|
|
1
|
+
import{a as Et,c as Oe,d as Rt,e as Ue}from"./chunk-PT5N7AY7.js";import{A as wt,B as bt,C as vt,D as _t,E as St,b as tt,d as nt,e as oe,j as rt,k as ot,m as it,n as at,o as lt,p as ct,q as dt,r as ut,s as ft,u as pt,v as ie,w as ht,x as gt,y as mt,z as yt}from"./chunk-G5VRFFBE.js";import{a as et}from"./chunk-QTHFMDZY.js";import{a as At}from"./chunk-G7CSAISC.js";import{a as kt}from"./chunk-L4QBHSVY.js";import{l as st,m as se}from"./chunk-BWYY4IPR.js";import{a as Lt,c as X,e as xe}from"./chunk-KKCUIOL4.js";import{a as Xe}from"./chunk-4NMMWAKD.js";import{b as qe,d as Ne}from"./chunk-GX243AIV.js";import{e as Qe,j as ne,n as Ze,o as re,p as Ie}from"./chunk-HPUX2H65.js";import{c as L}from"./chunk-YSFSRI3D.js";L();import{Counter as K,Gauge as ae,Histogram as le,Registry as fn,collectDefaultMetrics as pn}from"@prometheus-io/client";import{createServer as hn}from"http";var lo=9464,Ct="/metrics",ce="(other)",gn="(none)",mn=64,yn=128,wn=["/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",pt,gt,Qe],bn=new Set(wn);function vn(t){return bn.has(t)?t:ce}function _n(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var de=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?gn:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,ce):(this.admitted.add(e),e):ce}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ue=class{registry=new fn;modelLabel=new de(mn);orgLabel=new de(yn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ae({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 K({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 le({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 le({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 K({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 K({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 K({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 mt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ae({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"},yt()),this.ledgerQueue.set({measure:"oldest_age_seconds"},wt()/1e3)}}),this.labelCardinality=new ae({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 K({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 ae({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 le({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 le({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 K({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 K({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&&pn({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=vn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),o=this.modelLabel.overflowCount+this.orgLabel.overflowCount,s=this.modelLabel.of(e.model,r),i=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-o>0&&(this.modelLabel.overflowCount>o?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let c=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?ce:e.method,status_class:_n(e.status),stream:c,model:s,org:i}),this.duration.observe({lane:n,stream:c,model:s,org:i},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:s,org:i},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:s}),e.delivered||this.undelivered.inc({lane:n,model:s})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Pt(t){return hn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ct){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ct}
|
|
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 Nt}from"crypto";import{createServer as Sn}from"http";var ho=9465,kn="x-urun-key-id",En="x-urun-key-fingerprint",Rn="urun-ratelimit-bucket:",Ln="urun-ratelimit-tier:",Tt="anonymous",An=/^urun_sk_[A-Za-z0-9_-]{43}$/;function Cn(t){return Nt("sha256").update(`${Rn}${t}`).digest("hex")}function Pn(t){return Nt("sha256").update(`${Ln}${t}`).digest("hex")}function Tn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return An.test(n)?n:null}function It(){return Sn((t,e)=>{let n=Tn(t.headers.authorization);e.setHeader(kn,n===null?Tt:Cn(n)),e.setHeader(En,n===null?Tt:Pn(n)),e.writeHead(200),e.end()})}L();import{createClientToken as Nn,ClientTokenError as In}from"@urun-sh/core";import{createPublicKey as On,verify as Un}from"crypto";var Ot="urun-session-gateway",xn="machine",$n=3e5;function Dn(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var I=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}},H=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function he(t){let e=(t??"").trim();if(e==="")throw new I("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 I("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var Hn=60,Mn=6e4,Fn=4096;function Wn(t){return t===401||t===403}var fe=class{constructor(e){this.opts=e;this.mint=e.mint??Nn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new I("empty Authorization bearer token");let n=this.cache.get(e);if(n&&this.now()-n.at<Mn)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 s=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:Hn});r=s.orgId,o={...s.billingAudience!==void 0?{billingAudience:s.billingAudience}:{},...s.creditsAdmissionOk!==void 0?{creditsAdmissionOk:s.creditsAdmissionOk}:{},...s.creditsRefusalReason!==void 0?{creditsRefusalReason:s.creditsRefusalReason}:{}}}catch(s){throw s instanceof In&&Wn(s.status)?(this.cache.delete(e),new I("the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new H("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}: ${s instanceof Error?s.message:String(s)}`)}if(!r)throw new H("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>=Fn){let s=this.cache.keys().next();s.done||this.cache.delete(s.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 Ut(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}var pe=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<$n)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(i){throw new H("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}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok)throw new H("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 s;try{let i=await o.json();if(!Array.isArray(i.keys))throw new H("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`);s=i.keys}catch(i){throw i instanceof H?i:new H("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 s})().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 I("malformed machine token");let s,i;try{s=Ut(n),i=Ut(r)}catch{throw new I("malformed machine token")}if(s.alg!=="RS256")throw new I(`machine token alg must be RS256 (got ${JSON.stringify(s.alg??null)})`);let a=typeof s.kid=="string"?s.kid:"",c=typeof i.iss=="string"?i.iss:"";if(c===""||!this.opts.issuers.includes(c))throw new I(`machine token issuer is not one this endpoint accepts (${JSON.stringify(c)})`);if(i.aud!==Ot)throw new I(`machine token audience must be ${Ot} (got ${JSON.stringify(i.aud??null)})`);if(i.token_use!==xn)throw new I(`bearer is a ${JSON.stringify(String(i.token_use??""))} token, not a machine token`);let u=typeof i.org_id=="string"?i.org_id:"";if(u==="")throw new I("machine token carries no org_id \u2014 no tenancy to route by");if((typeof i.exp=="number"?i.exp:0)<=Math.floor(this.now()/1e3))throw new I("machine token is expired \u2014 re-mint and retry");let h=w=>w.kty==="RSA"&&w.n!==void 0&&w.e!==void 0,k=await this.jwksKeys(!1),v=a===""?void 0:k.find(w=>w.kid===a&&h(w));if(v===void 0&&(k=await this.jwksKeys(!0),v=a===""?void 0:k.find(w=>w.kid===a&&h(w))),v===void 0)throw new I(`machine token kid ${JSON.stringify(a)} is not in the machine issuer's JWKS`);let f=Buffer.from(`${n}.${r}`,"ascii"),S=Buffer.from(o.replace(/-/g,"+").replace(/_/g,"/"),"base64"),g=!1;try{let w=On({key:v,format:"jwk"});g=Un("RSA-SHA256",f,w,S)}catch{g=!1}if(!g)throw new I("machine token signature failed verification");return{apiKey:e,orgId:u,credential:"machine"}}};function $e(t,e,n){return n!==null&&Dn(t)?n.verify(t):e.resolve(t)}L();var Gn=8080,De="serve",So="0.0.0.0";function Kn(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function ko(t=process.env){let e=(t.PORT??"").trim(),n=e===""?Gn: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=st(se(Kn(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),o=(t.URUN_API_URL??"").trim(),s=o?se(o,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,i=(t.URUN_CATALOG_URL??"").trim(),a=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!i!=!!a)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let c=i?{catalogUrl:se(i,"URUN_CATALOG_URL"),anonKey:a}:null,u=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),d=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!u!=!!d)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let h=u?{keyId:d,key:u}:void 0,k={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()},v=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],f=v.filter((b,_)=>Object.values(k)[_]==="");if(f.length!==0&&f.length!==v.length)throw new Error(`${v.join(", ")} must be set together (or all left unset) \u2014 missing: ${f.join(", ")}, which would half-configure the lane plane`);let S=f.length===0?k:void 0,g={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},w=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],A=w.filter((b,_)=>Object.values(g)[_]==="");if(A.length!==0&&A.length!==w.length)throw new Error(`${w.join(", ")} must be set together (or all left unset) \u2014 missing: ${A.join(", ")}, which would half-configure the pooler cutover`);let E=A.length===0?g:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},m=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],C=m.filter((b,_)=>Object.values(p)[_]==="");if(C.length!==0&&C.length!==m.length)throw new Error(`${m.join(", ")} must be set together (or all left unset) \u2014 missing: ${C.join(", ")}, which would half-configure the machine-identity rung`);let T=p.issuers.split(",").map(b=>b.trim()).filter(b=>b!=="");if(T.length===0&&C.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 l=Number(p.tokenTtlS);if(C.length===0&&(!Number.isFinite(l)||l<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let y=C.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:T,tokenTtlS:l}:void 0;return{port:n,baseUrl:r,apiUrl:s,catalog:c,ledgerSigning:h,lane:S,pooler:E,machine:y}}L();import{createHash as Qn,randomUUID as Ht}from"crypto";L();import{request as Bn}from"http";var jn="/pooler/v1/inference",B=class extends Error{constructor(n,r,o,s){super(o);this.status=n;this.code=r;this.retryAfterSeconds=s;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Jn=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)},Vn=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)}},$t=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)}),zn=async t=>{let e="pooler_error",n=`the pooler refused the request (HTTP ${t.status})`;try{let r=JSON.parse(await $t(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 B(t.status,e,n,t.retryAfterSeconds)};async function Yn(t,e,n,r,o){let s=new URL(`${t.baseUrl.replace(/\/+$/,"")}${jn}`),i=JSON.stringify({region:t.region,model:r,request_id:n,streaming:o,payload:e,affinity:{systemPrompt:Jn(e),firstMessage:Vn(e)}});return new Promise((a,c)=>{let u=Bn({hostname:s.hostname,port:s.port===""?void 0:Number(s.port),path:`${s.pathname}${s.search}`,method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json",accept:o?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(i))}},d=>{let h=Number(d.headers["retry-after"]??"");a({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(h)?h:void 0,body:d})});u.on("error",d=>c(new B(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),u.end(i)})}var xt=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*qn(t){let e="";for await(let r of t.body)for(e+=String(r);;){let o=e.indexOf(`
|
|
4
|
+
|
|
5
|
+
`);if(o===-1)break;let s=e.slice(0,o);e=e.slice(o+2);let i=xt(s);i!==null&&(yield i)}let n=xt(e);n!==null&&(yield n)}async function Dt(t,e,n,r){let o=qe(e,n,r),s=o.model??"";if(s==="")throw new B(400,"missing_model","the pooler submit requires a model");let i=await Yn(t,o,n,s,e.stream===!0);if(i.status>=400)throw await zn(i);let a=e.stream===!0?Ne(n,qn(i)):await Xn(i,n);return(async function*(){yield{type:"response.created",response:{id:`resp_${n}`,status:"in_progress"}},yield*a})()}async function Xn(t,e){let n=await $t(t.body),r=null;try{let s=JSON.parse(n);s!==null&&typeof s=="object"&&(r=s)}catch{r=null}if(r===null)throw new B(502,"pooler_bad_body","the pooler answered a non-object body");let o=r;return Ne(e,(async function*(){yield o})())}var Zn=512;function ge(t){return`urun-inference-proxy-${Qn("sha256").update(t).digest("hex").slice(0,32)}`}var me=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let o=Object.assign(Object.create(e),{tenant:n.orgId}),s=this.opts.pooler;if(s===void 0)return o;let i=this.opts.lanes;return Object.assign(Object.create(o),{createResponse:async(a,c)=>{if(i!==void 0&&r!==void 0&&(await r.resolveTargetFor(a.model).catch(()=>null))?.sharedApp)return await o.createResponse(a,c);let u=`px_${Ht()}`;return Dt(s,a,u,u)}})}build(e){if(this.opts.build){let s=this.opts.build(e);return s.decision&&this.ensureDecisionReaper(),{router:s.router,clients:this.label(s.clients,e,s.router),decision:s.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:De,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:Et(process.env,process.env.HOSTNAME)??void 0},r=Oe(n),o=n.decisionPool?Rt(n,r):null;return o&&this.ensureDecisionReaper(),{router:r,clients:this.label(Ue(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>=Zn;){let o=this.tenants.entries().next();if(o.done)break;let[s,i]=o.value;this.tenants.delete(s),i.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let o=[r.router.closeAll().catch(s=>{n.push(String(s instanceof Error?s.message:s))})];r.decision&&o.push(r.decision.close().catch(s=>{n.push(String(s instanceof Error?s.message:s))})),await Promise.all(o)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Mt=512,er=1024,ye=class extends Error{constructor(){super(`conversation capacity reached (${Mt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function tr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(re))return{concurrencyKey:e};if(n.startsWith(re)||n.startsWith(Ie))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(re)||n.startsWith(Ie)||t.set(n,r)}}}function nr(t,e,n,r,o){let s=Oe({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:De,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",...tr(r,o)});return{clients:Ue(s,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await s.closeAll()}}}var we=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let o={id:n,subject:r!==void 0?`${ge(e.apiKey)}:live`:`${ge(e.apiKey)}:live:${n}`},s=new Map,i=this.opts.build?this.opts.build(e,o):nr(this.opts,e,o,s,r);return{id:n,backhaul:i,attachments:0,nativeRefs:s}}attachEntry(e,n,r){let o=this.byCaller.get(e.apiKey);o===void 0&&(o=new Map,this.byCaller.set(e.apiKey,o));let s=o.get(n);if(s!==void 0)return o.delete(n),o.set(n,s),s.attachments+=1,s;this.evictOverflow();let i=this.build(e,n,r);return i.attachments=1,o.set(n,i),i}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Mt;){let e=this.byCaller.keys().next();if(e.done)throw new ye;let n=e.value,r=this.byCaller.get(n),o=!1;for(let[s,i]of r)if(!(i.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),i.backhaul.release().catch(()=>{}),o=!0;break}if(!o)throw r.size===0&&this.byCaller.delete(n),new ye;r.size===0&&this.byCaller.delete(n)}}dropHandleIndexFor(e,n){for(let[r,o]of this.byHandle)o.apiKey===e&&o.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,o=!1,s=()=>(r===null&&(r=this.attachEntry(e,Ht(),n)),r),i={createResponse:(a,c)=>s().backhaul.clients.createResponse(a,c),catalogIdentity:a=>s().backhaul.clients.catalogIdentity(a),servingAppSlug:a=>{let c=s().backhaul.clients.servingAppSlug;if(c===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 c(a)},listModels:()=>s().backhaul.clients.listModels(),sessionHandle:a=>s().backhaul.clients.sessionHandle(a),dedicatedSessionHandle:a=>{let c=s().backhaul.clients.dedicatedSessionHandle;return c===void 0?s().backhaul.clients.sessionHandle(a):c(a)},releaseSessionHandle:a=>s().backhaul.clients.releaseSessionHandle?.(a),createResponseOn:(a,c,u)=>s().backhaul.clients.createResponseOn(a,c,u),onSessionEnd:(a,c)=>s().backhaul.clients.onSessionEnd(a,c)};return i.openAudio=async(a,c)=>{let u=s().backhaul.clients.openAudio;if(u===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return u(a,c)},i.openVideo=async a=>{let c=s().backhaul.clients.openVideo;if(c===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return c(a)},i.openVideoOut=async a=>{let c=s().backhaul.clients.openVideoOut;if(c===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return c(a)},i.supportsAudio=async a=>{let c=s().backhaul.clients.supportsAudio;if(c===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return c(a)},i.supportsSpeech=async a=>{let c=s().backhaul.clients.supportsSpeech;if(c===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return c(a)},i.speechVoices=async a=>{let c=s().backhaul.clients.speechVoices;if(c===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 c(a)},i.speechSessionHandle=async a=>{let c=s().backhaul.clients.speechSessionHandle;if(c===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 c(a)},i.openAudioOn=async(a,c,u)=>{let d=s().backhaul.clients.openAudioOn;if(d===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return d(a,c,u)},i.openVideoOn=async(a,c)=>{let u=s().backhaul.clients.openVideoOn;if(u===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return u(a,c)},i.openTurnsOn=(a,c)=>{let u=s().backhaul.clients.openTurnsOn;if(u===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return u(a,c)},i.evictSpeechSession=async a=>{let c=s().backhaul.clients.evictSpeechSession;if(c===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 c(a)},i.supportsTranscription=async a=>{let c=s().backhaul.clients.supportsTranscription;if(c===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return c(a)},i.transcriptStreamFor=async a=>{let c=s().backhaul.clients.transcriptStreamFor;if(c===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 c(a)},i.listSpeechToTextModels=async()=>{let a=s().backhaul.clients.listSpeechToTextModels;if(a===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return a()},{clients:i,bindResumeHandle:a=>{let c=r;if(c===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=er;){let u=this.byHandle.keys().next();if(u.done)break;this.byHandle.delete(u.value)}this.byHandle.set(a,{apiKey:e.apiKey,conversationId:c.id})},clientsForResume:async a=>{let c=this.byHandle.get(a),u=c===void 0?void 0:this.byCaller.get(c.apiKey),d=c===void 0||u===void 0?void 0:u.get(c.conversationId);if(c===void 0||d===void 0||c.apiKey!==e.apiKey)throw new ne("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=d,d.attachments+=1,d.backhaul.clients},release:async()=>{if(o)return;o=!0;let a=r;r=null,a!==null&&(a.attachments-=1,!(a.attachments>0)&&await a.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let o of r.values())e.push(o.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(o){n.push(String(o instanceof Error?o.message:o))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};L();var rr="/inference-ledger",or=1e4,be=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},Fe=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},$=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},We=class extends I{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ge=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},sr=[["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",He],["output_minutes",He],["cost_nano_usd",He],["price_version",t=>t===null||typeof t=="string"]];function ir(t){for(let[e,n]of sr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function ar(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"}:ir(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function He(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function Me(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function lr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function Ft(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 cr(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&&Ft(t.started_at,n.started_at)&&Ft(t.completed_at,n.completed_at)&&Me(t.prompt_tokens,n.prompt_tokens)&&Me(t.completion_tokens,n.completion_tokens)&&Me(t.output_units,n.output_units)&&lr(t.output_minutes,n.output_minutes)}function dr(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 ur(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(dr(t)));return{signature:Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join(""),key_id:e.keyId}}function fr(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new $(`${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 $(`${e} answered a row with no inference_id: ${JSON.stringify(t)}`);if(!("cost_nano_usd"in n))throw new $(`${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 $(`${e} answered cost_nano_usd ${JSON.stringify(o)}, which is neither a non-negative integer nor null`);let s=u=>{if(!(u in n))throw new $(`${e} answered a row with no ${u} field: ${JSON.stringify(t)}`);let d=n[u];if(d===null)return null;if(typeof d!="string")throw new $(`${e} answered a non-string ${u}: ${JSON.stringify(d)}`);if(!/[^\s]/.test(d))throw new $(`${e} answered a BLANK ${u} (${JSON.stringify(d)}) \u2014 it satisfies "is a string" while naming nothing, which is exactly what inference_requests_priced_attribution_check exists to forbid`);return d},i=s("price_version"),a=s("unpriced_reason"),c=o!=null;if(c&&(i===null||a!==null))throw new $(`${e} answered a PRICED row (cost_nano_usd ${String(o)}) that is not cleanly attributed \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}`);if(!c&&(i!==null||a===null))throw new $(`${e} answered an UNPRICED row that does not say why \u2014 price_version ${JSON.stringify(i)}, unpriced_reason ${JSON.stringify(a)}. NULL means NOT YET PRICED, and the reason is how an operator learns that traffic is being served which nobody can bill.`);return{inference_id:r,cost_nano_usd:o===void 0?null:o,price_version:i,unpriced_reason:a}}var ve=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async write(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${rr}`,o;try{o=this.opts.signing?JSON.stringify({...n,...await ur(n,this.opts.signing)}):JSON.stringify(n)}catch(u){throw new $(`the ledger row for inference_id ${n.inference_id} could not be SIGNED before posting: ${u instanceof Error?u.message:String(u)}`)}let s;try{s=await this.fetchImpl(r,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:o,signal:AbortSignal.timeout(or)})}catch(u){throw new $(`the uRun ledger surface at ${r} could not be reached: ${u instanceof Error?u.message:String(u)}`)}if(s.status===409){let u=await s.text().catch(()=>""),d=ar(u);throw d.status==="found"&&cr(n,d.row)?new Fe(d.row,`the uRun control plane already holds THIS PROXY'S OWN row for inference_id ${n.inference_id} \u2014 every billable field matches the row being re-sent, so an earlier attempt landed and this retry is a no-op. Nothing was written and nothing was overwritten.`):d.status==="not_in_this_org"?new be(`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 be(`the uRun control plane already holds a ledger row for inference_id ${n.inference_id} that is NOT the one being written${d.status==="unavailable"?" (and it could not be read back to compare)":""} \u2014 nothing was written and nothing was overwritten. Either this proxy wrote twice, or a row was fabricated ahead of it (this write is authenticated by the CALLER'S OWN org key). ${u.slice(0,400)}`)}if(s.status===401||s.status===403)throw await s.text().catch(()=>{}),new We("the uRun org API key was rejected by the uRun control plane when writing the inference ledger \u2014 the request was served but produced no billable row");if(!s.ok){let u=await s.text().catch(h=>`<body unreadable: ${h instanceof Error?h.message:String(h)}>`),d;try{let h=JSON.parse(u);if(h!==null&&typeof h=="object"&&"error"in h){let k=h.error;k!==null&&typeof k=="object"&&"code"in k&&(d=k.code)}}catch{}throw d==="ledger_signature_invalid"?new Ge(`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: `+u.slice(0,400)):new $(`the uRun ledger surface at ${r} answered HTTP ${s.status}: ${u.slice(0,400)}`)}let i;try{i=await s.json()}catch(u){throw new $(`the uRun ledger surface at ${r} answered a body that is not JSON: ${u instanceof Error?u.message:String(u)}`)}let a=i?.recorded;if(a===void 0)throw new $(`the uRun ledger surface at ${r} answered a body with no "recorded" field`);let c=fr(a,`the uRun ledger surface at ${r}`);if(c.inference_id!==n.inference_id)throw new $(`the uRun ledger surface at ${r} answered for inference_id ${c.inference_id} when asked about ${n.inference_id}`);return c}};L();import{createServer as Vr}from"http";L();import{SessionAllocationError as Er}from"@urun-sh/core";import{createWebsocketDocConnector as Rr}from"@urun-sh/core/internal";import Lr from"ws";L();import{request as pr}from"http";var hr="/pooler/v1/lanes/pick",gr="/pooler/v1/lanes/status",mr=1e4,Z=class extends Error{constructor(e){super(e),this.name="LanePickTimeoutError"}};function Wt(t,e,n,r,o){return new Promise((s,i)=>{let a=new URL(n,t.baseUrl),c=r===void 0?void 0:Buffer.from(JSON.stringify(r)),u=pr({hostname:a.hostname,port:a.port,path:`${a.pathname}${a.search}`,method:e,headers:{authorization:`Bearer ${t.token}`,...c===void 0?{}:{"content-type":"application/json","content-length":String(c.byteLength)}},timeout:o},d=>{let h=[];d.on("data",k=>h.push(k)),d.on("end",()=>{let k=Buffer.concat(h).toString("utf8"),v=null;try{v=k===""?null:JSON.parse(k)}catch{v=null}s({status:d.statusCode??0,json:v})}),d.on("error",i)});u.on("timeout",()=>{u.destroy(new Z(`pooler lane surface timed out after ${o}ms (${e} ${n})`))}),u.on("error",i),u.end(c)})}function Gt(t,e,n){if(t===503)return new oe(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 Kt(t){return{async pick({pool:e,model:n,holdMs:r=0}){let o=Math.min(Math.max(Math.trunc(r),0),At),s=await Wt(t,"POST",hr,{pool:e,model:n,hold_ms:o},o+mr);if(s.status!==200)throw Gt(s.status,s.json,e);return(s.json?.lanes??[]).filter(a=>typeof a.lane_id=="string"&&a.lane_id!==""&&typeof a.host=="string"&&a.host!=="").map(a=>({laneId:a.lane_id,host:a.host}))},async status(){let e=await Wt(t,"GET",gr,void 0,5e3);if(e.status!==200)throw Gt(e.status,e.json,"");let n=e.json;return Array.isArray(n?.pools)?n.pools:[]},async close(){}}}L();import*as j from"yjs";import{SessionDocumentImpl as yr}from"@urun-sh/core/internal";var wr=3e4;function br(t){return(e,n,r)=>{let o=t(e);j.applyUpdate(n,j.encodeStateAsUpdate(o));let s=a=>j.applyUpdate(o,a),i=a=>j.applyUpdate(n,a);return n.on("update",s),o.on("update",i),{awareness:r,get synced(){return!0},onSync(){return()=>{}},destroy(){n.off("update",s),o.off("update",i)}}}}function Ke(t){let{laneId:e}=t,n=t.connector??(t.roomDoc?br(t.roomDoc):null);if(n===null)throw new Error("createLaneSession requires exactly one of roomDoc (in-process host) or connector (remote join)");let r=new Map,o=!1,s=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let h=r.get(d);return h||(h=new yr(d,e,n),r.set(d,h)),h},i=new Map,a=d=>{if(o)throw new Error(`lane ${e} is destroyed \u2014 the doc host shut down or the lane was evicted`);let h=i.get(d);if(!h){if(!t.streamEndpoint)throw new Error(`lane ${e} carries no stream plane \u2014 createLaneSession needs streamEndpoint for "${d}"`);h=t.streamEndpoint(d),i.set(d,h)}return h},c=d=>{let h="llm-resp:";if(!d.startsWith(h))throw new Error(`lane session exposes no stream "${d}" \u2014 only the llm reply lanes (${h}<rid>)`);async function*k(){let v=a(d);try{yield*v.messages()}finally{i.delete(d),await v.close()}}return{messages:()=>k(),attach:async()=>{throw new Error("lane session carries no media track \u2014 the reply lane is a \xA75 data stream")},detach:async()=>{},track:null}};return{id:e,sessionId:e,consumerId:t.consumerId??`lane-${e}`,doc(d){return s(d)},stream:c,streamEndpoint:a,async end(){},async whenLive(d){let h=s("llm");if(h.synced===!0)return;let k=d?.timeout??t.whenLiveTimeoutMs??wr;await new Promise((v,f)=>{let S=setTimeout(()=>{g(),f(new Error(`lane ${e} llm doc never synced within ${k}ms`))},k),g=h.onSynced(()=>{clearTimeout(S),d?.signal?.removeEventListener("abort",w),v()}),w=()=>{clearTimeout(S),g(),f(d?.signal?.reason instanceof Error?d.signal.reason:new Error("aborted"))};d?.signal?.addEventListener("abort",w,{once:!0})})},destroy(){o=!0;for(let d of r.values())d.dispose();r.clear();for(let[d,h]of i)i.delete(d),h.close()}}}L();import _e,{WebSocketServer as vr}from"ws";import{ENVELOPE_KIND as zt,STREAM_END as _r,StreamFragmentReassembler as Sr}from"@urun-sh/core";var Bt="/stream/";function jt(t){if(!t.startsWith(Bt))return null;let e=t.slice(Bt.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 Ee(t){return t==="control"?"urun-control-v1":"urun-stream-v1"}function Se(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>zt.CHUNK)throw new Error(`unknown envelope kind 0x${e.toString(16)}`);return{kind:e}}var ke=class{reassembler=new Sr;queue=[];wake=null;ended=!1;failure=null;feed(e){let n=this.reassembler.feed(e);return n===_r&&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})}}},je=class{channels=new Map;chan(e,n){let r=`${e}::${n}`,o=this.channels.get(r);return o||this.channels.set(r,o={peers:new Set,pending:{list:[],bytes:0,warned:!1}}),o}deliver(e,n,r,o){let s=this.chan(e,n),i=[...s.peers].filter(a=>a!==r);if(i.length===0){let a=s.pending;(a.list.length>=Jt||a.bytes+o.byteLength>Vt)&&(a.list.shift(),a.warned||(a.warned=!0,console.warn(`[lane-stream] ${e}/${n}: pre-attach buffer overflowed \u2014 dropping oldest envelopes (bounded ${Jt} frames / ${Vt} bytes)`))),a.list.push({envelope:o,producer:r}),a.bytes+=o.byteLength;return}for(let a of i)a.deliver(o)}attach(e,n,r){let o=this.chan(e,n);o.peers.add(r);let s=o.pending;if(s.list.length===0)return;let i=s.list.filter(a=>a.producer!==r);s.list=s.list.filter(a=>a.producer===r),s.bytes=s.list.reduce((a,c)=>a+c.envelope.byteLength,0);for(let{envelope:a}of i)r.deliver(a)}detach(e,n,r){let o=`${e}::${n}`,s=this.channels.get(o);if(s){for(let i of[...s.peers])i===r&&s.peers.delete(i);s.peers.size===0&&s.pending.list.length===0&&this.channels.delete(o)}}forgetLane(e){let n=`${e}::`;for(let r of[...this.channels.keys()]){if(!r.startsWith(n))continue;let o=this.channels.get(r);this.channels.delete(r);for(let s of o?.peers??[])s.close(1001,"lane stream host shutting down")}}clear(){for(let e of[...this.channels.keys()]){let n=this.channels.get(e);this.channels.delete(e);for(let r of n?.peers??[])r.close(1001,"lane stream host shutting down")}}},Jt=256,Vt=8*1024*1024,M=new je;function Yt(t,e){let n=new ke,r={send(o){M.deliver(t,e,r,o)},deliver(o){if(!n.isEnded){try{Se(o)}catch(s){console.warn(`[lane-stream] ${t}/${e}: dropped malformed envelope: ${String(s)}`);return}n.push(n.feed(o))}},messages:()=>n.iterate(),async close(){n.finish(),M.detach(t,e,r)}};return M.attach(t,e,r),r}function kr(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 qt(t,e,n){let r=`${n.hostUrl}/${encodeURIComponent(e)}?token=${encodeURIComponent(n.token())}`,o=new _e(r,Ee(e)),s=new ke;return o.addEventListener("message",i=>{let a=new Uint8Array(i.data);try{Se(a)}catch(c){console.warn(`[lane-stream] remote ${r}: dropped malformed envelope: ${String(c)}`);return}s.push(s.feed(a))}),o.addEventListener("close",()=>{s.finish(new Error(`lane stream ${r} closed before END`))}),o.addEventListener("error",()=>{s.finish(new Error(`lane stream ${r} socket error`))}),{send(i){if(Se(i),o.readyState!==_e.OPEN)throw new Error(`lane stream ${r} is not open \u2014 cannot send`);o.send(i,{binary:!0})},deliver(i){throw new Error("laneStreamWsEndpoint.deliver: remote endpoints receive over their own socket")},messages:()=>s.iterate(),async close(){s.finish();try{o.close(1e3)}catch{}}}}function Be(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 Xt(t,e){let n=e.heartbeatMs??3e4,r=new vr({noServer:!0,handleProtocols:(u,d)=>{let h=jt(new URL(d.url??"/","http://localhost").pathname);if(!h)return!1;let k=Ee(h.name);return u.has(k)?k:!1}}),o=new Map,s=new Set,i=!1,a=(u,d,h,k)=>{let v={client:h,upstream:k,laneId:u,name:d};s.add(v);let f=S=>{if(s.delete(v)){console.warn(`[lane-stream] ${u}/${d}: host-affinity pump torn down (${S})`);for(let g of[h,k])try{(g.readyState===_e.OPEN||g.readyState===_e.CONNECTING)&&g.close(1001,"lane stream pump closed")}catch{}}};if(n>0){let S=(g,w)=>{let A=!0;g.on("pong",()=>{A=!0});let E=setInterval(()=>{if(!A){console.warn(`[lane-stream] ${u}/${d}: pong timeout on ${w} \u2014 reaping silent pump peer (pre-wedge signal: a stalled ${w} dial never sends a close)`),clearInterval(E);try{g.terminate()}catch{}f(`${w} pong timeout`);return}A=!1;try{g.ping()}catch{}},n);E.unref?.();let p=()=>clearInterval(E);g.once("close",p),g.once("error",p)};S(h,"client"),S(k,"host")}h.on("message",S=>{try{k.send(S,{binary:!0})}catch(g){f(`upstream send failed: ${String(g)}`)}}),k.on("message",S=>{try{h.send(S,{binary:!0})}catch(g){f(`client send failed: ${String(g)}`)}}),h.on("close",()=>f("client socket closed")),h.on("error",()=>f("client socket error")),k.on("close",()=>f("host socket closed")),k.on("error",()=>f("host socket error"))},c=(u,d,h)=>{let k;try{k=new URL(u.url??"/","http://localhost")}catch{Be(d,400,"malformed upgrade URL");return}d.on("error",()=>d.destroy());let v=jt(k.pathname);v&&(i||d.destroyed||(async()=>{let f=k.searchParams.get("token")??"",S=null;try{S=f===""?null:await e.verifyToken(f,v.laneId,v.name)}catch{S=null}if(S===null){Be(d,401,"invalid or missing lane stream token");return}if(e.selfAddress&&e.hostOf&&e.podToPodDial){let g=await e.hostOf(v.laneId).catch(()=>null);if(g&&g!==e.selfAddress)try{let w=await e.podToPodDial(v.laneId,v.name,g);r.handleUpgrade(u,d,h,A=>{a(v.laneId,v.name,A,w)});return}catch(w){console.warn(`[lane-stream] ${v.laneId}/${v.name}: host dial to ${g} failed (${String(w)}) \u2014 falling back to the local relay`)}}r.handleUpgrade(u,d,h,g=>{let w=kr(g);if(o.set(g,w),M.attach(v.laneId,v.name,w),n>0){let E=!0;g.on("pong",()=>{E=!0});let p=setInterval(()=>{if(!E){console.warn(`[lane-stream] ${v.laneId}/${v.name}: pong timeout \u2014 reaping silent wire peer (pre-wedge signal: a stalled runtime dial never sends a close)`),clearInterval(p),g.terminate();return}E=!1;try{g.ping()}catch{}},n);p.unref?.();let m=()=>clearInterval(p);g.once("close",m),g.once("error",m)}g.on("message",E=>{let p=new Uint8Array(E);try{Se(p)}catch(m){console.warn(`[lane-stream] ${v.laneId}/${v.name}: dropped malformed envelope: ${String(m)}`);return}M.deliver(v.laneId,v.name,w,p),p[1]===zt.END&&M.detach(v.laneId,v.name,w)});let A=()=>{o.delete(g),M.detach(v.laneId,v.name,w)};g.on("close",A),g.on("error",A)})})().catch(()=>{d.destroyed||Be(d,500,"lane stream upgrade failed")}))};return t.on("upgrade",c),{async close(){i=!0,t.off("upgrade",c),M.clear();for(let u of o.values())u.close(1001,"lane stream host shutting down");o.clear();for(let u of s)for(let d of[u.client,u.upstream])try{d.close(1001,"lane stream host shutting down")}catch{}s.clear()}}}function Ar(t){let e=(t.gpuSpec??"").split(":")[0];if(typeof t.appId!="string"||t.appId==="")throw new nt(`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 Qt(t){let e=t.now??Date.now,n=new Map,r=new Map,o=new Set,s=new Map,i=new Set,a=(f,S,g,w,A,E)=>{let p=g?l=>Yt(f,l):l=>qt(f,l,{hostUrl:`ws://${w}/stream/${f}`,token:()=>X(f,t.tokenSecret,void 0,void 0,E)}),m=g?Ke({laneId:f,roomDoc:l=>t.roomDoc(f,l),streamEndpoint:p}):Ke({laneId:f,streamEndpoint:p,connector:Rr({serverUrl:`ws://${w}/doc`,sessionId:f,token:()=>X(f,t.tokenSecret,void 0,void 0,E),WebSocketPolyfill:Lr})}),C=g?c(f):kt(m,`lane:${f}`,{armOnFirstSync:!0}),T={session:m,responses:new Xe(m,{sessionTag:null}),gone:C,goneWatch:C,laneId:f,pool:S,inFlight:0,laneSession:m,self:g,host:w??"",mintedRelease:A??"",retireWhenIdle:!1};return n.set(f,T),C.onGone(()=>u(T)),T},c=f=>{let S=null,g=!1,w=new Set,A=p=>{if(!S){S=p;for(let m of[...w])m(p);w.clear()}},E=t.hostedSignal?.(f,p=>{if(p){g=!0;return}g&&A(new ne(`the lane ${f} 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:()=>S,onGone(p){return S?(p(S),()=>{}):(w.add(p),()=>w.delete(p))},dispose(){E?.(),w.clear()}}},u=f=>{d(f)&&(n.delete(f.laneId),r.delete(f.laneId),f.goneWatch?.dispose(),M.forgetLane(f.laneId))},d=f=>{let S=f.laneId;return typeof S=="string"&&n.get(S)===f},h=f=>{d(f)&&(f.self&&!t.closeLane||(i.add(f.laneId),f.self&&t.closeLane?.(f.laneId),u(f)))},k=(f,S)=>{throw t.metrics?.observeLane503Fast(S??""),s.set(f,e()),new oe(f)},v=async(f,S)=>{let g=Ar(S);o.add(g);let w=e();try{let A=await t.laneWarmWaitMsFor?.(f,S)??t.laneColdWakeDefaultMs??0,E;try{E=await t.plane.pick({pool:g,model:f,holdMs:A})}catch(y){throw y instanceof Z?new Er(`lane pick hold expired for ${g}: ${y.message} \u2014 the lane demand stays enqueued`,{code:"queue_timeout"}):y}t.metrics?.observeLaneReady(f??"",E.length);let p=await t.currentReleaseOf?.(S)??null,m=new Set(E.map(y=>y.laneId));for(let y of i)m.has(y)||i.delete(y);let T=E.filter(y=>{let b=n.get(y.laneId);return b!==void 0&&p!==null&&b.mintedRelease!==""&&b.mintedRelease!==p&&(b.retireWhenIdle=!0,b.inFlight===0)?(h(b),!1):!i.has(y.laneId)}).map(y=>({laneId:y.laneId,self:y.host===t.selfAddress,host:y.host})).sort((y,b)=>y.self!==b.self?y.self?-1:1:(r.get(y.laneId)??0)-(r.get(b.laneId)??0))[0];T||k(g,f);let l=n.get(T.laneId);return l?.goneWatch?.gone()&&(u(l),l=void 0),l&&(l.pool!==g||l.self!==T.self||l.host!==T.host)&&(u(l),l=void 0),l||(l=a(T.laneId,g,T.self,T.host,p,S.sharedOrgId??void 0)),l.inFlight+=1,r.set(T.laneId,(r.get(T.laneId)??0)+1),{app:g,entry:l,identity:{kind:"catalog",model_id:S.modelId??f??"",variant:S.variant??""}}}finally{t.metrics?.observeLanePick(f??"",e()-w)}};return{sessionFor(f,S){return v(f,S)},release(f){d(f)&&(f.inFlight=Math.max(0,f.inFlight-1),r.set(f.laneId,f.inFlight),f.inFlight===0&&f.retireWhenIdle&&h(f))},owns(f){return d(f)},entryFor(f){return n.get(f)??null},evict(f){d(f)&&(f.gone.dispose(),n.delete(f.laneId),r.set(f.laneId,0),f.laneSession.destroy())},async status(){let f=[...new Set([...o,...[...n.values()].map(w=>w.pool)])].sort(),S=await t.plane.status().catch(()=>[]),g=new Map(Cr(S));return Promise.all(f.map(async w=>{let A=g.get(w)??{pool:w,lanes:[],lastDemandAt:null};return{pool:w,lanes:A.lanes,lastDemandAt:A.lastDemandAt,local:[...n.values()].filter(E=>E.pool===w).map(E=>({laneId:E.laneId,inFlight:E.inFlight,self:E.self,host:E.host})),lastRefusalAt:s.get(w)??null}}))},async close(){for(let f of n.values())f.gone.dispose(),f.laneSession.destroy();n.clear(),r.clear(),await t.plane.close()},stats(){return[...n.values()].map(f=>({pool:f.pool,laneId:f.laneId,inFlight:f.inFlight}))}}}function Cr(t){return new Map(t.map(e=>[e.pool,{lanes:e.lanes,lastDemandAt:e.lastDemandAt}]))}L();var Pr="urun:node-scheduler:apps:v1";function Tr(t){let e=(t.appId??"").trim(),n=(t.fnName??"").trim();return e===""||n===""?null:`${e}/${n}`}function Zt(t){return async e=>{let n=Tr(e);if(n===null)return null;try{let r=await t.hget(Pr,n);if(r===null||r==="")return null;let o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let s=o.current_release_id;if(typeof s!="string")return null;let i=s.trim();return i===""?null:i}catch{return null}}}L();import{WebSocketServer as Gr}from"ws";L();import*as tn from"yjs";import*as z from"y-protocols/sync";import*as W from"y-protocols/awareness";import*as N from"lib0/encoding";import*as Y from"lib0/decoding";import*as nn from"lib0/map";import Ir from"lodash.debounce";L();var en=()=>{};var Or=parseInt(process.env.CALLBACK_DEBOUNCE_WAIT)||2e3,Ur=parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT)||1e4,xr=0,$r=1;var Dr=process.env.GC!=="false"&&process.env.GC!=="0",Hr=process.env.YPERSISTENCE,Re=null;if(typeof Hr=="string")throw new Error("YPERSISTENCE is not supported by the vendored y-websocket utils (no y-leveldb native dep)");var V=new Map,Le=0,Ve=1,Mr=(t,e,n)=>{let r=N.createEncoder();N.writeVarUint(r,Le),z.writeUpdate(r,t);let o=N.toUint8Array(r);n.conns.forEach((s,i)=>ee(n,i,o))},Je=class extends tn.Doc{constructor(e){super({gc:Dr}),this.name=e,this.conns=new Map,this.awareness=new W.Awareness(this),this.awareness.setLocalState(null);let n=({added:r,updated:o,removed:s},i)=>{let a=r.concat(o,s);if(i!==null){let d=this.conns.get(i);d!==void 0&&(r.forEach(h=>{d.add(h)}),s.forEach(h=>{d.delete(h)}))}let c=N.createEncoder();N.writeVarUint(c,Ve),N.writeVarUint8Array(c,W.encodeAwarenessUpdate(this.awareness,a));let u=N.toUint8Array(c);this.conns.forEach((d,h)=>{ee(this,h,u)})};this.awareness.on("update",n),this.on("update",Mr),!1}},ze=(t,e=!0)=>nn.setIfUndefined(V,t,()=>{let n=new Je(t);return n.gc=e,Re!==null&&Re.bindState(t,n),V.set(t,n),n}),Fr=(t,e,n)=>{try{let r=N.createEncoder(),o=Y.createDecoder(n);switch(Y.readVarUint(o)){case Le:N.writeVarUint(r,Le),z.readSyncMessage(o,r,e,t),N.length(r)>1&&ee(e,t,N.toUint8Array(r));break;case Ve:{W.applyAwarenessUpdate(e.awareness,Y.readVarUint8Array(o),t);break}}}catch(r){console.error(r),e.emit("error",[r])}},J=(t,e)=>{if(t.conns.has(e)){let n=t.conns.get(e);t.conns.delete(e),W.removeAwarenessStates(t.awareness,Array.from(n),null),t.conns.size===0&&Re!==null&&(Re.writeState(t.name,t).then(()=>{t.destroy()}),V.delete(t.name))}e.close()},ee=(t,e,n)=>{e.readyState!==xr&&e.readyState!==$r&&J(t,e);try{e.send(n,r=>{r!=null&&J(t,e)})}catch{J(t,e)}},Wr=3e4,rn=(t,e,{docName:n=e.url.slice(1).split("?")[0],gc:r=!0}={})=>{t.binaryType="arraybuffer";let o=ze(n,r);o.conns.set(t,new Set),t.on("message",a=>Fr(t,o,new Uint8Array(a)));let s=!0,i=setInterval(()=>{if(!s)o.conns.has(t)&&J(o,t),clearInterval(i);else if(o.conns.has(t)){s=!1;try{t.ping()}catch{J(o,t),clearInterval(i)}}},Wr);t.on("close",()=>{J(o,t),clearInterval(i)}),t.on("pong",()=>{s=!0});{let a=N.createEncoder();N.writeVarUint(a,Le),z.writeSyncStep1(a,o),ee(o,t,N.toUint8Array(a));let c=o.awareness.getStates();if(c.size>0){let u=N.createEncoder();N.writeVarUint(u,Ve),N.writeVarUint8Array(u,W.encodeAwarenessUpdate(o.awareness,Array.from(c.keys()))),ee(o,t,N.toUint8Array(u))}}};var Ye="/doc/",sn=30,Kr=1e4,on="llm";function Br(t){if(!t.startsWith(Ye))return null;let e=t.slice(Ye.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 an(t,e){let n=new Gr({noServer:!0}),r=new Set,o=new Map,s=new Map,i=p=>o.get(`${p}/${on}`)??0,a=p=>s.get(p)??0,c=new Map,u=new Map,d=new Set,h=new Set,k=new Map,v=new Map,f=4096,S=!1,g=(p,m,C)=>{let T=i(p)>0,l=a(p),y=l>0,b=`${p}/${m}`,_=o.get(b)??0;C>0?o.set(b,C):o.delete(b);let R=l+C-_;R>0?s.set(p,R):s.delete(p);let P=i(p)>0,O=R>0;if(T!==P){P?w(p):A(p);for(let D of c.get(p)??[])D(P)}y&&!O&&queueMicrotask(()=>{let D=`${p}/`;for(let[F,G]of[...V.entries()])!F.startsWith(D)||G.conns.size>0||(V.delete(F),G.destroy())})},w=p=>{if(!e.hostRegistry||u.has(p))return;let m=()=>{e.hostRegistry?.setHost(p,e.selfAddress).catch(()=>{})};m();let C=setInterval(m,Kr);C.unref?.(),u.set(p,C)},A=p=>{let m=u.get(p);m&&(clearInterval(m),u.delete(p)),e.hostRegistry&&e.hostRegistry.delHost(p,e.selfAddress).catch(()=>{})},E=(p,m,C)=>{let T;try{T=new URL(p.url??"/","http://localhost")}catch{q(m,400,"malformed upgrade URL");return}m.on("error",()=>m.destroy()),m.on("close",()=>h.delete(m));let l=Br(T.pathname);if(!l){if(T.pathname.startsWith(Ye)){q(m,404,"malformed lane doc path \u2014 expected /doc/<laneId>/<docName>");return}h.add(m);return}d.add(m);let y=!1;(async()=>{if(v.has(l.laneId)){q(m,409,"lane retired \u2014 the app's release moved; a fresh lane serves it");return}let b=T.searchParams.get("token")??"",_=null;try{_=b===""?null:await e.verifyToken(b,l.laneId,l.docName)}catch{_=null}if(_===null){q(m,401,"invalid or missing lane doc token");return}let R=_;if(R.tenant!==void 0&&e.laneTenantOf){let P=null;try{P=await e.laneTenantOf(l.laneId)}catch{P=null}if(P==null||P==="")e.onLaneTenantMissing?.();else if(R.tenant!==P){q(m,403,"lane doc token org does not match the lane record");return}}S||m.destroyed||(y=!0,n.handleUpgrade(p,m,C,P=>{d.delete(m),r.add(P),P.on("close",()=>r.delete(P));let O=k.get(l.laneId);O||(O=new Set,k.set(l.laneId,O)),O.add(P),P.on("close",()=>{O.delete(P),O.size===0&&k.delete(l.laneId)});let D=R.scope===Lt||R.scope===void 0&&typeof R.app=="string"&&typeof R.fn=="string"&&R.aud==="sfu";if(D){let G=`${l.laneId}/${l.docName}`,te=(o.get(G)??0)+1;g(l.laneId,l.docName,te),te>1&&l.docName===on&&e.hostRegistry?.setHost(l.laneId,e.selfAddress).catch(()=>{})}P.on("close",()=>{if(!D)return;let G=`${l.laneId}/${l.docName}`;g(l.laneId,l.docName,Math.max(0,(o.get(G)??1)-1))}),rn(P,p,{docName:`${l.laneId}/${l.docName}`,gc:!0})}))})().catch(()=>{!y&&!m.destroyed&&q(m,500,"lane doc upgrade failed")}).finally(()=>d.delete(m))};return t.on("upgrade",E),{async close(){S=!0,t.off("upgrade",E);for(let m of[...u.keys()])A(m);await new Promise(m=>{if(r.size===0&&d.size===0){m();return}let C=r.size+d.size,T=()=>{C-=1,C<=0&&m()};for(let l of r)l.once("close",T);for(let l of d)l.once("close",T);for(let l of r)l.close(1001,"lane doc host shutting down");for(let l of d)l.destroy()}),o.clear(),s.clear(),c.clear()},roomDoc(p,m){return ze(`${p}/${m}`,!0)},isHosted(p){return i(p)>0},onHostedChange(p,m){let C=c.get(p);return C||(C=new Set,c.set(p,C)),C.add(m),m(i(p)>0),()=>{C.delete(m)}},closeLane(p){if(v.set(p,!0),v.size>f){let m=v.keys().next().value;m!==void 0&&v.delete(m)}A(p);for(let m of k.get(p)??[])m.close(1001,`lane ${p} retired \u2014 the app's release moved`)}}}import zr from"ws";L();var jr="urun:catalog:v1";function ln(t){let e=t.refreshMs??5e3,n=t.now??Date.now,r=null,o=0,s=null,i=async()=>{let c=await t.redis.hgetall(jr),u=[];for(let d of Object.values(c))try{u.push(JSON.parse(d))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
19
|
+
`)}return r=u,o=n(),u},a=()=>r===null||n()-o>=e;return{rows(){return a()?(s||(s=i().finally(()=>{s=null})),s):Promise.resolve(r)},close(){r=null,s=null}}}import Yr from"ioredis";L();var Ae="/inference-usage",cn=25e3;var Jr=new Set(["Error","TypeError","SyntaxError","TimeoutError"]);function dn(t){if(!(t instanceof Error))return`a ${typeof t}`;let e=Jr.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 Ce=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch}opts;fetchImpl;async lookup(e,n){let r=`${this.opts.apiUrl.replace(/\/+$/,"")}${Ae}`,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(cn)})}catch(i){throw new ie(`the uRun usage surface (POST ${Ae}) could not be reached within ${cn}ms: ${dn(i)}`)}if(o.status===401||o.status===403)throw await o.text().catch(()=>{}),new I("the uRun org API key was rejected by the uRun control plane \u2014 check the key and that it is not revoked");if(!o.ok){let i=await o.text().catch(()=>null),a=i===null?"body unreadable":`${i.length}-character body`;throw new ie(`the uRun usage surface (POST ${Ae}) answered HTTP ${o.status} (${a})`)}let s;try{s=await o.json()}catch(i){throw new ie(`the uRun usage surface (POST ${Ae}) answered HTTP ${o.status} with a body that is not JSON: ${dn(i)}`)}return ht(s,this.opts.onRejectedRow)}};var qr=5e3,Xr=1e3,Qr=1500,Zr=3e3,eo="/api/client-tokens";function Pe(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function un(t,e,n,r){Pe(t,e,{error:{message:n,type:r}})}async function to(t,e=fetch){let n=`${t.replace(/\/+$/,"")}${eo}`;try{let r=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(Zr)});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 ni(t){let e=t.resolver??new fe({gatewayUrl:t.baseUrl}),n=t.machine?new pe({jwksBaseUrl:t.machine.jwksBaseUrl,issuers:t.machine.issuers}):null,r=new ue(t.defaultMetrics===void 0?{}:{defaultMetrics:t.defaultMetrics}),o=null,s=null,i=(()=>{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 l=new Yr(t.lane.valkeyUrl,{lazyConnect:!0,maxRetriesPerRequest:2,commandTimeout:500}),y=ln({redis:l});return{registry:Qt({selfAddress:t.lane.selfAddress,tokenSecret:t.lane.tokenSecret,plane:Kt({baseUrl:t.pooler.baseUrl,token:t.pooler.token}),hostedSignal:(_,R)=>o?.onHostedChange(_,R)??(()=>()=>{}),roomDoc:(_,R)=>{if(!o)throw new Error("lane doc host not attached yet \u2014 requests cannot precede listen");return o.roomDoc(_,R)},metrics:r,laneColdWakeDefaultMs:2e4,laneWarmWaitMsFor:(_,R)=>y.rows().then(P=>{let O=Ze(P,R);return O?.warm_wait_s!==void 0?O.warm_wait_s*1e3:void 0}),currentReleaseOf:Zt(l),closeLane:_=>o?.closeLane(_)}),catalog:y,redis:l}})(),a=t.registry??new me({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry,pooler:t.pooler}),c=t.probeControlPlane??(()=>to(t.baseUrl)),u=async()=>{let l=null;for(let _ of a.decisionPools()){l=_;break}if(!l)return null;let y=l.stats();if(y.some(_=>_.draining))return{ok:!1,detail:"decision pool draining"};if(y.every(_=>_.attached===0&&_.inFlight===0))return{ok:!0,detail:"no active decision slot; gateway accepts on-demand resume"};let b=await l.pingReady(Qr);return{ok:b,detail:b?"a decision slot answered its session ping":"no decision slot answered its session ping"}},d=t.usageClient??new Ce({apiUrl:t.apiUrl}),h=t.ledgerClient??new ve({apiUrl:t.apiUrl,...t.ledgerSigning?{signing:t.ledgerSigning}:{}}),k=process.env.URUN_SHARED_ORG_ID?.trim(),v=process.env.URUN_SHARED_ORG_API_KEY?.trim();k&&v&&(async()=>{try{await a.decisionWarmerFor({orgId:k,apiKey:v})?.warmFor(_t)}catch(l){process.stderr.write(`[decision-warm] out-of-band warm failed (best-effort, retrying on next demand): ${String(l instanceof Error?l.message:l)}
|
|
20
|
+
`)}})();let f=async l=>$e(he(l.headers.authorization),e,n),S=async l=>{let y=await f(l);if(y.billingAudience==="platform"&&y.creditsAdmissionOk===!1){let b=y.creditsRefusalReason;throw new Q(b==="spend_cap_reached"||b==="insufficient_credits"?b:void 0)}return y},g=l=>l instanceof I?{status:l.status,openaiType:"authentication_error",anthropicType:"authentication_error"}:l instanceof Q?{status:402,openaiType:"insufficient_quota",anthropicType:"invalid_request_error",...l.code!==void 0?{code:l.code}:{}}:l instanceof H?{status:502,openaiType:"upstream_error",anthropicType:"api_error",operatorDetail:l.detail}:null,w=St({clients:async l=>a.clientsFor(await S(l)),usage:{authorize:l=>he(l.headers.authorization),lookup:(l,y)=>d.lookup(l,y)},statusOf:g,...t.requestLog?{requestLog:t.requestLog}:{},observe:l=>r.observe(l),ledger:{write:(l,y)=>h.write(he(l.headers.authorization),y),observe:l=>r.observeLedger(l),...t.ledgerLog?{report:t.ledgerLog}:{}}}),A=null,E=null,p=Vr((l,y)=>{let b=new URL(l.url??"/","http://localhost");(async()=>{if(l.method==="GET"&&b.pathname==="/healthz"){Pe(y,200,{ok:!0});return}if(l.method==="GET"&&b.pathname==="/readyz"){let P=Date.now();if((!A||P-A.at>=qr)&&(A={at:P,...await c()}),!E||P-E.at>=Xr){let F=await u();E=F===null?{at:P,ok:!0,detail:null}:{at:P,ok:F.ok,detail:F.detail}}let O=(A?.ready??!1)&&E.ok,D=E.detail===null?A?.detail??"control plane not yet probed":`${A?.detail??"control plane not yet probed"}; ${E.detail}`;Pe(y,O?200:503,{ok:O,control_plane:D});return}if(l.method==="GET"&&b.pathname==="/lanez"){Pe(y,200,{pools:i?await i.registry.status():null});return}let _=b.pathname==="/v1"||b.pathname.startsWith("/v1/"),R=b.pathname.startsWith("/partners/");if(!_&&!R){un(y,404,`no route for ${l.method} ${b.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}w(l,y)})().catch(_=>{if(!y.headersSent){un(y,500,String(_ instanceof Error?_.message:_),"proxy_error");return}y.end()})}),m=t.conversations??new we({baseUrl:t.baseUrl,apiUrl:t.apiUrl,catalog:i?null:t.catalog,catalogRows:i?()=>i.catalog.rows():void 0,lanes:i?.registry}),C=[tt(p,{authenticate:async l=>{let y=await $e(l,e,n),b=m.connectionFor(y);return{clients:b.clients,scope:ge(y.apiKey),onBindResumeHandle:b.bindResumeHandle,clientsForResume:b.clientsForResume,release:b.release}}}),ot(p,{clients:async l=>a.clientsFor(await S(l)),statusOf:g}).close,at(p,{resolver:{resolve:async(l,y)=>{let b=await S(l),_=m.connectionFor(b,ut(l)),R;try{R=await ft(lt(_.clients,t.realtimeCompanions),ct(l),y,dt(l))}catch(O){throw _.release().catch(()=>{}),O}let P=R.release;return{...R,release:async()=>{await P?.(),await _.release()}}}}})];if(t.lane&&i){let l=t.lane,y=(process.env.URUN_SESSION_TOKEN_SECRET_PREVIOUS??"").trim()||void 0;o=an(p,{verifyToken:(_,R)=>xe(_,R,l.tokenSecret,void 0,y),selfAddress:l.selfAddress,laneTenantOf:_=>i.redis.get(`lane_tenant:${_}`),onLaneTenantMissing:()=>r.observeLaneDocTenantMissing(),previousTokenSecret:y,hostRegistry:{setHost:(_,R)=>i.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:${_}`,R,String(sn)),delHost:_=>i.redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",1,`lane_hosts:${_}`,l.selfAddress)}}),s=Xt(p,{verifyToken:(_,R)=>xe(_,R,l.tokenSecret,void 0,y),selfAddress:l.selfAddress,hostOf:async _=>{let R=await i.redis.get(`lane_hosts:${_}`);return R&&R.trim()!==""?R.trim():null},podToPodDial:(_,R,P)=>new Promise((O,D)=>{(async()=>{let F=await i.redis.get(`lane_tenant:${_}`),G=X(_,l.tokenSecret,void 0,void 0,F||void 0),te=`ws://${P}/stream/${encodeURIComponent(_)}/${encodeURIComponent(R)}?token=${encodeURIComponent(G)}`,Te=new zr(te,Ee(R));Te.once("open",()=>O(Te)),Te.once("error",D)})().catch(D)})});let b=i;C.push(async()=>{await o.close(),await s.close(),await b.registry.close(),b.redis.quit().catch(()=>{})})}p.on("upgrade",(l,y)=>{let b=new URL(l.url??"/","http://localhost");b.pathname===et||b.pathname===rt||b.pathname===it||o!==null&&b.pathname.startsWith("/doc/")||s!==null&&b.pathname.startsWith("/stream/")||y.destroyed||(y.write(`HTTP/1.1 404 Not Found\r
|
|
21
|
+
Connection: close\r
|
|
22
|
+
\r
|
|
23
|
+
no WS route for ${b.pathname} \u2014 this endpoint serves only the Gemini Live, /v1/responses, and /v1/realtime upgrade paths`),y.destroy())});let T=async()=>{for(let l of C)await l();await m.detachAll()};return{server:p,metricsServer:Pt(r),metrics:r,edgeIdentityServer:It(),registry:a,closeAll:()=>a.closeAll(),closeWebSockets:T}}async function ri(t,e,n){n&&await n();let r=new Promise(o=>t.close(()=>o()));t.closeAllConnections(),await r,await bt()||vt(),await e()}export{lo as a,Ct as b,ce as c,gn as d,mn as e,yn as f,vn as g,_n as h,de as i,ue as j,Pt as k,ho as l,kn as m,En as n,Rn as o,Ln as p,Tt as q,Cn as r,Pn as s,Tn as t,It as u,I as v,H as w,he as x,Mn as y,Fn as z,fe as A,Gn as B,De as C,So as D,ko as E,Zn as F,ge as G,me as H,Mt as I,er as J,ye as K,we as L,rr as M,or as N,be as O,$ as P,fr as Q,ve as R,qr as S,Zr as T,ni as U,ri as V};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as Q}from"./chunk-CAR4AEQJ.js";import{f as re,g as U,h as ae,i as ce}from"./chunk-G5VRFFBE.js";import{c as J,f as M,g as X,p as z}from"./chunk-Z3QCHKJB.js";import{a as de,b as C}from"./chunk-L4QBHSVY.js";import{a as D}from"./chunk-4NMMWAKD.js";import{b as Y,c as Z,d as ee,g as ne,j as _,k as x,l as N,m as oe,p as te,q as b,r as se,s as ie}from"./chunk-HPUX2H65.js";import{c as A}from"./chunk-YSFSRI3D.js";A();import{App as j,createClientToken as fe,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Ie,DEFAULT_WHEN_LIVE_TIMEOUT_MS as me,isWakingPhase as Le,SessionFailedError as B}from"@urun-sh/core";A();import{SessionFailedError as he}from"@urun-sh/core";var V=2;function Se(e){let s=e?.type;return s==="response.created"||s==="response.in_progress"}function Pe(e){let s=e?.type;return s==="response.completed"||s==="error"}function le(e){return async function(a,p){let m=await e.sessionFor(a.model);return(async function*(){for(let l=1;l<=V;l++){let{app:w,entry:g,identity:S}=l===1?m:await e.sessionFor(a.model);p?.({sessionId:e.sessionIdOf?.(g)??null,identity:S});let i=!1,d=!1;try{let u=await e.createStream(g,a);for await(let f of u){if(Pe(f)&&(i=!0),Se(f)){if(l>1)continue}else d=!0;yield f}}catch(u){if(u instanceof he&&(u.kind==="never-live"||u.kind==="create-failed")){try{e.onAdmissionVerdict?.(w,g,u)}catch{}throw u}if(l<V&&!d){await e.evict(w,g);continue}throw u}if(i)return;if(l<V&&!d){await e.evict(w,g);continue}return}})()}}import{randomUUID as ge}from"crypto";A();import{encodeStreamEnvelope as Ee}from"@urun-sh/core";var ve="audio";function pe(e){let s=e.streamEndpoint(ve);return{sessionId:e.id,appendInputAudio(a){let p=Buffer.from(a,"base64");p.byteLength!==0&&s.send(Ee(new Uint8Array(p)))},onOutputAudio(){return()=>{}}}}A();import{encodeStreamEnvelope as Ae}from"@urun-sh/core";var Oe="rt-video-in";function ue(e){let s=e.streamEndpoint(Oe);return{sendInputFrame:async a=>{s.send(Ae(a))}}}var _e=0,ke=4,Te=4;function sn(e,s){let a=(l,w)=>{let g=(e[l]??"").trim();if(!g)return w;let S=Number.parseInt(g,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},p=(e.URUN_DECISION_POOL_MIN??"").trim();if(p==="0")return null;let m=p?Number.parseInt(p,10):_e;if(!Number.isInteger(m)||m<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=a("URUN_DECISION_POOL_MAX",Math.max(m,ke));return{min:m,max:c,idleGraceMs:3e4,inFlightCap:a("URUN_DECISION_POOL_INFLIGHT_CAP",Te),replicaId:(e.URUN_REPLICA_ID??"").trim()||s||"proxy"}}function rn(e){let s=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!s)return U;let a=Number.parseInt(s,10);if(!Number.isInteger(a)||a<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return a*1e3}function W(e,s,a,p){let m=e[a];if(typeof m!="function")throw new Error(`app "${s}" has no function "${a}" (set URUN_FUNCTION)`);let c=p?m(void 0,p):m();if(typeof c.end!="function")throw new Error(`app "${s}" function "${a}" returned a session without end()`);return c}function we(e,s,a,p){let{baseUrl:m,orgId:c,auth:l}=e,w=s.fnName??e.fnName,g=e.sessionStartOptions?.(a),S=p||g||s.sharedApp?{...s.sharedApp?{sharedApp:!0}:{},...g,...p}:void 0,i=y=>({session:y,responses:new D(y),gone:de(y,a)});if(l.lane==="jwt"){let y=j(s.appSlug,{baseUrl:m,orgId:c,jwt:l.jwt});return i(W(y,s.appSlug,w,S))}if(l.lane==="machine"){let{machineToken:y,gatewayUrl:F}=l,I=(typeof e.subject=="function"?e.subject():e.subject)??ge(),L=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(y,{baseUrl:F,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:I,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(L,s.appSlug,w,S))}let{apiKey:d,gatewayUrl:u}=l,f=(typeof e.subject=="function"?e.subject():e.subject)??ge(),h=j(s.appSlug,{baseUrl:m,orgId:c,getAccessToken:async()=>(await fe(d,{baseUrl:u,expiresIn:300,allowedFunctions:[`${s.appSlug}/${w}`],subject:f,...s.sharedApp?{sharedApp:!0}:{}})).token});return i(W(h,s.appSlug,w,S))}function ye(e){let s=e.session.id;if(typeof s!="string"||s.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return s}function q(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let s=e.status.error?.httpStatus,a=e.status.error?.code;return s===410||s===409&&(a==="cancelled"||a==="expired")?!0:a==="client_ended"}var Fe=new Set(["error","paused"]);function an(e){let{auth:s,catalog:a}=e,p=null,m=(l,w)=>{let g=we(e,l,w);return e.onSessionOpen&&typeof g.session.id=="string"&&g.session.id!==""&&e.onSessionOpen(w,g.session.id),g.gone.onGone(()=>{p?.evict(w,g)}),g},c=new ie({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:m,closeSession:async l=>{if(l.gone.dispose(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:s.lane==="api-key"?()=>oe({apiUrl:e.apiUrl,apiKey:s.apiKey}):null,listCatalog:e.catalogRows??(a?()=>Q(a):null),listPrices:a?()=>ee(a):null,shared:s.lane==="api-key"?()=>Z({apiUrl:e.apiUrl,apiKey:s.apiKey}):s.lane==="machine"&&e.catalogRows?async()=>{let l=await e.catalogRows();return Y(l)}:null,sessionKey:ye});return p=c,e.defaultApp!==null&&c.seed(e.defaultApp,m({appSlug:e.defaultApp},b({appSlug:e.defaultApp}))),c}function cn(e,s){let a=e.decisionPool;if(!a)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let p=a.replicaId??"proxy",m=new Map,c=new Map,l=new Map,w=i=>{process.stderr.write(`[decision-pool] ${i}
|
|
2
|
+
`)},g=(i,d)=>{let u=m.get(d);if(u)return u;let f=new re({min:a.min,max:a.max,idleGraceMs:a.idleGraceMs,inFlightCap:a.inFlightCap,replicaId:p,openSlot:async h=>{let y=we(e,i,d,{concurrencyKey:h.concurrencyKey});return y.gone.onGone(()=>f.markSessionDead(y)),await T(y.session),w(`slot attached pool=${d} 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=${d} slot=${h.concurrencyKey} reason=${y}`),terminalOpenFailure:h=>h instanceof B&&q(h)});return c.set(d,{target:i,env:a}),m.set(d,f),f},S=async(i,d)=>{let u=c.get(d);if(u)try{let f=await s.poolTuningFor(i);g(i,d).retune({min:f?.min??u.env.min,max:f?.max??u.env.max,inFlightCap:f?.in_flight_cap??u.env.inFlightCap,idleGraceMs:f?.idle_grace_s!==void 0?f.idle_grace_s*1e3:u.env.idleGraceMs,warmWaitMs:f?.warm_wait_s!==void 0?f.warm_wait_s*1e3:void 0})}catch(f){w(`pool tuning refresh failed pool=${d} reason=${f instanceof Error?f.message:String(f)}`)}};return{async boot(){if(e.defaultApp===null)return;let i={appSlug:e.defaultApp};await g(i,b(i)).boot()},async sessionFor(i){let d=await s.resolveTargetFor(i),u=b(d),f=g(d,u);await S(d,u);let h=await f.acquire({timeoutMs:f.requestWaitMs}),y=l.get(h.entry)??[];return y.push(h),l.set(h.entry,y),{app:u,entry:h.entry,identity:se(d)}},async warmFor(i){let d=await s.resolveTargetFor(i);await g(d,b(d)).boot()},end(i){let d=l.get(i)?.shift();d&&(l.get(i)?.length===0&&l.delete(i),d.release())},evict(i){for(let d of m.values())d.evict(i)},markSessionDead(i){for(let d of m.values())d.markSessionDead(i)},reap(){for(let[i,{target:d}]of c)S(d,i).then(()=>{let u=m.get(i);u&&u.reap()})},async pingReady(i){for(let d of m.values())if(await d.pingReady(i))return!0;return!1},stats(){return[...m.entries()].map(([i,d])=>({poolKey:i,...d.stats()}))},async drain(i){await Promise.all([...m.values()].map(d=>d.drain({timeoutMs:i})))},async close(){await Promise.all([...m.values()].map(i=>i.close()))}}}function Re(e){return Le(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?me:Ie:me}async function T(e,s){let a=e.whenLive;if(typeof a!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await a.call(e,{timeout:Re(e.phase),signal:s})}async function G(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 k(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function dn(e,s=X,a,p,m=U,c){let l=new WeakMap,w=new WeakMap,g=new WeakMap,S=new WeakMap,i=new WeakMap,d=n=>{let o=n.session.id;return typeof o=="string"&&o.length>0?o:null},u="lane",f=n=>{let o=N(n);if(!c||!o||o.app!==u)return null;let t=c.entryFor(o.key);if(!t)throw new _(`the lane behind this handle (${o.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:o.key,entry:t}},h=async n=>f(n)?.entry??(await e.sessionForHandle(n)).entry,y=n=>{let o=l.get(n);if(!o){let t={waiting:0,gone:new AbortController};i.set(n,t),o=(async()=>{if(await T(n.session,t.gone.signal),t.gone.signal.aborted)throw k(t.gone.signal);i.get(n)===t&&i.delete(n);let r=await J(n.session,await s());return Object.assign(r,{sessionId:n.session.id})})(),l.set(n,o),o.catch(()=>{l.get(n)===o&&l.delete(n)}),o.then(()=>{i.get(n)===t&&i.delete(n)},()=>{i.get(n)===t&&i.delete(n)})}return o},F=n=>{let o=S.get(n);return o||(o=(async()=>{let t=await y(n);return{appendInputAudio:r=>t.appendInputAudio(r),onOutputAudio:r=>t.onOutputAudio(r),sessionId:d(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=i.get(n);throw(l.get(n)===void 0||E!==void 0&&E.waiting===0)&&await G(n.session),k(t)}let r=o(n),P=i.get(n);return P!==void 0&&P.waiting++,t===void 0?r:new Promise((E,v)=>{let O=()=>{P!==void 0&&--P.waiting===0&&i.get(n)===P&&(P.gone.abort(),i.delete(n),l.delete(n),S.delete(n),G(n.session).catch(()=>{})),v(k(t))};t.addEventListener("abort",O,{once:!0});let K=()=>t.removeEventListener("abort",O);r.then(R=>{K(),E(R)},R=>{K(),v(R)})})},L=async(n,o,t)=>{try{return await t}catch(r){throw(r instanceof _||r instanceof B&&q(r))&&(e.evict(n,o),r instanceof B&&a?.(n,r.kind==="never-live"?"never-live":"create-failed")),r}};return{createResponse:le({sessionFor:c?async n=>{let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await c.sessionFor(n,o);return{app:t.app,entry:t.entry,identity:t.identity}}return p?p.sessionFor(n):e.sessionFor(n)}:p?n=>p.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>d(n),evict:(n,o)=>{c&&c.owns(o)?c.evict(o):p?p.evict(o):e.evict(n,o)},onAdmissionVerdict:(n,o,t)=>{q(t)&&(c&&c.owns(o)?c.evict(o):p?p.markSessionDead(o):e.evict(n,o),a?.(n,t.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,o)=>{try{await T(n.session);let t=ae(C(await n.responses.responses.create(o),n.gone),m);if(!p&&!c)return t;let r=n;return(async function*(){try{yield*t}catch(E){throw ce(E)&&(c&&c.owns(r)?c.evict(r):p&&(E instanceof _?p.markSessionDead(r):p.evict(r))),E}finally{c&&c.owns(r)?c.release(r):p?.end(r)}})()}catch(t){throw c&&c.owns(n)?c.release(n):p&&p.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{app:t,entry:r}=await e.sessionFor(n);return await L(t,r,I(r,y,o))},openAudioOn:async(n,o,t)=>{let r=f(n);if(r){let v=r.entry.session;return pe(v)}let{app:P,entry:E}=await e.sessionForHandle(n);return await L(P,E,I(E,F,o))},openTurnsOn:async function*(n,o){if(o?.aborted)throw k(o);let t=await h(n);yield*ne(t.session,o)},openVideoOn:async n=>{let o=f(n);if(o)return ue(o.entry.session);let{entry:t}=await e.sessionForHandle(n),r=w.get(t);return r||(r=M(t.session),w.set(t,r)),r},openVideo:async n=>{let{entry:o}=await e.sessionFor(n),t=w.get(o);return t||(t=M(o.session),w.set(o,t)),t},openVideoOut:async n=>{let{entry:o}=await e.sessionFor(n),t=g.get(o);return t||(t=z(o.session),g.set(o,t)),t},sessionHandle:async n=>{if(c){let o=await e.resolveTargetFor(n);if(o.sharedApp){let t=await c.sessionFor(n,o),r=d(t.entry);if(r===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return x(u,r)}}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:r}=await e.dedicatedSessionFor(n);return x(t,ye(r))},releaseSessionHandle:n=>{let o=N(n);if(!o)return;if(o.app.startsWith(te)){(async()=>{let r=null;try{r=(await e.sessionForHandle(n)).entry}catch{return}await G(r.session).catch(()=>{}),await e.evict(o.app,r)})();return}if(!c||o.app!==u)return;let t=c.entryFor(o.key);t&&c.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 r=await h(n);await T(r.session);let P=t!==void 0&&f(n)?new D({...r.session,consumerId:t},{sessionTag:t}):r.responses;return C(await P.responses.create(o),r.gone)},onSessionEnd:async(n,o)=>{let t=f(n);if(t)return t.entry.gone.onGone(v=>o({timeLeftMs:null,reason:v.message}));let{entry:r}=await e.sessionForHandle(n),P=r.session;if(typeof P.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return P.onPhase(v=>{if(E||!Fe.has(v.name))return;E=!0;let O=P.endsAt??null;o({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:v.reason??`session ${v.name}`})})}}}export{sn as a,rn as b,an as c,cn as d,dn as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as I,o as A}from"./chunk-
|
|
1
|
+
import{a as I,o as A}from"./chunk-Z3QCHKJB.js";import{c as v}from"./chunk-YSFSRI3D.js";v();var J="/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",k=1007,F=1008,R=1011,V=1008,n=class extends Error{constructor(o,i=k){super(o);this.closeCode=i}closeCode},d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,w=["setup","clientContent","realtimeInput","toolResponse"];function B(e){let t;try{t=JSON.parse(e)}catch{throw new n("client message is not valid JSON")}let o=d(t);if(!o)throw new n("client message must be a JSON object");let i=w.filter(c=>o[c]!==void 0),s=Object.keys(o).filter(c=>!w.includes(c));if(s.length>0)throw new n(`unknown client message field(s) ${JSON.stringify(s)} \u2014 expected exactly one of ${w.join(", ")}`);if(i.length!==1)throw new n(`client message must contain exactly one of ${w.join(", ")} (got ${i.length})`);let r=i[0],a=d(o[r]);if(!a)throw new n(`"${r}" must be a JSON object`);return{kind:r,[r]:a}}function C(e,t){if(typeof e=="string")return e;let o=d(e),i=o?o.parts:void 0;if(!Array.isArray(i))throw new n(`${t}: expected a Content with a parts array`);let s=[];for(let r of i){let a=d(r);if(a&&typeof a.text=="string"){s.push(a.text);continue}throw a&&(a.inlineData!==void 0||a.fileData!==void 0)?new n(`${t}: media parts (inlineData/fileData) are a declared follow-up slice (audio/video lanes over the proxy transport AudioBridge) \u2014 only text parts are supported in this slice`):a&&(a.functionCall!==void 0||a.functionResponse!==void 0)?new n(`${t}: functionCall/functionResponse parts are not valid here \u2014 the Live API exchanges tool traffic via the dedicated toolCall/toolResponse messages`):new n(`${t}: unsupported part ${JSON.stringify(r)}`)}return s.join(`
|
|
2
2
|
`)}var _={manualActivity:!1,activityHandling:"START_OF_ACTIVITY_INTERRUPTS"},h="urun.videoOut";function G(e){return{framing:A,codec:e}}function Y(e){let{seq:t,ptsUs:o,codec:i,key:s}=e.header;return{[h]:{v:1,seq:t,ptsUs:o,codec:i,key:s,data:Buffer.from(e.au).toString("base64")}}}var x={inputAudioTranscription:"setup.inputAudioTranscription is part of the declared audio follow-up slice",outputAudioTranscription:"setup.outputAudioTranscription is part of the declared audio follow-up slice"},S=["model","generationConfig","systemInstruction","tools","realtimeInputConfig","sessionResumption",h],T=["START_OF_ACTIVITY_INTERRUPTS","NO_INTERRUPTION"];function E(e){let t=d(e);if(!t)throw new n("setup.realtimeInputConfig must be an object");for(let s of Object.keys(t))if(!(s==="automaticActivityDetection"||s==="activityHandling"))throw new n(s==="turnCoverage"?"realtimeInputConfig.turnCoverage is part of the declared audio follow-up slice":`unsupported realtimeInputConfig field "${s}"`);let o=d(t.automaticActivityDetection);if(t.automaticActivityDetection!==void 0&&!o)throw new n("realtimeInputConfig.automaticActivityDetection must be an object");for(let s of Object.keys(o??{}))if(s!=="disabled")throw new n(`automaticActivityDetection.${s} tunes AUTOMATIC (server-side) activity detection \u2014 the declared platform follow-up (serve turn_detection events over the session stream lane); only "disabled: true" (manual activity mode) is supported in this slice`);if(o?.disabled!==!0)throw new n("automatic (server-side) activity detection is the declared platform follow-up (serve turn_detection turn_start/turn_end events over the session stream lane, not proxy DSP) \u2014 set realtimeInputConfig.automaticActivityDetection.disabled: true for manual activity mode");let i="START_OF_ACTIVITY_INTERRUPTS";if(t.activityHandling!==void 0){if(!T.includes(t.activityHandling))throw new n(`unsupported activityHandling ${JSON.stringify(t.activityHandling)} \u2014 expected one of ${T.join(", ")}`);i=t.activityHandling}return{manualActivity:!0,activityHandling:i}}var N=["temperature","maxOutputTokens","responseModalities"];function K(e){for(let[u,f]of Object.entries(x))if(e[u]!==void 0)throw new n(f);for(let u of Object.keys(e))if(!S.includes(u))throw new n(`unsupported setup field "${u}"`);if(typeof e.model!="string"||e.model.length===0)throw new n('setup.model is required (format "models/{model}")');let t=e.model.replace(/^models\//,""),o,i,s=!1,r=d(e.generationConfig);if(e.generationConfig!==void 0&&!r)throw new n("setup.generationConfig must be an object");if(r){for(let u of Object.keys(r))if(!N.includes(u))throw new n(`unsupported generationConfig field "${u}"`);if(r.temperature!==void 0){if(typeof r.temperature!="number")throw new n("generationConfig.temperature must be a number");o=r.temperature}if(r.maxOutputTokens!==void 0){if(typeof r.maxOutputTokens!="number")throw new n("generationConfig.maxOutputTokens must be a number");i=r.maxOutputTokens}if(r.responseModalities!==void 0){let u=Array.isArray(r.responseModalities)?r.responseModalities:[r.responseModalities];for(let f of u){let y=String(f).toUpperCase();if(y==="AUDIO"){s=!0;continue}if(y!=="TEXT")throw new n(`responseModalities ${JSON.stringify(f)} is not supported \u2014 this surface speaks TEXT and AUDIO (audio-out rides the native AudioBridge 'audio' lane)`)}}}let a=[];e.systemInstruction!==void 0&&a.push({role:"system",content:C(e.systemInstruction,"setup.systemInstruction")});let c;if(e.tools!==void 0){if(!Array.isArray(e.tools))throw new n("setup.tools must be an array");c=[];for(let u of e.tools){let f=d(u);if(!f)throw new n("setup.tools entries must be objects");for(let y of Object.keys(f))if(y!=="functionDeclarations")throw new n(`unsupported tool "${y}" \u2014 this slice translates functionDeclarations only (no googleSearch/codeExecution)`);if(!Array.isArray(f.functionDeclarations))throw new n("tool.functionDeclarations must be an array");for(let y of f.functionDeclarations){let g=d(y);if(!g||typeof g.name!="string")throw new n("functionDeclarations entries require a string name");c.push({type:"function",name:g.name,description:g.description,parameters:g.parameters})}}c.length===0&&(c=void 0)}let m={enabled:!1,handle:null};if(e.sessionResumption!==void 0){let u=d(e.sessionResumption);if(!u)throw new n("setup.sessionResumption must be an object (SessionResumptionConfig)");for(let f of Object.keys(u))if(f!=="handle")throw new n(`unsupported sessionResumption field "${f}" \u2014 this lane implements SessionResumptionConfig.handle only`);if(u.handle!==void 0&&(typeof u.handle!="string"||u.handle.length===0))throw new n("sessionResumption.handle must be a non-empty string when present");m={enabled:!0,handle:typeof u.handle=="string"?u.handle:null}}let p=e.realtimeInputConfig===void 0?_:E(e.realtimeInputConfig),l=!1;if(e[h]!==void 0){if(!d(e[h]))throw new n(`setup["${h}"] must be an object (the v1 opt-in is {})`);l=!0}return{model:t,systemItems:a,tools:c,temperature:o,maxOutputTokens:i,audioModality:s,activity:p,sessionResumption:m,videoOut:l}}function q(e){return{sessionResumptionUpdate:{newHandle:e,resumable:!0}}}function W(e){let t=Math.max(0,e??0)/1e3;return{goAway:{timeLeft:`${Math.round(t*1e3)/1e3}s`}}}function X(e){for(let i of Object.keys(e))if(i!=="turns"&&i!=="turnComplete")throw new n(`unsupported clientContent field "${i}"`);let t=e.turns===void 0?[]:e.turns;if(!Array.isArray(t))throw new n("clientContent.turns must be an array");let o=[];for(let i of t){let s=d(i);if(!s)throw new n("clientContent.turns entries must be Content objects");let r=s.role===void 0?"user":String(s.role).toLowerCase();if(r!=="user"&&r!=="model")throw new n(`clientContent turn role must be "user" or "model" (got ${JSON.stringify(s.role)})`);o.push({role:r==="model"?"assistant":"user",content:C(s,"clientContent.turns")})}return{items:o,turnComplete:e.turnComplete===!0}}var b=16e3,O=24e3,$=`audio/pcm;rate=${O}`,z=Buffer.alloc(960).toString("base64");function j(e,t,o){if(t===o)return e;let i=Math.floor(e.length*o/t),s=new Int16Array(i),r=t/o,a=e.length-1;for(let c=0;c<i;c++){let m=c*r,p=Math.floor(m);if(p>=a){s[c]=e[a];continue}let l=m-p;s[c]=Math.round(e[p]+(e[p+1]-e[p])*l)}return s}function U(e){let t=d(e);if(!t)throw new n("realtimeInput.video must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^image\/jpeg\s*(;|$)/.test(t.mimeType))throw new n(`realtimeInput.video.mimeType must be image/jpeg (the Live video input stream is individual JPEG frames), got ${JSON.stringify(t.mimeType)}`);if(typeof t.data!="string"||t.data.length===0)throw new n("realtimeInput.video.data must be non-empty base64");let o=Buffer.from(t.data,"base64");if(o.length<3||o[0]!==255||o[1]!==216)throw new n("realtimeInput.video.data does not decode to a JPEG frame (missing FF D8 SOI marker)");return new Uint8Array(o)}function D(e){let t=d(e);if(!t)throw new n("realtimeInput.audio must be a Blob object {mimeType, data}");if(typeof t.mimeType!="string"||!/^audio\/pcm\s*(;|$)/.test(t.mimeType))throw new n(`realtimeInput.audio.mimeType must be audio/pcm (16-bit LE PCM @16kHz mono per the Live spec), got ${JSON.stringify(t.mimeType)}`);let o=/;\s*rate=(\d+)/.exec(t.mimeType);if(o&&Number(o[1])!==b)throw new n(`realtimeInput.audio.mimeType declares rate=${o[1]} \u2014 the Live spec input format is ${b} Hz (audio/pcm;rate=${b})`);if(typeof t.data!="string"||t.data.length===0)throw new n("realtimeInput.audio.data must be non-empty base64");let i=Buffer.from(t.data,"base64");if(i.length===0||i.length%2!==0)throw new n(`realtimeInput.audio.data must decode to whole 16-bit samples (got ${i.length} bytes \u2014 not even)`);let s=new Int16Array(i.length/2);for(let a=0;a<s.length;a++)s[a]=i.readInt16LE(a*2);let r=j(s,b,O);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}function Q(e){if(e.mediaChunks!==void 0)throw new n('realtimeInput.mediaChunks is deprecated by the Live API \u2014 send the audio stream via realtimeInput.audio ({mimeType:"audio/pcm;rate=16000", data}) instead');if(e.activityStart!==void 0||e.activityEnd!==void 0){if(Object.keys(e).length!==1||e.activityStart!==void 0&&e.activityEnd!==void 0)throw new n("realtimeInput must carry exactly one field when signaling activity (activityStart XOR activityEnd, nothing else)");let s=e.activityStart!==void 0?"activityStart":"activityEnd",r=d(e[s]);if(!r||Object.keys(r).length!==0)throw new n(`realtimeInput.${s} must be an empty object (ActivityStart/ActivityEnd are bare markers)`);return{kind:s}}let t=["text","audio","audioStreamEnd","video"];for(let i of Object.keys(e))if(!t.includes(i))throw new n(`unsupported realtimeInput field "${i}"`);let o=t.filter(i=>e[i]!==void 0);if(o.length!==1)throw new n(`realtimeInput must carry exactly one of ${t.join(", ")} (got ${o.length})`);if(e.audio!==void 0)return{kind:"audio",base64Pcm24k:D(e.audio)};if(e.video!==void 0)return{kind:"video",jpegFrame:U(e.video)};if(e.audioStreamEnd!==void 0){if(e.audioStreamEnd!==!0)throw new n("realtimeInput.audioStreamEnd must be true when present");return{kind:"audioStreamEnd"}}if(typeof e.text!="string"||e.text.length===0)throw new n("realtimeInput.text must be a non-empty string");return{kind:"text",text:e.text}}function Z(e){for(let t of Object.keys(e))if(t!=="functionResponses")throw new n(`unsupported toolResponse field "${t}"`);if(!Array.isArray(e.functionResponses)||e.functionResponses.length===0)throw new n("toolResponse.functionResponses must be a non-empty array");return e.functionResponses.map(t=>{let o=d(t);if(!o||typeof o.id!="string"||o.id.length===0)throw new n("functionResponses entries require the string id matched from the toolCall");return{type:"function_call_output",call_id:o.id,output:JSON.stringify(o.response??null)}})}function ee(e){return e.type!=="response.output_text.delta"||typeof e.delta!="string"?null:{serverContent:{modelTurn:{role:"model",parts:[{text:e.delta}]}}}}function te(e){return{serverContent:{modelTurn:{role:"model",parts:[{inlineData:{mimeType:$,data:e}}]}}}}function ne(e){let t=d(e)??{},o=Array.isArray(t.output)?t.output:[],i=[],s=[],r=typeof t.output_text=="string"?t.output_text:"";if(!r)for(let p of o){let l=d(p);if(!(l?.type!=="message"||!Array.isArray(l.content)))for(let u of l.content){let f=d(u);f?.type==="output_text"&&typeof f.text=="string"&&(r+=f.text)}}r&&s.push({role:"assistant",content:r});for(let p of o){let l=d(p);if(l?.type!=="function_call")continue;if(typeof l.call_id!="string"||typeof l.name!="string")throw new n(`upstream function_call item is missing call_id/name: ${JSON.stringify(p)}`,R);let u=typeof l.arguments=="string"&&l.arguments.length>0?l.arguments:"{}",f;try{f=JSON.parse(u)}catch{throw new n(`upstream function_call arguments are not valid JSON: ${u}`,R)}i.push({id:l.call_id,name:l.name,args:f}),s.push({type:"function_call",call_id:l.call_id,name:l.name,arguments:u})}let a=[];i.length>0&&a.push({toolCall:{functionCalls:i}}),a.push({serverContent:{generationComplete:!0}});let c=d(t.usage),m={serverContent:{turnComplete:!0}};if(c){let p={};typeof c.input_tokens=="number"&&(p.promptTokenCount=c.input_tokens),typeof c.output_tokens=="number"&&(p.responseTokenCount=c.output_tokens),typeof c.total_tokens=="number"&&(p.totalTokenCount=c.total_tokens),Object.keys(p).length>0&&(m.usageMetadata=p)}return a.push(m),{messages:a,assistantItems:s}}export{J as a,k as b,F as c,R as d,V as e,n as f,B as g,h,G as i,Y as j,K as k,q as l,W as m,X as n,b as o,O as p,$ as q,z as r,j as s,Q as t,Z as u,ee as v,te as w,ne as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as m}from"./chunk-YSFSRI3D.js";m();var W=24e3,g="audio",w=class{constructor(t,r){this.backend=t;this.opts=r}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(t){this.dataEmit=t}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(t){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(t,"base64"),n=Math.floor(r.byteLength/2),i=new Int16Array(n);for(let a=0;a<n;a++)i[a]=r.readInt16LE(a*2);this.source.onData(i),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(a=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(a instanceof Error?a.message:String(a)))}))}async startInbound(t){if(t==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(t),this.sink.onframe=r=>{let n=Buffer.from(r.samples.buffer,r.samples.byteOffset,r.samples.byteLength).toString("base64");for(let i of this.outHandlers)i(n)}}onOutputAudio(t){return this.outHandlers.add(t),()=>this.outHandlers.delete(t)}};async function F(e,t,r=1e4){let n=new w(t,{sampleRate:24e3}),i=await n.startOutbound(),a=e.stream(g);await a.attach(i),typeof a.emit=="function"&&n.setDataEmit(u=>a.emit(u));let d=await T(e,r);return await n.startInbound(d),n}function T(e,t){let r=e.stream(g);return r.track!=null?Promise.resolve(r.track):new Promise((n,i)=>{let a,d=setTimeout(()=>{a?.(),i(new Error(`enableSessionAudio: no downstream audio track within ${t}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},t),u=o=>{o!=null&&(clearTimeout(d),a?.(),n(o))};a=r.on?.("track",u),r.track!=null&&u(r.track)})}var h="rt-video-in",y=256e3;function H(e){let t=e.stream(h),r=t.emit;if(typeof r!="function")throw new Error(`enableSessionVideo: session.stream('${h}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async n=>{if(n.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(n.byteLength>y)throw new Error(`enableSessionVideo: frame is ${n.byteLength} bytes \u2014 over the ${y}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await r.call(t,n)}}}var V=24e3,l=480,I=111;async function L(){let e=await import("opusscript"),t=e.default??e;return new t(V,1,2048)}async function $(){let e=await import("werift"),t=await L();return{createSource:()=>{let r=new e.MediaStreamTrack({kind:"audio"}),n=Math.random()*4294967295>>>0,i=Math.random()*65535&65535,a=Math.random()*4294967295>>>0,d=new Int16Array(0);return{track:r,onData:u=>{let o=new Int16Array(d.length+u.length);o.set(d,0),o.set(u,d.length);let s=0;for(;o.length-s>=l;){let c=o.subarray(s,s+l);s+=l;let f=Buffer.from(c.buffer,c.byteOffset,c.byteLength),v=t.encode(f,l);i=i+1&65535,a=a+l>>>0;let O=new e.RtpHeader({version:2,payloadType:I,sequenceNumber:i,timestamp:a,ssrc:n,marker:!1}),S=new e.RtpPacket(O,v);r.writeRtp(S)}d=o.slice(s)}}},createSink:r=>{let n={onframe:null};return r.onReceiveRtp.subscribe(a=>{let d;try{d=t.decode(a.payload)}catch{return}let u=new Int16Array(d.length/2);for(let o=0;o<u.length;o++)u[o]=d.readInt16LE(o*2);n.onframe?.({samples:u})}),n}}}async function N(){let e=await import("@roamhq/wrtc");return{createSource:()=>{let t=new e.nonstandard.RTCAudioSource;return{track:t.createTrack(),onData:n=>t.onData({samples:n,sampleRate:24e3})}},createSink:t=>{let r={onframe:null},n=new e.nonstandard.RTCAudioSink(t);return n.ondata=i=>{r.onframe?.(i)},r}}}m();import{WtControlDecoder as U,consumeWtDataStreams as _,encodeWtControlFrame as D,STREAM_END as P}from"@urun-sh/core";var p="rt-video-out",x="urun.videoOut.v1",b="h264";function k(e,t){if(!Number.isInteger(e.seq)||e.seq<0)throw new Error(`${t}: header seq must be a non-negative integer (got ${e.seq})`);if(!Number.isInteger(e.ptsUs))throw new Error(`${t}: header ptsUs must be an integer microsecond timestamp (got ${e.ptsUs})`);if(typeof e.codec!="string"||e.codec.length===0)throw new Error(`${t}: header codec must be a non-empty string`);if(typeof e.key!="boolean")throw new Error(`${t}: header key must be a boolean`)}function J(e,t){if(k(e,"encodeVideoOutRecord"),t.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let r=new TextEncoder().encode(JSON.stringify({v:1,seq:e.seq,ptsUs:e.ptsUs,codec:e.codec,key:e.key}));if(r.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${r.byteLength} bytes \u2014 over the u16 length prefix`);let n=new Uint8Array(2+r.byteLength+t.byteLength);return n[0]=r.byteLength&255,n[1]=r.byteLength>>8,n.set(r,2),n.set(t,2+r.byteLength),n}function E(e){if(e.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${e.byteLength} byte(s), no header length)`);let t=e[0]|e[1]<<8;if(e.byteLength<2+t)throw new Error(`decodeVideoOutRecord: truncated record (header says ${t} bytes, ${e.byteLength-2} present)`);let r;try{r=JSON.parse(new TextDecoder().decode(e.subarray(2,2+t)))}catch(d){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(d)})`)}let n=r;if(n===null||typeof n!="object"||n.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(n?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let i=n;k(i,"decodeVideoOutRecord");let a=e.subarray(2+t);if(a.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:i,au:a.slice()}}async function Y(e){let t=e.wtDataEndpoint;if(typeof t!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let r=await t.call(e),n=r.sessionId??e.sessionId;if(typeof n!="string"||n.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:r.url,certHashes:r.certHashes,token:r.token,sessionId:n,stream:p,codec:b,framing:x}}var G="urun.videoOut.v2-ws";function Q(e){let t=e.stream(p);if(typeof t.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${p}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let r=new Set,n=new Set,i=new Set,a=o=>{for(let s of n)s(o)},d=!1,u=async()=>{for await(let o of t.messages()){if(!(o instanceof Uint8Array)){a(new Error(`openSessionVideoOutLane: "${p}" delivered a non-BINARY \xA75 payload (${typeof o}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let s;try{s=E(o)}catch(c){a(c instanceof Error?c:new Error(String(c)));continue}for(let c of r)c(s)}for(let o of i)o()};return{codec:b,onOutputFrame:o=>(r.add(o),d||(d=!0,u().catch(s=>a(s instanceof Error?s:new Error(String(s))))),()=>r.delete(o)),onLaneError:o=>(n.add(o),()=>n.delete(o)),onEnd:o=>(i.add(o),()=>i.delete(o))}}function B(e){if(e.length%2!==0||/[^0-9a-fA-F]/.test(e))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(e)})`);let t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}async function j(e,t,r){let n=r??(typeof globalThis.WebTransport=="function"?(s,c)=>new globalThis.WebTransport(s,c):void 0);if(!n)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let i=n(e.url,{serverCertificateHashes:e.certHashes.map(s=>({algorithm:"sha-256",value:B(s)}))});await i.ready;let a=await i.createBidirectionalStream();await a.writable.getWriter().write(D({t:"hello",token:e.token,sessionId:e.sessionId}));let d=a.readable.getReader(),u=new U,o=!1;for(;!o;){let{value:s,done:c}=await d.read();if(c)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(s)for(let f of u.push(s)){if(f.t==="hello-ack"){o=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(f.t)} before hello-ack)`)}}await _(i.incomingUnidirectionalStreams,{onData:(s,c)=>{if(s===e.stream){if(c===P){t.onEnd?.();return}if(!(c instanceof Uint8Array)){t.onLaneError(new Error(`consumeVideoOut: "${e.stream}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{t.onFrame(E(c))}catch(f){t.onLaneError(f instanceof Error?f:new Error(String(f)))}}},onLaneError:s=>t.onLaneError(s)})}export{W as a,w as b,F as c,h as d,y as e,H as f,$ as g,N as h,p as i,x as j,b as k,J as l,E as m,Y as n,G as o,Q as p,j as q};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as CatalogRow } from './models-D7F0bLJ3.js';
|
|
2
2
|
import { IncomingMessage } from 'node:http';
|
|
3
|
-
import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-
|
|
3
|
+
import { a as AudioBridge, h as VideoFrameLane, j as VideoOutLane } from './video-out-REmiQMBJ.js';
|
|
4
4
|
|
|
5
5
|
type TurnCatalogIdentity = {
|
|
6
6
|
kind: 'catalog';
|
|
@@ -249,6 +249,8 @@ declare class ModelRouter<S> {
|
|
|
249
249
|
private readonly opts;
|
|
250
250
|
private readonly pool;
|
|
251
251
|
|
|
252
|
+
private readonly mintedIds;
|
|
253
|
+
|
|
252
254
|
private apps;
|
|
253
255
|
private rows;
|
|
254
256
|
private shared;
|
|
@@ -257,6 +259,8 @@ declare class ModelRouter<S> {
|
|
|
257
259
|
private swr;
|
|
258
260
|
|
|
259
261
|
seed(appSlug: string, entry: S): void;
|
|
262
|
+
|
|
263
|
+
private snapshotMintId;
|
|
260
264
|
private deployedApps;
|
|
261
265
|
|
|
262
266
|
private sharedBlock;
|
|
@@ -598,6 +602,8 @@ interface ProxyClients {
|
|
|
598
602
|
|
|
599
603
|
openAudioOn?(handle: string, signal?: AbortSignal, connectionTag?: string): Promise<PinnedAudioLane>;
|
|
600
604
|
|
|
605
|
+
openVideoOn?(handle: string, signal?: AbortSignal): Promise<ProxyVideoLane>;
|
|
606
|
+
|
|
601
607
|
openTurnsOn?(handle: string, signal?: AbortSignal): AsyncIterable<SessionTurnLaneEvent>;
|
|
602
608
|
|
|
603
609
|
transcriptStreamFor?(model: string | undefined): Promise<string>;
|
|
@@ -673,4 +679,4 @@ interface RealtimeCompanions {
|
|
|
673
679
|
|
|
674
680
|
type RealtimeCompanionsFor = (model: string | undefined) => Promise<RealtimeCompanions | null>;
|
|
675
681
|
|
|
676
|
-
export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type
|
|
682
|
+
export { type DialObserver as D, type InferenceRecord as I, type LedgerFailure as L, ModelRouter as M, type ProxyClients as P, type RealtimeCompanionsFor as R, SessionGoneError as S, UnknownModelError as U, type DialReport as a, type InferenceUsageRecord as b, type LedgerOutcome as c, type LedgerRecorded as d, type LedgerWrite as e, type ProxyHandlerOptions as f, type ProxyIdentity as g, type ProxyVideoLane as h, type ProxyVideoOutLane as i, type RouteTarget as j, type UsageRowReporter as k, billingIdentityOf as l };
|