@urun-sh/openai 0.6.56 → 0.6.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-B3GQYAJ5.js → chunk-2VZR5MAX.js} +1 -1
- package/dist/{chunk-N3Y2GDQK.js → chunk-4GW343S5.js} +1 -1
- package/dist/{chunk-KNWFUWXY.js → chunk-EA3GQ2MM.js} +1 -1
- package/dist/{chunk-NMNR3SQ5.js → chunk-HIM6EB3J.js} +1 -1
- package/dist/{chunk-6R3TCKOH.js → chunk-O3Z5AY5E.js} +1 -1
- package/dist/{chunk-MBIJRS4O.js → chunk-RONITPWW.js} +1 -1
- package/dist/{chunk-WXO7IIRV.js → chunk-SNCDIY53.js} +1 -1
- package/dist/{composite-CIOofxp2.d.cts → composite-4JhDPmCP.d.cts} +1 -1
- package/dist/{composite-lokLYIya.d.ts → composite-BjRgfMOX.d.ts} +1 -1
- package/dist/hosted/bin.cjs +1 -1
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +1 -1
- package/dist/hosted/index.d.cts +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +2 -2
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.d.cts +2 -2
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as v}from"./chunk-
|
|
1
|
+
import{c as v}from"./chunk-O3Z5AY5E.js";import{c as D}from"./chunk-YSFSRI3D.js";D();import{createClientToken as H}from"@urun-sh/core";import{Queue as I}from"bullmq";import{randomUUID as V}from"crypto";var O=3e4;var q=1e3,X=12e4;function T(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var M=class extends Error{};async function $(n,s){let t;try{await Promise.race([n,new Promise(l=>{t=setTimeout(l,Math.max(0,s))})])}finally{clearTimeout(t)}}function Y(n){let s=n.now??Date.now,t=new Map,l=new Map,h=new Map,u=new Map,g=new Map,_=new Map,b=new Map,L=new Set,k=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??x(e),t.set(e,a)),a},x=e=>{let a=n.redis,c=new I(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let i=(await c.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,o)=>r.timestamp-o.timestamp);if(i.length===0)return{found:0};for(let r of i)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of i.slice(1))try{await r.remove()}catch{}return{found:i.length}},close:()=>c.close()}},E=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),c=[],p=new Map;for(let[r,o]of Object.entries(a)){let d=T(o);d&&d.proxy_url===n.docHostUrl&&(c.push(r),p.set(r,d.region))}if(c.length===0)return[];let y=await n.redis.mget(...c.map(r=>`lane_hosts:${r}`)),i=[];return c.forEach((r,o)=>{let d=y[o];d&&i.push({laneId:r,host:d,region:p.get(r)})}),i},S=async(e,a,c,p,y,i)=>{let r=c,o=p,d=y;if(typeof r!="string"||r===""||typeof o!="string"||o===""){let C=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(C)r=C.app,o=C.fn,d=C.sharedApp??d;else{let F=h.get(e)??0;if(s()-F<O)return;throw h.set(e,s()),new M("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let m=l.get(e)??0,w=s();if(w-m<O)return;if(l.set(e,w),(await k(e).reassertWaiting(s()).catch(C=>{throw l.delete(e),C})).found>0){g.set(a??"",(g.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let A=`lane-${V().replaceAll("-","")}`,P=await n.admission.createLaneSession({pool:e,app:r,fn:o,...d?{sharedApp:!0}:{},...i?{requestorOrgId:i}:{},laneId:A,laneHostUrl:n.docHostUrl});if(P.sessionId!==A)throw new Error(`session-api lane admission returned session_id "${P.sessionId}" for requested logical_id "${A}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:c,sharedApp:p,requestorOrgId:y,model:i,holdMs:r=0}){if(L.add(e),n.targets!==void 0&&i!==void 0&&!n.targets.some(f=>f.model===i)){let f=`no pooler target for ${i} \u2014 refusing to mint a lane demand`;throw _.set("untargeted",(_.get("untargeted")??0)+1),b.set(e,f),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:i,reason:f}),new v(e,i)}let o=async f=>{try{await S(e,i,a,c,p,f)}catch(R){let A=R instanceof Error?R.message:String(R),P=R instanceof M?"identity":"admission";_.set(P,(_.get(P)??0)+1),b.set(e,A),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:i,reason:A})}},d=async()=>{try{return await E(e)}catch{return[]}},m=await d();if(m.length>0){let f=n.laneMinFor?.(e)??0;return f>m.length&&(async()=>{for(let R=m.length;R<f;R++)await o(void 0)})(),m}let w=s()+r;for(await $(o(y),r);s()<w;){if(await new Promise(f=>setTimeout(f,q)),m=await d(),m.length>0)return m;await $(o(y),w-s())}return[]},async status(){let e=[...L].sort();return Promise.all(e.map(async a=>{let c=[];try{let p=await n.redis.hgetall(`lanes:${a}`),y=Object.keys(p),i=y.length===0?[]:await n.redis.mget(...y.map(o=>`lane_hosts:${o}`)),r=s();c=y.map((o,d)=>{let m=p[o],w=m===void 0?null:T(m);return{laneId:o,occupantId:w?.occupant_id??"",capacity:w?.capacity??0,heartbeatAgeMs:w===null?null:r-w.heartbeat_ms,advertisedHere:w?.proxy_url===n.docHostUrl,hosted:!!i[d]}})}catch{}return{pool:a,lanes:c,lastDemandAt:l.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),...g.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:g.get(a)??0}))},demandRefusals(){return[..._.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var j=4e3,Q=5e3;function J(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(j)})}function Z(n){return{createLaneSession:async({pool:s,app:t,fn:l,sharedApp:h,requestorOrgId:u,laneId:g,laneHostUrl:_})=>{let b=await H(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${l}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:J(n.fetch??globalThis.fetch)}),L=n.fetch??globalThis.fetch,k;try{k=await L(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(Q),headers:{"content-type":"application/json",authorization:`Bearer ${b.token}`,"x-tenant-id":b.orgId},body:JSON.stringify({app:t,function:l,...h?{shared_app:!0}:{},...h&&u?{requestor_org_id:u}:{},logical_id:g,idempotency_key:g,concurrency_key:g,lane_host_url:_})})}catch(S){throw new Error(`session-api lane admission for ${g} (app ${t}/${l}) failed: ${S instanceof Error?S.message:String(S)}`)}let x={};try{x=await k.json()}catch{}let E=x.session_id;if(k.status!==200||x.status!=="allocated"||typeof E!="string"){let S=typeof x.message=="string"?x.message:`HTTP ${k.status}`;throw new Error(`session-api lane admission refused for ${g} (app ${t}/${l}): ${S}`)}return{sessionId:E}}}}D();var K="urun:catalog:v1";function te(n){let s=n.refreshMs??5e3,t=n.now??Date.now,l=null,h=0,u=null,g=async()=>{let b=await n.redis.hgetall(K),L=[];for(let k of Object.values(b))try{L.push(JSON.parse(k))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
2
2
|
`)}return l=L,h=t(),L},_=()=>l===null||t()-h>=s;return{rows(){return _()?(u||(u=g().finally(()=>{u=null})),u):Promise.resolve(l)},close(){l=null,u=null}}}export{X as a,Y as b,Z as c,K as d,te as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as w}from"./chunk-YSFSRI3D.js";w();import{randomUUID as Ke}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",X="model_id,variant,unit,price_usd,effective_at,expires_at",Q={per_request:!0,per_minute:!0,per_output_unit:!0},Se=5e3;function Te(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 Z(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 $e(n,e,t){return n===null?null:Z(n,e,t)}function ke(n,e){if(n===j)return"input";if(n===U)return"output";if(typeof n=="string"&&Object.hasOwn(Q,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(Q).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 X.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:Te(i.price_usd,r),effective_at:Z(i.effective_at,r,"effective_at"),expires_at:$e(i.expires_at,r,"expires_at")})}return e}function ee(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 I(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 O={prices:[],refusals:[]};async function rt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${X}&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},te={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ie(n){let e=n.toLowerCase();return Object.hasOwn(te,e)?te[e]:null}var ne={"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 Oe(n,e){if(!n||n.length===0)return[];let t=[],o=[];for(let r of n){let i=Object.hasOwn(ne,r)?ne[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 re={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},oe={2:"Llama2",3:"Llama3"};function Ee(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(re,i))return re[i];let s=o[r+1];if(i==="llama"&&s!==void 0&&Object.hasOwn(oe,s))return oe[s];if(i==="phi"&&s!==void 0&&/^\d/.test(s))return"Phi"}return null}var Ae=["context_length","max_model_len"];function Me(n){let e=Ae.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(Me),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 B(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 K(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 Fe(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return E(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return E(o);let r=K(n,e);return r.length>0?E(r):null}function E(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e:Le(n),matches:n}:null}function Le(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 T=class extends Error{name="ModelCreatedError"};function $(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 T(`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 T(`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 T(`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 T(`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 F(n,e,t){let o=Fe(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=$(i),a=I(r.model_id,r.variant,t),l=ae(r,i),u=B(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 ae(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?E(n):null;return e===null?{published:[],defect:null}:ae(e.row,e.matches)}function ie(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 se(n){return{input:[{type:"prompt",unit:"token",cost_usd:ie(n.input)}],output:[{type:"completion",unit:"token",cost_usd:ie(n.output)}]}}function je(n,e,t,o){if(e.length===0)return null;let r=E(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=I(i.model_id,i.variant,t),l=Ee(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:$(s),quantization:Ie(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:se(a).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...a?{pricing:se(a).output}:{}}],...o.datacenters.length>0?{datacenters:o.datacenters}:{},...o.compliance?{compliance:o.compliance}:{}}}function le(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:Oe(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 de={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 ue(n){let e=n.t;if(typeof e!="string"||!(e in de))throw new k(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(de).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 ue(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 ue(n)}function ce(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 ce(e);let i=r.next();if(e!==void 0&&await Je(i,e)==="aborted")throw i.catch(()=>{}),ce(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{},M=class extends Error{bindingLost;reason;constructor(e,t){super(e),this.bindingLost=t?.bindingLost??!1,this.reason=t?.reason??null}},St="credits_exhausted",Tt="insufficient_credits",V="urs1.";function pe(n,e){return V+Buffer.from(JSON.stringify([n,e]),"utf8").toString("base64url")}function ge(n){if(!n.startsWith(V))return null;try{let e=JSON.parse(Buffer.from(n.slice(V.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 $t(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 fe(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)}
|
|
1
|
+
import{c as w}from"./chunk-YSFSRI3D.js";w();import{randomUUID as Ke}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",X="model_id,variant,unit,price_usd,effective_at,expires_at",Q={per_request:!0,per_minute:!0,per_output_unit:!0},Se=5e3;function Te(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 Z(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 $e(n,e,t){return n===null?null:Z(n,e,t)}function ke(n,e){if(n===j)return"input";if(n===U)return"output";if(typeof n=="string"&&Object.hasOwn(Q,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(Q).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 X.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:Te(i.price_usd,r),effective_at:Z(i.effective_at,r,"effective_at"),expires_at:$e(i.expires_at,r,"expires_at")})}return e}function ee(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 I(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 O={prices:[],refusals:[]};async function rt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${X}&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},te={int4:"int4",int8:"int8",fp4:"fp4",mxfp4:"mxfp4",nvfp4:"nvfp4",fp6:"fp6",fp8:"fp8",mxfp8:"mxfp8",fp16:"fp16",bf16:"bf16",fp32:"fp32"};function Ie(n){let e=n.toLowerCase();return Object.hasOwn(te,e)?te[e]:null}var ne={"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 Oe(n,e){if(!n||n.length===0)return[];let t=[],o=[];for(let r of n){let i=Object.hasOwn(ne,r)?ne[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 re={qwen:"Qwen",qwen1:"Qwen",qwen2:"Qwen",qwen3:"Qwen",gemma:"Gemma",diffusiongemma:"Gemma",gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",mistral:"Mistral"},oe={2:"Llama2",3:"Llama3"};function Ee(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(re,i))return re[i];let s=o[r+1];if(i==="llama"&&s!==void 0&&Object.hasOwn(oe,s))return oe[s];if(i==="phi"&&s!==void 0&&/^\d/.test(s))return"Phi"}return null}var Ae=["context_length","max_model_len"];function Me(n){let e=Ae.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(Me),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 B(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 K(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 Fe(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return E(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return E(o);let r=K(n,e);return r.length>0?E(r):null}function E(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e:Le(n),matches:n}:null}function Le(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 T=class extends Error{name="ModelCreatedError"};function $(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 T(`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 T(`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 T(`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 T(`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 F(n,e,t){let o=Fe(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=$(i),a=I(r.model_id,r.variant,t),l=ae(r,i),u=B(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 ae(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?E(n):null;return e===null?{published:[],defect:null}:ae(e.row,e.matches)}function ie(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 se(n){return{input:[{type:"prompt",unit:"token",cost_usd:ie(n.input)}],output:[{type:"completion",unit:"token",cost_usd:ie(n.output)}]}}function je(n,e,t,o){if(e.length===0)return null;let r=E(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=I(i.model_id,i.variant,t),l=Ee(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:$(s),quantization:Ie(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:se(a).input}:{}},...i.task==="vl"?[{type:"image"}]:[]],output_modalities:[{type:"text",streaming:!0,supported_parameters:u,...a?{pricing:se(a).output}:{}}],...o.datacenters.length>0?{datacenters:o.datacenters}:{},...o.compliance?{compliance:o.compliance}:{}}}function le(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:Oe(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 de={delta:!0,final:!0,turn_start:!0,turn_end:!0,turn_dropped:!0,turn_eager_end:!0,turn_resumed:!0},k=class extends Error{constructor(e){super(e),this.name="TurnLaneDecodeError"}};function ue(n){let e=n.t;if(typeof e!="string"||!(e in de))throw new k(`the "stt" transcript lane delivered an unknown turn kind ${JSON.stringify(e??null)} \u2014 known kinds: ${Object.keys(de).join(", ")}`);let t={kind:e};return e!=="turn_dropped"&&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 ue(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 ue(n)}function ce(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 ce(e);let i=r.next();if(e!==void 0&&await Je(i,e)==="aborted")throw i.catch(()=>{}),ce(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{},M=class extends Error{bindingLost;reason;constructor(e,t){super(e),this.bindingLost=t?.bindingLost??!1,this.reason=t?.reason??null}},St="credits_exhausted",Tt="insufficient_credits",V="urs1.";function pe(n,e){return V+Buffer.from(JSON.stringify([n,e]),"utf8").toString("base64url")}function ge(n){if(!n.startsWith(V))return null;try{let e=JSON.parse(Buffer.from(n.slice(V.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 $t(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 fe(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
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
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 he(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:",me="speech:",qe="realtime:";function q(n){return n.sharedApp?we+n.appSlug:n.appSlug}function G(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 W(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=W(n,e);return t.length>0?t:K(n,e)}function A(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 L=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??L):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??L):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??L):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??L;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
4
|
`),O}let o=ee(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}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as d}from"./chunk-
|
|
1
|
+
import{j as d}from"./chunk-4GW343S5.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.`,{bindingLost:!0,reason:e.reason??null}))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as te}from"./chunk-CAR4AEQJ.js";import{e as pe,f as W,g as fe,h as me}from"./chunk-
|
|
1
|
+
import{a as te}from"./chunk-CAR4AEQJ.js";import{e as pe,f as W,g as fe,h as me}from"./chunk-RONITPWW.js";import{d as ee,g as V,h as ne,q as oe}from"./chunk-MYNG74AX.js";import{a as ge,b as G}from"./chunk-EA3GQ2MM.js";import{c as ue}from"./chunk-O3Z5AY5E.js";import{a as H}from"./chunk-526ZJAOW.js";import{b as Z,d as j}from"./chunk-AWCC5WRB.js";import{b as se,c as re,d as ie,g as ae,j as F,m as B,n as _,o as ce,r as R,s as L,t as de,u as le}from"./chunk-4GW343S5.js";import{c as b}from"./chunk-YSFSRI3D.js";b();import{App as J,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as Be,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as We,SessionFailedError as z}from"@urun-sh/core";b();import{SessionFailedError as _e}from"@urun-sh/core";var q=2;function Le(e){let t=e?.type;return t==="response.created"||t==="response.in_progress"}function Te(e){let t=e?.type;return t==="response.completed"||t==="error"}function ye(e){return async function(r,i){let a=await e.sessionFor(r.model);return(async function*(){for(let l=1;l<=q;l++){let{app:g,entry:y,identity:S}=l===1?a:await e.sessionFor(r.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:S});let p=!1,u=!1;try{let f=await e.createStream(y,r);for await(let m of f){if(Te(m)&&(p=!0),Le(m)){if(l>1)continue}else u=!0;yield m}}catch(f){if(f instanceof _e&&(f.kind==="never-live"||f.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,f)}catch{}throw f}if(l<q&&!u){await e.evict(g,y);continue}throw f}if(p)return;if(l<q&&!u){await e.evict(g,y);continue}return}})()}}import{randomUUID as Oe}from"crypto";b();import{request as Fe}from"http";var Re="/pooler/v1/inference",k=class extends Error{constructor(r,i,a,c){super(a);this.status=r;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Me=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let t=e.messages?.find(r=>r.role==="system"||r.role==="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content)},Ne=e=>{let t=e.messages?.find(r=>r.role!=="system"&&r.role!=="developer");if(t!==void 0)return typeof t.content=="string"?t.content:JSON.stringify(t.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let r=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(r===void 0)return;if(typeof r=="string")return r;if(r!==null&&typeof r=="object"&&"content"in r){let i=r.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(r)}},he=e=>new Promise((t,r)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>t(Buffer.concat(i).toString("utf8"))),e.on("error",r)}),De=async e=>{let t="pooler_error",r=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await he(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(t=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(r=a.message)}}catch{}return new k(e.status,t,r,e.retryAfterSeconds)};async function xe(e,t,r,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Re}`),l=JSON.stringify({region:e.region,model:i,request_id:r,streaming:a,payload:t,affinity:{systemPrompt:Me(t),firstMessage:Ne(t)}});return new Promise((g,y)=>{let S=Fe({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},p=>{let u=Number(p.headers["retry-after"]??"");g({status:p.statusCode??0,retryAfterSeconds:Number.isFinite(u)?u:void 0,body:p})});S.on("error",p=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${p.message}`))),S.end(l)})}var we=e=>{if(!e.startsWith("data: "))return null;let t=e.slice(6).trim();if(t===""||t==="[DONE]")return null;let r;try{r=JSON.parse(t)}catch{return null}if(r===null||typeof r!="object")return null;let i=r;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*Ce(e){let t="";for await(let i of e.body)for(t+=String(i);;){let a=t.indexOf(`
|
|
2
2
|
|
|
3
3
|
`);if(a===-1)break;let c=t.slice(0,a);t=t.slice(a+2);let l=we(c);l!==null&&(yield l)}let r=we(t);r!==null&&(yield r)}async function on(e,t,r,i){let a=Z(t,r,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await xe(e,a,r,c,t.stream===!0);if(l.status>=400)throw await De(l);let g=t.stream===!0?j(r,Ce(l)):await Ue(l,r);return(async function*(){yield{type:"response.created",response:{id:`resp_${r}`,status:"in_progress"}},yield*g})()}async function Ue(e,t){let r=await he(e.body),i=null;try{let c=JSON.parse(r);c!==null&&typeof c=="object"&&(i=c)}catch{i=null}if(i===null)throw new k(502,"pooler_bad_body","the pooler answered a non-object body");let a=i;return j(t,(async function*(){yield a})())}b();import{encodeStreamEnvelope as Se}from"@urun-sh/core";var $e="audio";function Pe(e){let t=e.streamEndpoint($e);return{sessionId:e.id,appendInputAudio(r,i){let a=Buffer.from(r,"base64");if(a.byteLength!==0){if(i===void 0){t.send(Se(new Uint8Array(a)));return}t.send(Se({pcm16:r,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}b();import{encodeStreamEnvelope as je}from"@urun-sh/core";var Ve="rt-video-in";function ve(e){let t=e.streamEndpoint(Ve);return{sendInputFrame:async r=>{t.send(je(r))}}}var Ge=0,qe=4,Je=4;function Fn(e,t){let r=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let S=Number.parseInt(y,10);if(!Number.isInteger(S)||S<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return S},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):Ge;if(!Number.isInteger(a)||a<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=r("URUN_DECISION_POOL_MAX",Math.max(a,qe));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:r("URUN_DECISION_POOL_INFLIGHT_CAP",Je),replicaId:(e.URUN_REPLICA_ID??"").trim()||t||"proxy"}}function Rn(e){let t=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!t)return W;let r=Number.parseInt(t,10);if(!Number.isInteger(r)||r<=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 r*1e3}function K(e,t,r,i){let a=e[r];if(typeof a!="function")throw new Error(`app "${t}" has no function "${r}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${t}" function "${r}" returned a session without end()`);return c}function ke(e,t,r,i){let{baseUrl:a,orgId:c,auth:l}=e,g=t.fnName??e.fnName,y=e.sessionStartOptions?.(r),S={...t.sharedApp?{sharedApp:!0}:{},...y,...i,presenceIdleMs:3e4},p=h=>({session:h,responses:new H(h),gone:ge(h,r)});if(l.lane==="jwt"){let h=J(t.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return p(K(h,t.appSlug,g,S))}if(l.lane==="machine"||l.lane==="user"){let h=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:I}=l,C=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),T=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(h,{baseUrl:I,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:C,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(T,t.appSlug,g,S))}let{apiKey:u,gatewayUrl:f}=l,m=(typeof e.subject=="function"?e.subject():e.subject)??Oe(),w=J(t.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(u,{baseUrl:f,expiresIn:300,allowedFunctions:[`${t.appSlug}/${g}`],subject:m,...t.sharedApp?{sharedApp:!0}:{}})).token});return p(K(w,t.appSlug,g,S))}function Ie(e){let t=e.session.id;if(typeof t!="string"||t.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 t}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let t=e.status.error?.httpStatus,r=e.status.error?.code;return t===410||t===409&&(r==="cancelled"||r==="expired")?!0:r==="client_ended"}var Ke=new Set(["error","paused"]);function Mn(e){let{auth:t,catalog:r}=e,i=null,a=(l,g)=>{let y=ke(e,l,g);return e.onSessionOpen&&typeof y.session.id=="string"&&y.session.id!==""&&e.onSessionOpen(g,y.session.id),y.gone.onGone(()=>{i?.evict(g,y)}),y},c=new le({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,callerOrgId:e.orgId,openSession:a,closeSession:async l=>{if(l.gone.dispose(),l.audioDispose?.(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:t.lane==="api-key"?()=>ce({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,listCatalog:e.catalogRows??(r?()=>te(r):null),listPrices:r?()=>ie(r):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return se(l)}:t.lane==="api-key"?()=>re({apiUrl:e.apiUrl,apiKey:t.apiKey}):null,sessionKey:Ie});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},L({appSlug:e.defaultApp}))),c}function Nn(e,t){let r=e.decisionPool;if(!r)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=r.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=p=>{process.stderr.write(`[decision-pool] ${p}
|
|
4
4
|
`)},y=(p,u)=>{let f=a.get(u);if(f)return f;let m=new pe({min:r.min,max:r.max,idleGraceMs:r.idleGraceMs,inFlightCap:r.inFlightCap,replicaId:i,onLease:w=>w.session.activity?.(),openSlot:async w=>{let h=ke(e,p,u,{concurrencyKey:w.concurrencyKey});return h.gone.onGone(I=>I.bindingLost?m.evict(h):m.markSessionDead(h)),await x(h.session),g(`slot attached pool=${u} slot=${w.concurrencyKey} session=${h.session.id??"(no id)"}`),h},closeSlot:async w=>{w.gone.dispose(),w.audioDispose?.(),await w.session.end()},onDetach:(w,h)=>g(`slot detached pool=${u} slot=${w.concurrencyKey} reason=${h}`),terminalOpenFailure:w=>w instanceof z&&X(w)});return c.set(u,{target:p,env:r}),a.set(u,m),m},S=async(p,u)=>{let f=c.get(u);if(f)try{let m=await t.poolTuningFor(p);y(p,u).retune({min:m?.min??f.env.min,max:m?.max??f.env.max,inFlightCap:m?.in_flight_cap??f.env.inFlightCap,idleGraceMs:m?.idle_grace_s!==void 0?m.idle_grace_s*1e3:f.env.idleGraceMs,warmWaitMs:m?.warm_wait_s!==void 0?m.warm_wait_s*1e3:void 0})}catch(m){g(`pool tuning refresh failed pool=${u} reason=${m instanceof Error?m.message:String(m)}`)}};return{async boot(){if(e.defaultApp===null)return;let p={appSlug:e.defaultApp};await y(p,L(p)).boot()},async sessionFor(p){let u=await t.resolveTargetFor(p),f=L(u),m=y(u,f);await S(u,f);let w=await m.acquire({timeoutMs:m.requestWaitMs}),h=l.get(w.entry)??[];return h.push(w),l.set(w.entry,h),{app:f,entry:w.entry,identity:de(u)}},async warmFor(p){let u=await t.resolveTargetFor(p);await y(u,L(u)).boot()},end(p){let u=l.get(p)?.shift();u&&(l.get(p)?.length===0&&l.delete(p),u.release())},evict(p){for(let u of a.values())u.evict(p)},markSessionDead(p){for(let u of a.values())u.markSessionDead(p)},reap(){for(let[p,{target:u}]of c)S(u,p).then(()=>{let f=a.get(p);f&&f.reap()})},async pingReady(p){for(let u of a.values())if(await u.pingReady(p))return!0;return!1},stats(){return[...a.entries()].map(([p,u])=>({poolKey:p,...u.stats()}))},async drain(p){await Promise.all([...a.values()].map(u=>u.drain({timeoutMs:p})))},async close(){await Promise.all([...a.values()].map(p=>p.close()))}}}function ze(e){return We(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:Be:be}async function x(e,t){let r=e.whenLive;if(typeof r!="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 r.call(e,{timeout:ze(e.phase),signal:t})}async function Xe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}async function Ae(e){let t=e.phase?.name;if(t==="live"||t==="paused"){if(typeof e.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");e.detach();return}if(typeof e.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await e.end()}function D(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Dn(e,t=ne,r,i,a=W,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,S=new WeakMap,p=new Map,u=new WeakMap,f=n=>{let s=n.session.id;return typeof s=="string"&&s.length>0?s:null},m="lane",w=n=>{let s=_(n);if(!c||!s||s.app!==m)return null;let o=c.entryFor(s.key);if(!o)throw new F(`the lane behind this handle (${s.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:s.key,entry:o}},h=async n=>w(n)?.entry??(await e.sessionForHandle(n)).entry,I=n=>{let s=l.get(n);if(!s){let o={waiting:0,gone:new AbortController};u.set(n,o),s=(async()=>{if(await x(n.session,o.gone.signal),o.gone.signal.aborted)throw D(o.gone.signal);u.get(n)===o&&u.delete(n);let d=await ee(n.session,await t());return Object.assign(d,{sessionId:n.session.id})})(),l.set(n,s),s.then(d=>{l.get(n)===s&&(n.audioDispose=()=>d.dispose())},()=>{}),s.catch(()=>{l.get(n)===s&&l.delete(n)}),s.then(()=>{u.get(n)===o&&u.delete(n)},()=>{u.get(n)===o&&u.delete(n)})}return s},C=n=>{let s=S.get(n);return s||(s=(async()=>{let o=await I(n);return{appendInputAudio:(d,v)=>o.appendInputAudio(d,v),onOutputAudio:d=>o.onOutputAudio(d),sessionId:f(n)}})(),S.set(n,s),s.catch(()=>{S.get(n)===s&&S.delete(n)})),s},T=async(n,s,o,d=!1)=>{let v=()=>d?Ae(n.session):Xe(n.session);if(o?.aborted){let O=u.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await v().catch(()=>{}),D(o)}let E=s(n),P=u.get(n);return P!==void 0&&P.waiting++,o===void 0?E:new Promise((O,A)=>{let Q=()=>{P!==void 0&&--P.waiting===0&&u.get(n)===P&&(P.gone.abort(),u.delete(n),l.delete(n),S.delete(n),v().catch(()=>{})),A(D(o))};o.addEventListener("abort",Q,{once:!0});let Y=()=>o.removeEventListener("abort",Q);E.then($=>{Y(),O($)},$=>{Y(),A($)})})},U=async(n,s,o)=>{try{return await o}catch(d){throw(d instanceof F||d instanceof z&&X(d))&&(e.evict(n,s),d instanceof z&&r?.(n,d.kind==="never-live"?"never-live":"create-failed")),d}};return{createResponse:ye({sessionFor:c?async n=>{let s=await e.resolveTargetFor(n);if(s.sharedApp)try{let o=await c.sessionFor(n,s);return{app:o.app,entry:o.entry,identity:o.identity}}catch(o){if(o instanceof ue)return i?i.sessionFor(n):e.sessionFor(n);if(o instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${o.name} ${o.code}: ${o.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw o}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>f(n),evict:(n,s)=>{c&&c.owns(s)?c.evict(s):i?i.evict(s):e.evict(n,s)},onAdmissionVerdict:(n,s,o)=>{X(o)&&(c&&c.owns(s)?c.evict(s):i?i.markSessionDead(s):e.evict(n,s),r?.(n,o.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,s)=>{try{await x(n.session);let o=fe(G(await n.responses.responses.create(s),n.gone),a);if(!i&&!c)return o;let d=n;return(async function*(){try{yield*o}catch(E){throw me(E)&&(c&&c.owns(d)?c.evict(d):i&&(E instanceof F&&!E.bindingLost?i.markSessionDead(d):i.evict(d))),E}finally{c&&c.owns(d)?c.release(d):i?.end(d)}})()}catch(o){throw c&&c.owns(n)?c.release(n):i&&i.end(n),o}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,s)=>e.supportsImages(n,s),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,s)=>{let{app:o,entry:d}=await e.sessionFor(n);return await U(o,d,T(d,I,s))},openAudioOn:async(n,s,o,d)=>{let v=w(n);if(v){let A=v.entry.session;return Pe(A)}let{app:E,entry:P}=await e.sessionForHandle(n);if(d&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;d({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let O=_(n)?.app.startsWith(R)??!1;return await U(E,P,T(P,C,s,O))},openTurnsOn:async function*(n,s){if(s?.aborted)throw D(s);let o=await h(n);yield*ae(o.session,s)},openVideoOn:async n=>{let s=w(n);if(s)return ve(s.entry.session);let{entry:o}=await e.sessionForHandle(n),d=g.get(o);return d||(d=V(o.session),g.set(o,d)),d},openVideo:async n=>{let{entry:s}=await e.sessionFor(n),o=g.get(s);return o||(o=V(s.session),g.set(s,o)),o},openVideoOut:async n=>{let{entry:s}=await e.sessionFor(n),o=y.get(s);return o||(o=oe(s.session),y.set(s,o)),o},sessionHandle:async n=>{if(c){let s=await e.resolveTargetFor(n);if(s.sharedApp){let o=await c.sessionFor(n,s),d=f(o.entry);if(d===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return B(m,d)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:o,entry:d}=await e.dedicatedSessionFor(n);return B(o,Ie(d))},touchSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);o||(o=new Map,p.set(n,o)),o.set(s,Date.now());let d=null;try{d=await h(n)}catch{return}d.session.activity?.()})()},detachSessionPresence:(n,s)=>{(async()=>{let o=p.get(n);if(o?.delete(s),o&&o.size===0&&p.delete(n),o&&o.size>0)return;let d=null;try{d=await h(n)}catch{return}d.session.presenceDetach?.()})()},releaseSessionHandle:n=>{let s=_(n);if(!s)return;if(s.app.startsWith(R)){(async()=>{let d=null;try{d=(await e.sessionForHandle(n)).entry}catch{return}await Ae(d.session).catch(()=>{}),await e.evict(s.app,d)})();return}if(!c||s.app!==m)return;let o=c.entryFor(s.key);o&&c.release(o)},endDedicatedSession:async n=>{let s=_(n);if(!s||!s.app.startsWith(R))return;let o=null;try{o=(await e.sessionForHandle(n)).entry}catch{return}if(typeof o.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let d=await o.session.end();return await e.evict(s.app,o),d},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:s,entry:o}=await e.sessionForHandle(n);await e.evict(s,o)},createResponseOn:async(n,s,o)=>{let d=await h(n);await x(d.session);let v=o!==void 0&&w(n)?new H({...d.session,consumerId:o},{sessionTag:o}):d.responses;return G(await v.responses.create(s),d.gone)},onSessionEnd:async(n,s)=>{let o=w(n);if(o)return o.entry.gone.onGone(P=>s({timeLeftMs:null,reason:P.message}));let{entry:d}=await e.sessionForHandle(n),v=d.session;if(typeof v.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let E=!1;return v.onPhase(P=>{if(E||!Ke.has(P.name))return;E=!0;let O=v.endsAt??null;s({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}export{k as a,on as b,Fn as c,Rn as d,Mn as e,Nn as f,Dn as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as m}from"./chunk-
|
|
1
|
+
import{h as m}from"./chunk-4GW343S5.js";import{c}from"./chunk-YSFSRI3D.js";c();import P from"os";import N from"path";import{fileURLToPath as k}from"url";import{format as I}from"util";var g="0.6.57";var y=4141,A=g,M={claude:{bin:"claude",env:"anthropic"},codex:{bin:"codex",env:"openai"},pi:{bin:"pi",env:"openai"},omp:{bin:"omp",env:"openai"},aider:{bin:"aider",env:"openai"},opencode:{bin:"opencode",env:"openai"},crush:{bin:"crush",env:"openai"}};function O(e,t="openai"){if(t==="anthropic")return{ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}`,ANTHROPIC_API_KEY:"urun-local"};let n=`http://127.0.0.1:${e}/v1`;return{OPENAI_BASE_URL:n,OPENAI_API_BASE:n,OPENAI_API_KEY:"urun-local"}}function F(e,t,n){let r={...e,...O(t,n)};return delete r.URUN_API_KEY,delete r.URUN_JWT,r}function H(e,t,n){let r=["-c","model_providers.urun.name=urun","-c",`model_providers.urun.base_url="http://127.0.0.1:${e}/v1"`,"-c",'model_providers.urun.wire_api="responses"',"-c",'model_provider="urun"'],o=n.indexOf("--"),s=o===-1?n:n.slice(0,o),a=s.some(d=>d==="-m"||d==="--model"||d.startsWith("--model=")),i=n[0]==="exec",u=s.includes("--skip-git-repo-check"),p=i&&!u?["exec","--skip-git-repo-check",...n.slice(1)]:n;return[...r,...a?[]:["-m",t],...p]}function V(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--provider","urun","--model",e,...t]}function X(e,t){return t.some(r=>r==="--model"||r==="--provider"||r.startsWith("--model=")||r.startsWith("--provider="))?t:["--model",`urun/${e}`,...t]}function z(e,t,n){let r=(e.URUN_PI_EXTENSION_ENTRY??"").trim();if(r){if(!n(r))throw new Error(`URUN_PI_EXTENSION_ENTRY points at ${r}, which does not exist \u2014 the launcher that injected it (the vendored urun CLI shim) must materialize the pi extension bundle before spawning pi`);return r}let o=k(new URL("../pi-extension/standalone.cjs",t));if(!n(o))throw new Error(`pi extension entry not found at ${o} \u2014 the pi lane loads the self-contained @urun-sh/openai dist/pi-extension/standalone.cjs from the installed package (run \`urun compat pi\` via the npm-installed CLI, e.g. \`npx @urun-sh/openai\`), or pass an entry to pi yourself: \`pi -e <path-to-@urun-sh/openai>/dist/pi-extension/standalone.cjs\``);return o}function x(e){let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`--port needs a non-negative integer (0 = OS-assigned ephemeral), got ${e}`);return t}function Q(e){if(e[0]!=="--port")return null;let t=x(e[1]);return e.splice(0,2),t}function Z(e){let t=e.indexOf("--port");if(t===-1)return y;let n=x(e[t+1]);return e.splice(t,2),n}function ee(e){if(e===0)throw new Error("`env` cannot use --port 0: it starts no proxy, so the OS never assigns the ephemeral port \u2014 pass the actual port of the running proxy");return e}function l(e,t){let n=(e[t]??"").trim();if(!n)throw new Error(`${t} is not set. The proxy needs URUN_BASE_URL, URUN_ORG_ID, URUN_APP and either URUN_API_KEY (the org key; the proxy vends short-lived function-scoped client tokens from it via the SDK) or URUN_JWT (an explicit pre-vended token override) \u2014 plus optional URUN_FUNCTION, default "serve" \u2014 to open the backhaul session.`);return n}function te(e){let t=$(l(e,"URUN_BASE_URL")),n=l(e,"URUN_ORG_ID"),r=l(e,"URUN_APP"),o=(e.URUN_FUNCTION??"serve").trim()||"serve",s=(e.URUN_API_URL??"").trim(),a=s?f(s,"URUN_API_URL"):m,i=(e.URUN_JWT??"").trim();if(i)return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"jwt",jwt:i}};let u=(e.URUN_API_KEY??"").trim();if(u){let p=(e.URUN_GATEWAY_URL??"").trim(),d=p?f(p):void 0;return{baseUrl:t,orgId:n,appId:r,fnName:o,apiUrl:a,auth:{lane:"api-key",apiKey:u,gatewayUrl:d}}}throw new Error("neither URUN_API_KEY nor URUN_JWT is set. Set URUN_API_KEY (the org API key \u2014 the proxy vends short-lived, function-scoped client tokens from it via the SDK, so the key never reaches the agent process) or URUN_JWT (an explicit pre-vended token; when set it always wins). URUN_BASE_URL, URUN_ORG_ID and URUN_APP are also required.")}function $(e,t="URUN_BASE_URL"){if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`${t} must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org control-plane API form (that belongs in URUN_API_URL); session allocation 404s against it. Drop the /v1.`);return e}function f(e,t="URUN_GATEWAY_URL"){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!r)throw new Error(`${t} must be https (got ${e}) \u2014 the org API key rides the request's Authorization header`);return e}function ne(e){return{app:e.appId,org:e.orgId,fn:e.fnName,base_url:e.baseUrl,proxy_version:A}}function j(e,t){return e.app===t.app&&e.org===t.org&&e.fn===t.fn&&e.base_url===t.base_url&&e.proxy_version===t.proxy_version}var T=250;async function L(e,t=T){try{let n=await fetch(`http://127.0.0.1:${e}/stats`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let r=(await n.json()).identity;if(r==null||typeof r!="object")return null;let{app:o,org:s,fn:a,base_url:i,proxy_version:u}=r;return typeof o!="string"||typeof s!="string"||typeof a!="string"||typeof i!="string"||typeof u!="string"?null:{app:o,org:s,fn:a,base_url:i,proxy_version:u}}catch{return null}}var v=2e3;async function C(e,t=v){try{let n=await fetch(`http://127.0.0.1:${e}/v1/models`,{signal:AbortSignal.timeout(t)});return n.ok?null:`GET /v1/models answered HTTP ${n.status}`}catch(n){return`GET /v1/models failed (${String(n instanceof Error?n.message:n)})`}}async function re(e,t,n=y,r=v){if(e!=null)return{mode:"spawn",port:e};let o=await L(n);if(o!==null&&j(o,t)){let s=await C(n,r);return s===null?{mode:"reuse",port:n,identity:o}:{mode:"spawn",port:0,reason:`a urun-openai proxy on port ${n} matches this invocation's identity but failed the serving-surface liveness check (${s}) \u2014 starting a fresh proxy on an ephemeral port instead of pointing the harness at it`}}return{mode:"spawn",port:0}}function oe(e,t=P.homedir()){return N.join(t,".urun","logs",`compat-proxy-${e}.log`)}var h=["log","info","warn","error","debug","trace"];function ie(e,t=process,n=console){let r=t.stdout.write,o=t.stderr.write,s=(i,...u)=>e.write(i,...u);t.stdout.write=s,t.stderr.write=s;let a=Object.fromEntries(h.map(i=>[i,n[i]]));for(let i of h)n[i]=(...u)=>{e.write(`${I(...u)}
|
|
2
2
|
`)};return()=>{t.stdout.write=r,t.stderr.write=o;for(let i of h)n[i]=a[i]}}var D=new Set(["EPIPE","EIO","EBADF","ENXIO"]);function E(e){let t=e?.code;return typeof t=="string"&&D.has(t)}function se(e,t){try{return e.write(t),!0}catch(n){if(E(n))return!1;throw n}}function ae(e){let t={stdout:!1,stderr:!1},n=[];for(let r of["stdout","stderr"]){let o=e.streams[r],s=a=>{E(a)&&(t[r]=!0);let i=a?.code;try{e.note(`${new Date().toISOString()} urun compat: process.${r} died (${String(i??(a instanceof Error?a.message:a))}) \u2014 the terminal is gone; launcher output continues in this log only
|
|
3
3
|
`)}catch{}};o.on("error",s),n.push([o,s])}return{isDead:r=>t[r],uninstall:()=>{for(let[r,o]of n)r.off("error",o)}}}function ue(e){let t=n=>{let r=n instanceof Error?`${n.stack??`${n.name}: ${n.message}`}`:String(n);try{e.appendSync(e.logPath,`${new Date().toISOString()} launcher crashed (in-process proxy): ${r}
|
|
4
4
|
`)}catch{}e.restore();try{e.writeStderr(`urun compat: the in-process proxy crashed (${n instanceof Error?n.message:String(n)}) \u2014 terminating the harness (its backend is gone); details: ${e.logPath}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Xn,c as Yn,d as Fe,e as Ct,f as re,g as Qn,h as Zn,i as es,j as ts,k as ns,l as ss,m as rs,n as is,r as os,t as as,u as us,v as ls,w as ds,x as cs}from"./chunk-KV3UXLNF.js";import{a as an,b as Mt,f as un}from"./chunk-MYNG74AX.js";import{a as Oe,b as ye,v as Pe}from"./chunk-6R3TCKOH.js";import{a as zn,e as ct,f as Kn,i as J,j as Q,k as ln,l as dn}from"./chunk-N3Y2GDQK.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as Gr}from"crypto";import{WebSocketServer as Jr}from"ws";var Wr=256,Lt=class{snapshots=new Map;store(e,t,s){for(this.snapshots.set(`${e}\0${t}`,s);this.snapshots.size>Wr;){let r=this.snapshots.keys().next().value;this.snapshots.delete(r)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Vr="local",pt=n=>n.slice(0,120),$t=class{constructor(e,t,s){this.ws=e;this.call=t;this.registry=s;this.clients=t.clients,this.scope=t.scope,e.on("message",r=>this.onMessage(r)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Yn,pt(e.message));return}if(e instanceof Q){this.ws.close(Ct,pt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,pt(e.message));return}this.ws.close(Fe,pt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Qn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let s=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:i}=is(t.clientContent);this.transcript.push(...r),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=as(t.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,s);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:os);return}this.transcript.push(...us(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=ns(e),s=t.sessionResumption.handle;if(s!==null){let i=this.registry.get(this.scope,s);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Ct);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(s)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Ct);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let r={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(ts(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},r[Zn]=es(o.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let s=await t.call(this.clients,e.model);return this.detachAudio=s.onOutputAudio(r=>this.send(ds(r))),s})(),this.audio.catch(s=>this.fail(s)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(s=>this.fail(s)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let s=Gr();this.registry.store(this.scope,s,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(s),this.send(ss(s))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(rs(e.timeLeftMs)),this.ws.close(Fe,pt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let s=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),r,i=!1;for await(let u of s){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){r=l.response,i=!0;continue}let d=ls(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=cs(r);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,s){super(s);this.status=t;this.name="UpgradeAuthError"}status};function zr(n,e,t){let s=new Set;(u=>{if(typeof u=="string")u!==""&&s.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&s.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&s.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&s.add(o),s.size>1)throw new De(401,`contradictory credentials: ${s.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of s)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ps(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let s=new Jr({noServer:!0}),r=new Lt;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Xn&&(a.on("error",()=>{}),(async()=>{let d=zr(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:Vr}}s.handleUpgrade(o,a,u,p=>{new $t(p,c,r)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
|
|
1
|
+
import{a as Xn,c as Yn,d as Fe,e as Ct,f as re,g as Qn,h as Zn,i as es,j as ts,k as ns,l as ss,m as rs,n as is,r as os,t as as,u as us,v as ls,w as ds,x as cs}from"./chunk-KV3UXLNF.js";import{a as an,b as Mt,f as un}from"./chunk-MYNG74AX.js";import{a as Oe,b as ye,v as Pe}from"./chunk-O3Z5AY5E.js";import{a as zn,e as ct,f as Kn,i as J,j as Q,k as ln,l as dn}from"./chunk-4GW343S5.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{randomUUID as Gr}from"crypto";import{WebSocketServer as Jr}from"ws";var Wr=256,Lt=class{snapshots=new Map;store(e,t,s){for(this.snapshots.set(`${e}\0${t}`,s);this.snapshots.size>Wr;){let r=this.snapshots.keys().next().value;this.snapshots.delete(r)}}get(e,t){return this.snapshots.get(`${e}\0${t}`)}},Vr="local",pt=n=>n.slice(0,120),$t=class{constructor(e,t,s){this.ws=e;this.call=t;this.registry=s;this.clients=t.clients,this.scope=t.scope,e.on("message",r=>this.onMessage(r)),e.on("close",()=>{this.unsubscribeEnd?.(),this.unsubscribeEnd=null,this.detachAudio?.(),this.detachVideoOut?.(),this.call.release?.().catch(()=>{})})}ws;call;registry;config=null;transcript=[];queue=Promise.resolve();proxyHandle=null;unsubscribeEnd=null;audio=null;detachAudio=null;detachVideoOut=null;video=null;activityOpen=!1;activeTurn=null;scope;clients;send(e){this.ws.readyState===this.ws.OPEN&&this.ws.send(JSON.stringify(e))}fail(e){if(e instanceof J){this.ws.close(Yn,pt(e.message));return}if(e instanceof Q){this.ws.close(Ct,pt(e.message));return}if(e instanceof re){this.ws.close(e.closeCode,pt(e.message));return}this.ws.close(Fe,pt(String(e instanceof Error?e.message:e)))}onMessage(e){try{let t=Qn(typeof e=="string"?e:Buffer.concat(Array.isArray(e)?e:[e]).toString("utf8"));if(t.kind==="setup"){this.handleSetup(t.setup).catch(r=>this.fail(r));return}if(!this.config)throw new re(`"${t.kind}" before setup \u2014 the first client message must be BidiGenerateContentSetup`);let s=this.config;if(t.kind==="clientContent"){let{items:r,turnComplete:i}=is(t.clientContent);this.transcript.push(...r),i&&this.enqueue(()=>this.runTurn());return}if(t.kind==="realtimeInput"){let r=as(t.realtimeInput);if(r.kind==="activityStart"||r.kind==="activityEnd"){this.onActivity(r.kind,s);return}if(r.kind==="text"){this.transcript.push({role:"user",content:r.text}),this.enqueue(()=>this.runTurn());return}if(r.kind==="video"){this.appendVideoFrame(r.jpegFrame);return}this.appendAudio(r.kind==="audio"?r.base64Pcm24k:os);return}this.transcript.push(...us(t.toolResponse)),this.enqueue(()=>this.runTurn())}catch(t){this.fail(t)}}async handleSetup(e){if(this.config)throw new re("setup may only be sent once, as the first client message");let t=ns(e),s=t.sessionResumption.handle;if(s!==null){let i=this.registry.get(this.scope,s);if(!i)throw new re("unknown sessionResumption.handle \u2014 the Live session it names is gone (proxy restarted, handle evicted, or never issued) and cannot be resumed; reconnect without a handle to start a new session",Ct);if(i.model!==t.model)throw new re(`sessionResumption.handle was issued for model "${i.model}" \u2014 the model cannot change on resume (got "${t.model}", per the Live API session-resumption contract)`);if(t.systemItems.length>0)throw new re("setup.systemInstruction cannot be changed on resume \u2014 it is part of the resumed conversation state");if(this.call.clientsForResume!==void 0&&(this.clients=await this.call.clientsForResume(s)),this.proxyHandle=await this.clients.sessionHandle(t.model),this.proxyHandle!==i.proxyHandle)throw new re(`sessionResumption.handle named pooled session "${i.proxyHandle}" but the re-attach landed on "${this.proxyHandle}" \u2014 the conversation's native session changed and the snapshot cannot be adopted; reconnect without a handle to start a new session`,Ct);this.unsubscribeEnd=await this.clients.onSessionEnd(i.proxyHandle,o=>this.enqueue(()=>this.handleUpstreamEnd(o))),this.transcript=[...i.transcript]}else this.proxyHandle=await this.clients.sessionHandle(t.model),this.unsubscribeEnd=await this.clients.onSessionEnd(this.proxyHandle,i=>this.enqueue(()=>this.handleUpstreamEnd(i))),this.transcript.push(...t.systemItems);this.config=t;let r={};if(t.videoOut){let i=this.clients.openVideoOut;if(i){let o=await i.call(this.clients,t.model),a=o.onOutputFrame(l=>this.send(ts(l))),u=o.onLaneError(l=>this.fail(l));this.detachVideoOut=()=>{a(),u()},r[Zn]=es(o.codec)}}this.send({setupComplete:r}),t.audioModality&&this.ensureAudioLane(),t.sessionResumption.enabled&&await this.mintResumptionUpdate()}ensureAudioLane(){if(this.audio)return this.audio;let e=this.config;if(!e)throw new re("audio before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openAudio;if(!t)throw new re("audio lane not wired: this proxy embedding provides no ProxyClients.openAudio (the native AudioBridge seam over the canonical `audio` lane)",Fe);return this.audio=(async()=>{let s=await t.call(this.clients,e.model);return this.detachAudio=s.onOutputAudio(r=>this.send(ds(r))),s})(),this.audio.catch(s=>this.fail(s)),this.audio}appendAudio(e){this.ensureAudioLane().then(t=>t.appendInputAudio(e)).catch(t=>this.fail(t))}ensureVideoLane(){if(this.video)return this.video;let e=this.config;if(!e)throw new re("video before setup \u2014 the first client message must be BidiGenerateContentSetup");let t=this.clients.openVideo;if(!t)throw new re("video lane not wired: this proxy embedding provides no ProxyClients.openVideo (the native rt-video-in frame-lane seam, transport/media.ts enableSessionVideo)",Fe);return this.video=Promise.resolve(t.call(this.clients,e.model)),this.video.catch(s=>this.fail(s)),this.video}appendVideoFrame(e){this.ensureVideoLane().then(t=>t.sendInputFrame(e)).catch(t=>this.fail(t))}onActivity(e,t){if(!t.activity.manualActivity)throw new re(`realtimeInput.${e} requires manual activity mode \u2014 set setup.realtimeInputConfig.automaticActivityDetection.disabled: true (automatic server-side activity detection is the declared platform follow-up)`);if(e==="activityStart"){if(this.activityOpen)throw new re("activityStart while an activity window is already open (send activityEnd first)");this.activityOpen=!0,t.activity.activityHandling==="START_OF_ACTIVITY_INTERRUPTS"&&this.activeTurn&&(this.activeTurn.interrupted=!0);return}if(!this.activityOpen)throw new re("activityEnd without an open activity window (send activityStart first)");this.activityOpen=!1}enqueue(e){this.queue=this.queue.then(e,()=>{}),this.queue=this.queue.catch(t=>this.fail(t))}async mintResumptionUpdate(){let e=this.config;if(!e?.sessionResumption.enabled||this.ws.readyState!==this.ws.OPEN)return;let t=await this.clients.sessionHandle(e.model);this.proxyHandle=t;let s=Gr();this.registry.store(this.scope,s,{model:e.model,proxyHandle:t,transcript:[...this.transcript]}),this.call.onBindResumeHandle?.(s),this.send(ss(s))}async handleUpstreamEnd(e){if(this.ws.readyState!==this.ws.OPEN||!this.config)return;this.unsubscribeEnd?.(),this.unsubscribeEnd=null;let t=null;try{t=await this.clients.sessionHandle(this.config.model)}catch{}if(t!==null&&t!==this.proxyHandle){this.proxyHandle=t,this.unsubscribeEnd=await this.clients.onSessionEnd(t,s=>this.enqueue(()=>this.handleUpstreamEnd(s))),this.config.sessionResumption.enabled&&await this.mintResumptionUpdate();return}this.send(rs(e.timeLeftMs)),this.ws.close(Fe,pt(`upstream session ended: ${e.reason}`))}async runTurn(){let e=this.config;if(!e||this.ws.readyState!==this.ws.OPEN)return;let t={interrupted:!1};this.activeTurn=t;try{let s=await this.clients.createResponse({model:e.model,input:[...this.transcript],stream:!0,tools:e.tools,temperature:e.temperature,max_output_tokens:e.maxOutputTokens}),r,i=!1;for await(let u of s){if(t.interrupted)break;let l=u;if(l.type==="error")throw new re(`upstream error: ${JSON.stringify(l)}`,Fe);if(l.type==="response.completed"){r=l.response,i=!0;continue}let d=ls(l);d&&this.send(d)}if(t.interrupted){this.send({serverContent:{interrupted:!0}});return}if(!i)throw new re("upstream produced no response.completed event",Fe);let{messages:o,assistantItems:a}=cs(r);this.transcript.push(...a);for(let u of o)this.send(u);await this.mintResumptionUpdate()}finally{this.activeTurn=null}}},De=class extends Error{constructor(t,s){super(s);this.status=t;this.name="UpgradeAuthError"}status};function zr(n,e,t){let s=new Set;(u=>{if(typeof u=="string")u!==""&&s.add(u);else if(Array.isArray(u))for(let l of u)l!==""&&s.add(l)})(n.headers["x-goog-api-key"]);let i=n.headers.authorization;typeof i=="string"&&i.startsWith("Bearer ")&&i.length>7&&s.add(i.slice(7));let o=e.searchParams.get("key")??void 0;if(o!==void 0&&o!==""&&s.add(o),s.size>1)throw new De(401,`contradictory credentials: ${s.size} distinct keys presented across the x-goog-api-key/Authorization headers and the ?key= query parameter \u2014 present exactly one`);if(t&&o!==void 0&&o!=="")throw new De(401,"the ?key= query parameter is not accepted on the hosted endpoint \u2014 send the org API key in the x-goog-api-key header or as Authorization: Bearer");let a;for(let u of s)a=u;if(a===void 0&&t)throw new De(401,"missing credentials: send the org API key in the x-goog-api-key header or as Authorization: Bearer");return a??""}function ps(n,e){let t=e.authenticate!==void 0;if(t&&(e.clients!==void 0||e.apiKey!==void 0))throw new TypeError("attachGeminiLive: authenticate (hosted per-request resolution) is mutually exclusive with a fixed clients/apiKey lane");if(!t&&e.clients===void 0)throw new TypeError("attachGeminiLive: pass fixed `clients` (local lane) or `authenticate` (hosted lane)");let s=new Jr({noServer:!0}),r=new Lt;n.on("upgrade",(o,a,u)=>{let l=new URL(o.url??"/","http://localhost");l.pathname===Xn&&(a.on("error",()=>{}),(async()=>{let d=zr(o,l,t),c;if(e.authenticate)c=await e.authenticate(d,o);else{if(e.apiKey!==void 0&&d!==e.apiKey)throw new De(401,"invalid local proxy api key");c={clients:e.clients,scope:Vr}}s.handleUpgrade(o,a,u,p=>{new $t(p,c,r)})})().catch(d=>{let c=502;(d instanceof De||typeof d=="object"&&d!==null&&"status"in d&&typeof d.status=="number")&&(c=d.status);let p=c===401?"Unauthorized":c===403?"Forbidden":c===502?"Bad Gateway":"Internal Server Error",m=d instanceof Error?d.message:String(d);a.destroyed||(a.write(`HTTP/1.1 ${c} ${p}\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
4
|
${m}\r
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Me,b as Ct,c as xt,e as De,f as Mt,g as He}from"./chunk-
|
|
1
|
+
import{a as Me,b as Ct,c as xt,e as De,f as Mt,g as He}from"./chunk-HIM6EB3J.js";import{A as Ot,B as Tt,C as Pt,D as Ut,E as Nt,b as ct,d as dt,i as ht,j as pt,l as mt,m as yt,n as wt,o as bt,p as vt,q as _t,r as St,t as kt,u as de,v as Et,w as Rt,x as Lt,y as It,z as At}from"./chunk-RONITPWW.js";import{a as lt}from"./chunk-KV3UXLNF.js";import{a as Ht,e as Wt}from"./chunk-2VZR5MAX.js";import{a as $t}from"./chunk-EA3GQ2MM.js";import{a as ut,b as le,c as ft,o as gt,p as ce}from"./chunk-O3Z5AY5E.js";import{a as Dt,c as te,e as We}from"./chunk-XNRPTMSL.js";import{a as ot}from"./chunk-526ZJAOW.js";import{e as it,j as ie,p as at,q as ae,r as xe}from"./chunk-4GW343S5.js";import{c as T}from"./chunk-YSFSRI3D.js";T();import{Counter as J,Gauge as ue,Histogram as fe,Registry as Un,collectDefaultMetrics as Nn}from"@prometheus-io/client";import{createServer as Cn}from"http";var Ds=9464,Ft="/metrics",he="(other)",$n="(none)",xn=64,Mn=128,Dn=["/v1/responses","/v1/chat/completions","/v1/systemone","/v1/decisions","/v1/messages","/v1/messages/count_tokens","/v1/models","/v1/images/models","/v1/images/generations","/v1/images/edits","/v1/audio/speech","/v1/audio/models","/v1/audio/transcriptions",kt,Rt,it],Hn=new Set(Dn);function Wn(t){return Hn.has(t)?t:he}function Fn(t){return t===null?"none":t>=500?"5xx":t>=400?"4xx":t>=300?"3xx":t>=200?"2xx":"1xx"}var pe=class{constructor(e){this.max=e}max;admitted=new Set;overflows=0;of(e,n=!0){return e===null||e===""?$n:this.admitted.has(e)?e:n?this.admitted.size>=this.max?(this.overflows+=1,he):(this.admitted.add(e),e):he}get size(){return this.admitted.size}get overflowCount(){return this.overflows}},ge=class{registry=new Un;modelLabel=new pe(xn);orgLabel=new pe(Mn);requests;duration;ttft;streamErrors;undelivered;ledgerWrites;ledgerQueue;labelCardinality;labelOverflows;lanesReady;lanePickMs;laneFirstEventMs;lane503Fast;laneDocTenantMissing;buildInfo;constructor(e={}){this.buildInfo=new ue({name:"urun_build_info",help:"Always 1. Labels identify what this process is running: component and the image commit it was built from (URUN_BUILD_COMMIT). A stale-image pod is then visible on the scrape instead of inferred.",labelNames:["component","commit"],registers:[this.registry]}),this.buildInfo.set({component:"inference_proxy",commit:process.env.URUN_BUILD_COMMIT??"unknown"},1),this.requests=new J({name:"urun_inference_requests_total",help:"Completed /v1 requests, by lane, method, HTTP status class, streaming, model and org.",labelNames:["lane","method","status_class","stream","model","org"],registers:[this.registry]}),this.duration=new fe({name:"urun_inference_request_duration_seconds",help:"Wall time from request receipt to response close. For a stream this is the WHOLE generation, not the time to the head.",labelNames:["lane","stream","model","org"],buckets:[.1,.25,.5,1,2.5,5,10,30,60,120,300,600],registers:[this.registry]}),this.ttft=new fe({name:"urun_inference_ttft_seconds",help:"Time to first output-text delta on a streamed response. The metric Hugging Face gates provider listing on (<5s for conversational models).",labelNames:["lane","model","org"],buckets:[.1,.25,.5,1,2,3,5,8,15,30,60],registers:[this.registry]}),this.streamErrors=new J({name:"urun_inference_stream_errors_total",help:"Responses that emitted an error frame AFTER the head flushed. These are HTTP 200 with a complete body, so no status-based metric can see them.",labelNames:["lane","model"],registers:[this.registry]}),this.undelivered=new J({name:"urun_inference_undelivered_total",help:"Responses whose socket did not finish flushing \u2014 the client vanished mid-answer.",labelNames:["lane","model"],registers:[this.registry]}),this.ledgerWrites=new J({name:"urun_inference_ledger_writes_total",help:"Terminal fate of the per-request ledger row for each billable /v1 request. outcome=written is the row landing (reason=priced|unpriced); outcome=skipped and outcome=failed are BOTH revenue that went unrecorded. failed/duplicate is the ENG-410 fabricated-row signal.",labelNames:["outcome","reason"],registers:[this.registry]});for(let n of Lt)this.ledgerWrites.inc({outcome:n.outcome,reason:n.reason},0);this.ledgerQueue=new ue({name:"urun_inference_ledger_queue",help:'The ledger write queue right now. measure="depth" is rows waiting for a worker; measure="oldest_age_seconds" is how long the head has waited \u2014 approaching the dwell bound means rows are about to be given up on, which is revenue lost.',labelNames:["measure"],registers:[this.registry],collect:()=>{this.ledgerQueue.set({measure:"depth"},It()),this.ledgerQueue.set({measure:"oldest_age_seconds"},At()/1e3)}}),this.labelCardinality=new ue({name:"urun_inference_label_cardinality",help:"Distinct values admitted for a bounded metric label. At its ceiling, further values report as (other).",labelNames:["label"],registers:[this.registry],collect:()=>{this.labelCardinality.set({label:"model"},this.modelLabel.size),this.labelCardinality.set({label:"org"},this.orgLabel.size)}}),this.labelOverflows=new J({name:"urun_inference_label_overflows_total",help:"Observations that would have taken a new label value but found the budget spent. Non-zero means a metric dimension is now partly blind.",labelNames:["label"],registers:[this.registry]}),this.lanesReady=new ue({name:"urun_lanes_ready",help:"Ready lanes this replica can pick for the model (self-hosted or joinable).",labelNames:["model"],registers:[this.registry]}),this.lanePickMs=new fe({name:"urun_lane_pick_ms",help:"Wall time of one lane pick (registry HGETALL + host check + entry reuse). The request-path cost of the lane plane.",labelNames:["model"],buckets:[1,5,10,25,50,100,250,500,1e3],registers:[this.registry]}),this.laneFirstEventMs=new fe({name:"urun_lane_first_event_ms",help:'Time from a lane request write to the first reply event on that lane. The p99 <50ms warm-lane SLO reads _bucket{le="50"} / _count.',labelNames:["model"],buckets:[5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4],registers:[this.registry]}),this.lane503Fast=new J({name:"urun_lane_503_fast_total",help:"Requests refused fast (503 + Retry-After 2) because no lane was ready; one demand enqueue rode each refusal window.",labelNames:["model"],registers:[this.registry]}),this.laneDocTenantMissing=new J({name:"urun_lane_doc_tenant_missing_total",help:"Tenant-bearing /doc upgrades accepted WITHOUT a lane record to bind against (lane_tenant absent or lookup threw). Fail-open by design \u2014 the strict derived-key ladder is the primary gate \u2014 but a climbing series means the runtime lane_tenant writer regressed.",registers:[this.registry]}),e.defaultMetrics!==!1&&Nn({register:this.registry,prefix:"urun_inference_proxy_"})}observeLedger(e){this.ledgerWrites.inc({outcome:e.outcome,reason:e.reason})}observeLaneReady(e,n){this.lanesReady.set({model:this.modelLabel.of(e)},n)}observeLanePick(e,n){this.lanePickMs.observe({model:this.modelLabel.of(e)},n)}observeLaneFirstEvent(e,n){this.laneFirstEventMs.observe({model:this.modelLabel.of(e)},n)}observeLane503Fast(e){this.lane503Fast.inc({model:this.modelLabel.of(e)})}observeLaneDocTenantMissing(){this.laneDocTenantMissing.inc()}observe(e){let n=Wn(e.path),r=e.status!==null&&!(e.status>=400&&e.status<500),s=this.modelLabel.overflowCount+this.orgLabel.overflowCount,o=this.modelLabel.of(e.model,r),a=this.orgLabel.of(e.org,r);this.modelLabel.overflowCount+this.orgLabel.overflowCount-s>0&&(this.modelLabel.overflowCount>s?this.labelOverflows.inc({label:"model"}):this.labelOverflows.inc({label:"org"}));let l=e.stream===!0?"true":"false";this.requests.inc({lane:n,method:e.method===""?he:e.method,status_class:Fn(e.status),stream:l,model:o,org:a}),this.duration.observe({lane:n,stream:l,model:o,org:a},e.duration_ms/1e3),e.ttft_ms!==null&&this.ttft.observe({lane:n,model:o,org:a},e.ttft_ms/1e3),e.stream_error&&this.streamErrors.inc({lane:n,model:o}),e.delivered||this.undelivered.inc({lane:n,model:o})}scrape(){return this.registry.metrics()}get contentType(){return this.registry.contentType}};function Gt(t){return Cn((e,n)=>{(async()=>{let r=(e.url??"/").split("?")[0];if(e.method!=="GET"||r!==Ft){n.writeHead(404,{"content-type":"text/plain"}),n.end(`no route for ${e.method} ${r} \u2014 this port serves only GET ${Ft}
|
|
2
2
|
`);return}let s=await t.scrape();n.writeHead(200,{"content-type":t.contentType}),n.end(s)})().catch(r=>{if(!n.headersSent){n.writeHead(500,{"content-type":"text/plain"}),n.end(`${String(r instanceof Error?r.message:r)}
|
|
3
3
|
`);return}n.end()})})}T();import{createHash as Kt}from"crypto";import{createServer as Gn}from"http";var Bs=9465,Bn="x-urun-key-id",Kn="x-urun-key-fingerprint",jn="urun-ratelimit-bucket:",Jn="urun-ratelimit-tier:",Bt="anonymous",zn=/^urun_sk_[A-Za-z0-9_-]{43}$/;function qn(t){return Kt("sha256").update(`${jn}${t}`).digest("hex")}function Vn(t){return Kt("sha256").update(`${Jn}${t}`).digest("hex")}function Yn(t){let e=/^Bearer[ \t]+(\S.*)$/i.exec((t??"").trim());if(!e)return null;let n=e[1].trim();return zn.test(n)?n:null}function jt(){return Gn((t,e)=>{let n=Yn(t.headers.authorization);e.setHeader(Bn,n===null?Bt:qn(n)),e.setHeader(Kn,n===null?Bt:Vn(n)),e.writeHead(200),e.end()})}T();import{createClientToken as Qn,ClientTokenError as Jt}from"@urun-sh/core";import{createPublicKey as Xn,verify as Zn}from"crypto";var zt="urun-session-gateway",er="machine",tr=3e5;function Yt(t){let e=t.split(".");return e.length===3&&e[0]!==""&&e[1]!==""&&e[2]!==""}var N=class extends Error{constructor(n,r=401){super(n);this.status=r;this.name="ProxyAuthError"}status},q=class extends Error{status=402;code;constructor(e){super(e==="spend_cap_reached"?"the organization reached its monthly credit cap \u2014 new requests are refused until the cap resets":e==="insufficient_credits"?"the organization has no credits left \u2014 new requests are refused until credits are added":"the organization cannot start new requests under its current credits status"),this.name="CreditsAdmissionRefusalError",this.code=e}},G=class extends Error{detail;constructor(e,n){super(e),this.name="ControlPlaneUnavailableError",this.detail=n}};function be(t){let e=(t??"").trim();if(e==="")throw new N("missing Authorization header \u2014 send your uRun org API key as `Authorization: Bearer <key>`");let n=/^Bearer[ \t]+(\S.*)$/i.exec(e);if(!n)throw new N("malformed Authorization header \u2014 expected `Authorization: Bearer <urun org api key>`");return n[1].trim()}var nr=60,rr=6e4,sr=4096;function or(t){return t===401||t===403}var re=class{constructor(e){this.opts=e;this.mint=e.mint??Qn,this.now=e.now??Date.now}opts;cache=new Map;mint;now;async resolve(e){if(e==="")throw new N("empty Authorization bearer token");let n=this.opts.credential??"api-key",r=this.cache.get(e);if(r&&this.now()-r.at<rr)return{apiKey:e,orgId:r.orgId,credential:n,...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}};let s,o;try{let a=await this.mint(e,{baseUrl:this.opts.gatewayUrl,expiresIn:nr});s=a.orgId,o={...a.billingAudience!==void 0?{billingAudience:a.billingAudience}:{},...a.creditsAdmissionOk!==void 0?{creditsAdmissionOk:a.creditsAdmissionOk}:{},...a.creditsRefusalReason!==void 0?{creditsRefusalReason:a.creditsRefusalReason}:{}}}catch(a){throw a instanceof Jt&&a.status===402?(this.cache.delete(e),new q(a.code==="spend_cap_reached"||a.code==="insufficient_credits"?a.code:void 0)):a instanceof Jt&&or(a.status)?(this.cache.delete(e),new N(n==="user"?"the WorkOS user token was rejected by the control plane \u2014 check that the user belongs to an org with inference access":"the uRun org API key was rejected by the control plane \u2014 check the key and that it is not revoked")):new G(n==="user"?"the control plane could not be reached to verify this user token \u2014 retry shortly":"the control plane could not be reached to verify this API key \u2014 retry shortly",`could not verify the ${n==="user"?"user token":"API key"} against the control plane at ${this.opts.gatewayUrl}: ${a instanceof Error?a.message:String(a)}`)}if(!s)throw new G(`the control plane verified the ${n==="user"?"user token":"API key"} but returned no org_id \u2014 refusing to route a request with no tenancy (control-plane contract violation)`);if(this.cache.size>=sr){let a=this.cache.keys().next();a.done||this.cache.delete(a.value)}return this.cache.set(e,{orgId:s,at:this.now(),...o}),{apiKey:e,orgId:s,credential:n,...o}}clear(){this.cache.clear()}};function ne(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString("utf8"))}function qt(t){return t.kty==="RSA"&&t.n!==void 0&&t.e!==void 0}var me=class{constructor(e,n,r,s){this.fetchImpl=e;this.now=n;this.unavailable=r;this.jwksNoun=s}fetchImpl;now;unavailable;jwksNoun;entries=new Map;inFlight=new Map;async fetchKeys(e){let n;try{n=await this.fetchImpl(e,{signal:AbortSignal.timeout(3e3)})}catch(r){throw this.unavailable(`could not fetch the ${this.jwksNoun} at ${e}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw this.unavailable(`the ${this.jwksNoun} at ${e} answered HTTP ${n.status}`);try{let r=await n.json();if(!Array.isArray(r.keys))throw this.unavailable(`the ${this.jwksNoun} at ${e} answered no "keys" array`);return r.keys}catch(r){throw r instanceof G?r:this.unavailable(`the ${this.jwksNoun} at ${e} answered a body that is not JSON`)}}async keys(e,n){let r=this.entries.get(e);if(!n&&r!==void 0&&this.now()-r.at<tr)return r.keys;let s=this.inFlight.get(e);if(s!==void 0)return s;let o=this.fetchKeys(e).finally(()=>{this.inFlight.delete(e)});this.inFlight.set(e,o);let a=await o;return this.entries.set(e,{keys:a,at:this.now()}),a}async keyFor(e,n){let r=await this.keys(e,!1),s=n===""?void 0:r.find(o=>o.kid===n&&qt(o));return s===void 0&&(r=await this.keys(e,!0),s=n===""?void 0:r.find(o=>o.kid===n&&qt(o))),s}};function Qt(t,e,n){try{let r=Xn({key:n,format:"jwk"});return Zn("RSA-SHA256",t,r,e)}catch{return!1}}var ye=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new me(e.fetchImpl??fetch,e.now??Date.now,n=>new G("the machine-identity issuer could not be reached to verify this machine token \u2014 retry shortly",n),"machine issuer's JWKS")}opts;cache;now;async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new N("malformed machine token");let o,a;try{o=ne(n),a=ne(r)}catch{throw new N("malformed machine token")}if(o.alg!=="RS256")throw new N(`machine token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new N(`machine token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);if(a.aud!==zt)throw new N(`machine token audience must be ${zt} (got ${JSON.stringify(a.aud??null)})`);if(a.token_use!==er)throw new N(`bearer is a ${JSON.stringify(String(a.token_use??""))} token, not a machine token`);let h=typeof a.org_id=="string"?a.org_id:"";if(h==="")throw new N("machine token carries no org_id \u2014 no tenancy to route by");let f=typeof a.exp=="number"?a.exp:0;if(f<=Math.floor(this.now()/1e3))throw new N("machine token is expired \u2014 re-mint and retry");let m=await this.cache.keyFor(`${this.opts.jwksBaseUrl.replace(/\/+$/,"")}/api/machine-identity/jwks.json`,i);if(m===void 0)throw new N(`machine token kid ${JSON.stringify(i)} is not in the machine issuer's JWKS`);let O=Buffer.from(`${n}.${r}`,"ascii"),P=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qt(O,P,m))throw new N("machine token signature failed verification");if(f<=Math.floor(this.now()/1e3))throw new N("machine token is expired \u2014 re-mint and retry");return{apiKey:e,orgId:h,credential:"machine"}}},ir="https://api.workos.com/sso/jwks/";function ar(t){return`${ir}${t.slice(t.lastIndexOf("/")+1)}`}var Fe=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.cache=new me(e.fetchImpl??fetch,this.now,n=>new G("the WorkOS issuer could not be reached to verify this user token \u2014 retry shortly",n),"WorkOS issuer's JWKS")}opts;cache;now;accepts(e){if(!Yt(e))return!1;try{let n=ne(e.split(".")[1]??"").iss;return typeof n=="string"&&this.opts.issuers.includes(n)}catch{return!1}}async verify(e){let[n,r,s]=e.split(".");if(n===void 0||r===void 0||s===void 0)throw new N("malformed user token");let o,a;try{o=ne(n),a=ne(r)}catch{throw new N("malformed user token")}if(o.alg!=="RS256")throw new N(`user token alg must be RS256 (got ${JSON.stringify(o.alg??null)})`);let i=typeof o.kid=="string"?o.kid:"",l=typeof a.iss=="string"?a.iss:"";if(l===""||!this.opts.issuers.includes(l))throw new N(`user token issuer is not one this endpoint accepts (${JSON.stringify(l)})`);let h=typeof a.org_id=="string"?a.org_id:"";if(h==="")throw new N("user token carries no org_id \u2014 no tenancy to route by");let f=typeof a.sub=="string"?a.sub:"",m=typeof a.exp=="number"?a.exp:0;if(m<=Math.floor(this.now()/1e3))throw new N("user token is expired \u2014 re-authenticate and retry");let O=await this.cache.keyFor(ar(l),i);if(O===void 0)throw new N(`user token kid ${JSON.stringify(i)} is not in the WorkOS issuer's JWKS`);let P=Buffer.from(`${n}.${r}`,"ascii"),c=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(!Qt(P,c,O))throw new N("user token signature failed verification");if(m<=Math.floor(this.now()/1e3))throw new N("user token is expired \u2014 re-authenticate and retry");return{apiKey:e,orgId:h,credential:"user",subject:f}}},lr=5e3,cr=1500,dr=4096,z=class extends Error{status=403;detail;constructor(e,n){super(e),this.name="MembershipRefusalError",this.detail=n}};function Vt(){return new z("this account is not an active member of the organization \u2014 the membership may have been removed; sign out and sign back in")}var Ge=class{constructor(e){this.opts=e;this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now,this.timeoutMs=e.timeoutMs??cr}opts;cache=new Map;fetchImpl;now;timeoutMs;async assertActive(e,n){if(n==="")throw new z("the user token carries no subject \u2014 organization membership cannot be confirmed");let r=`${e}\0${n}`,s=this.cache.get(r);if(s!==void 0&&this.now()-s.at<lr){if(!s.active)throw Vt();return}let o=!1,a;try{let i=await this.fetchImpl(`${this.opts.url}/membership-check`,{method:"POST",headers:{authorization:`Bearer ${this.opts.token}`,"content-type":"application/json"},body:JSON.stringify({org_id:e,subject:n}),signal:AbortSignal.timeout(this.timeoutMs)});if(i.status!==200)a=`membership-check answered HTTP ${i.status}`;else try{let l=await i.json();l===null||typeof l!="object"||Array.isArray(l)||!("active"in l)||typeof l.active!="boolean"?a="membership-check answered a malformed body (expected {active: boolean})":o=l.active}catch(l){a=`membership-check answered a body that is not JSON (${l instanceof Error?l.message:String(l)})`}}catch(i){a=`membership-check failed (${i instanceof Error?i.message:String(i)})`}if(a!==void 0)throw new z("organization membership for this account could not be confirmed \u2014 try again shortly",a);if(this.cache.size>=dr){let i=this.cache.keys().next();i.done||this.cache.delete(i.value)}if(this.cache.set(r,{active:o,at:this.now()}),!o)throw Vt()}},we=class{verifier;bindings;memberGate;warnedGateDisabled=!1;constructor(e){this.verifier=new Fe({issuers:e.issuers,...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.now!==void 0?{now:e.now}:{}}),this.bindings=new re({gatewayUrl:e.gatewayUrl,credential:"user",...e.now!==void 0?{now:e.now}:{},...e.mint!==void 0?{mint:e.mint}:{}}),this.memberGate=e.memberGate!==void 0?new Ge(e.memberGate):null}accepts(e){return this.verifier.accepts(e)}async resolve(e){let n=await this.verifier.verify(e);this.memberGate!==null?await this.memberGate.assertActive(n.orgId,n.subject):this.warnedGateDisabled||(this.warnedGateDisabled=!0,process.stderr.write(`[member-gate] member gate disabled \u2014 removed-member window remains open
|
|
4
4
|
`));let r=await this.bindings.resolve(n.apiKey);if(r.orgId!==n.orgId)throw new N("the control plane bound this user token to a different org than its org_id claim \u2014 refusing to route a request whose two sources of tenancy disagree");return{apiKey:n.apiKey,orgId:n.orgId,credential:"user",...r.billingAudience!==void 0?{billingAudience:r.billingAudience}:{},...r.creditsAdmissionOk!==void 0?{creditsAdmissionOk:r.creditsAdmissionOk}:{},...r.creditsRefusalReason!==void 0?{creditsRefusalReason:r.creditsRefusalReason}:{}}}};function Be(t,e,n,r){if(Yt(t)){if(r!==null&&r.accepts(t))return r.resolve(t);if(n!==null)return n.verify(t)}return e.resolve(t)}T();var ur=8080,Ke="serve",Qs="0.0.0.0";function fr(t,e,n){let r=(t[e]??"").trim();if(!r)throw new Error(`${e} is not set \u2014 ${n}`);return r}function Xs(t=process.env){let e=(t.PORT??"").trim(),n=e===""?ur:Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`PORT must be an integer in 0..65535, got ${JSON.stringify(e)}`);let r=gt(ce(fr(t,"URUN_BASE_URL","the hosted proxy needs the uRun session-gateway base it opens sessions and verifies API keys against (e.g. https://api.urun.sh)"),"URUN_BASE_URL")),s=(t.URUN_API_URL??"").trim(),o=s?ce(s,"URUN_API_URL"):`${r.replace(/\/+$/,"")}/v1`,a=(t.URUN_CATALOG_URL??"").trim(),i=(t.URUN_CATALOG_ANON_KEY??"").trim();if(!!a!=!!i)throw new Error("URUN_CATALOG_URL and URUN_CATALOG_ANON_KEY must be set together (or both left unset) \u2014 exactly one of them is set, which would silently disable the model-catalog oracle");let l=a?{catalogUrl:ce(a,"URUN_CATALOG_URL"),anonKey:i}:null,h=(t.URUN_LEDGER_SIGNING_KEY??"").trim(),f=(t.URUN_LEDGER_SIGNING_KEY_ID??"").trim();if(!!h!=!!f)throw new Error("URUN_LEDGER_SIGNING_KEY and URUN_LEDGER_SIGNING_KEY_ID must be set together (or both left unset) \u2014 exactly one of them is set, which would half-configure the ENG-410 ledger row signature");let m=h?{keyId:f,key:h}:void 0,O={docHostUrl:(t.URUN_LANE_DOC_HOST_URL??"").trim(),valkeyUrl:(t.URUN_LANE_VALKEY_URL??"").trim(),tokenSecret:(t.URUN_SESSION_TOKEN_SECRET??"").trim(),selfAddress:(t.URUN_LANE_SELF_ADDRESS??"").trim()},P=["URUN_LANE_DOC_HOST_URL","URUN_LANE_VALKEY_URL","URUN_SESSION_TOKEN_SECRET","URUN_LANE_SELF_ADDRESS"],c=P.filter((v,A)=>Object.values(O)[A]==="");if(c.length!==0&&c.length!==P.length)throw new Error(`${P.join(", ")} must be set together (or all left unset) \u2014 missing: ${c.join(", ")}, which would half-configure the lane plane`);let y=c.length===0?O:void 0,_={baseUrl:(t.URUN_POOLER_URL??"").trim(),token:(t.URUN_POOLER_TOKEN??"").trim(),region:(t.URUN_POOLER_REGION??"").trim()},k=["URUN_POOLER_URL","URUN_POOLER_TOKEN","URUN_POOLER_REGION"],g=k.filter((v,A)=>Object.values(_)[A]==="");if(g.length!==0&&g.length!==k.length)throw new Error(`${k.join(", ")} must be set together (or all left unset) \u2014 missing: ${g.join(", ")}, which would half-configure the pooler cutover`);let E=g.length===0?_:void 0,p={jwksBaseUrl:(t.URUN_MACHINE_JWKS_BASE_URL??"").trim(),issuers:(t.URUN_MACHINE_ISSUERS??"").trim(),tokenTtlS:(t.URUN_MACHINE_TOKEN_TTL_S??"").trim()},d=["URUN_MACHINE_JWKS_BASE_URL","URUN_MACHINE_ISSUERS","URUN_MACHINE_TOKEN_TTL_S"],S=d.filter((v,A)=>Object.values(p)[A]==="");if(S.length!==0&&S.length!==d.length)throw new Error(`${d.join(", ")} must be set together (or all left unset) \u2014 missing: ${S.join(", ")}, which would half-configure the machine-identity rung`);let R=p.issuers.split(",").map(v=>v.trim()).filter(v=>v!=="");if(R.length===0&&S.length===0)throw new Error("URUN_MACHINE_ISSUERS resolved to no issuer URNs \u2014 set at least one (e.g. urn:urun:machine-issuer:prod-usw2)");let w=Number(p.tokenTtlS);if(S.length===0&&(!Number.isFinite(w)||w<=0))throw new Error(`URUN_MACHINE_TOKEN_TTL_S must be a positive number of seconds, got ${JSON.stringify(p.tokenTtlS)}`);let I=S.length===0?{jwksBaseUrl:p.jwksBaseUrl,issuers:R,tokenTtlS:w}:void 0,U=(t.URUN_WORKOS_ISSUERS??"").trim(),$=U.split(",").map(v=>v.trim()).filter(v=>v!=="");if(U!==""&&$.length===0)throw new Error("URUN_WORKOS_ISSUERS resolved to no issuer URLs \u2014 set at least one (e.g. https://api.workos.com/user_management/client_01KNNB76YVGNH78X98A1X3S56C)");for(let v of $){let A;try{A=new URL(v)}catch{throw new Error(`URUN_WORKOS_ISSUERS entry is not a URL: ${JSON.stringify(v)}`)}if(A.protocol!=="https:")throw new Error(`URUN_WORKOS_ISSUERS entry must be https (got ${v}) \u2014 the issuer is the user rung's trust root`)}let u=(t.URUN_CONTROL_PLANE_URL??"").trim(),b=(t.URUN_CONTROL_PLANE_TOKEN??"").trim(),L=u!==""&&b!==""?{url:u.replace(/\/+$/,""),token:b}:void 0;return{port:n,baseUrl:r,apiUrl:o,catalog:l,ledgerSigning:m,lane:y,pooler:E,machine:I,memberGate:L,...$.length>0?{userIssuers:$}:{}}}T();import{createHash as hr,randomUUID as Xt}from"crypto";var pr=512;function ve(t){return`urun-inference-proxy-${hr("sha256").update(t).digest("hex").slice(0,32)}`}var _e=class{constructor(e){this.opts=e}opts;tenants=new Map;label(e,n,r){let s=Object.assign(Object.create(e),{tenant:n.orgId}),o=this.opts.pooler;if(o===void 0)return s;let a=this.opts.lanes;return Object.assign(Object.create(s),{createResponse:async(i,l)=>{if(a!==void 0&&r!==void 0&&(await r.resolveTargetFor(i.model).catch(()=>null))?.sharedApp)return await s.createResponse(i,l);let h=`px_${Xt()}`;return Ct(o,i,h,h)}})}build(e){if(this.opts.build){let o=this.opts.build(e);return o.decision&&this.ensureDecisionReaper(),{router:o.router,clients:this.label(o.clients,e,o.router),decision:o.decision}}let n={baseUrl:this.opts.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ke,sharedOnlyListing:!0,apiUrl:this.opts.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:this.opts.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:this.opts.baseUrl},catalog:this.opts.catalogRows?null:this.opts.catalog,catalogRows:this.opts.catalogRows,lanes:this.opts.lanes,release:"end",decisionPool:xt(process.env,process.env.HOSTNAME)??void 0},r=De(n),s=n.decisionPool?Mt(n,r):null;return s&&this.ensureDecisionReaper(),{router:r,clients:this.label(He(r,void 0,void 0,s??void 0,void 0,this.opts.lanes),e,r),decision:s??void 0}}ensureDecisionReaper(){if(this.decisionReaper!==null)return;let e=setInterval(()=>{for(let n of this.tenants.values())n.decision?.reap()},5e3);e.unref(),this.decisionReaper=e}decisionReaper=null;clientsFor(e){let n=this.tenants.get(e.apiKey);if(n)return this.tenants.delete(e.apiKey),this.tenants.set(e.apiKey,n),n.clients;for(;this.tenants.size>=pr;){let s=this.tenants.entries().next();if(s.done)break;let[o,a]=s.value;this.tenants.delete(o),a.router.closeAll().catch(()=>{})}let r=this.build(e);return this.tenants.set(e.apiKey,r),r.clients}get size(){return this.tenants.size}*decisionPools(){for(let e of this.tenants.values())e.decision&&(yield e.decision)}decisionWarmerFor(e){return this.clientsFor(e),this.tenants.get(e.apiKey)?.decision??null}async closeAll(){this.decisionReaper!==null&&(clearInterval(this.decisionReaper),this.decisionReaper=null);let e=[...this.tenants.values()];this.tenants.clear();let n=[];if(await Promise.all(e.map(async r=>{let s=[r.router.closeAll().catch(o=>{n.push(String(o instanceof Error?o.message:o))})];r.decision&&s.push(r.decision.close().catch(o=>{n.push(String(o instanceof Error?o.message:o))})),await Promise.all(s)})),n.length>0)throw new Error(`failed to close ${n.length} tenant backhaul(s): ${n.join("; ")}`)}},Zt=512,gr=1024,je=class extends Error{constructor(){super(`conversation capacity reached (${Zt} conversations on this replica) \u2014 every slot holds an active or resumable conversation; retry later or scale out`),this.name="ConversationCapacityError"}};function mr(t,e){return{sessionStartOptions:n=>{if(e!==void 0&&!n.startsWith(ae))return{concurrencyKey:e};if(n.startsWith(ae)||n.startsWith(xe))return;let r=t.get(n);return r===void 0?void 0:{sessionId:r}},onSessionOpen:(n,r)=>{n.startsWith(ae)||n.startsWith(xe)||t.set(n,r)}}}function yr(t,e,n,r,s){let o=De({baseUrl:t.baseUrl,orgId:e.orgId,defaultApp:null,fnName:Ke,sharedOnlyListing:!0,apiUrl:t.apiUrl,auth:e.credential==="machine"?{lane:"machine",machineToken:e.apiKey,gatewayUrl:t.baseUrl}:e.credential==="user"?{lane:"user",userToken:e.apiKey,gatewayUrl:t.baseUrl}:{lane:"api-key",apiKey:e.apiKey,gatewayUrl:t.baseUrl},catalog:t.catalogRows?null:t.catalog,catalogRows:t.catalogRows,lanes:t.lanes,subject:n.subject,release:"detach",...mr(r,s)});return{clients:He(o,void 0,void 0,void 0,void 0,t.lanes),release:async()=>{await o.closeAll()}}}var Se=class{constructor(e){this.opts=e}opts;byCaller=new Map;byHandle=new Map;build(e,n,r){let s={id:n,subject:r!==void 0?`${ve(e.apiKey)}:live`:`${ve(e.apiKey)}:live:${n}`},o=new Map,a=this.opts.build?this.opts.build(e,s):yr(this.opts,e,s,o,r);return{id:n,backhaul:a,attachments:0,nativeRefs:o}}attachEntry(e,n,r){let s=this.byCaller.get(e.apiKey);s===void 0&&(s=new Map,this.byCaller.set(e.apiKey,s));let o=s.get(n);if(o!==void 0)return s.delete(n),s.set(n,o),o.attachments+=1,o;this.evictOverflow();let a=this.build(e,n,r);return a.attachments=1,s.set(n,a),a}get conversationCount(){let e=0;for(let n of this.byCaller.values())e+=n.size;return e}evictOverflow(){for(;this.conversationCount>=Zt;){let e=!1;for(let[n,r]of this.byCaller){for(let[s,o]of r)if(!(o.attachments>0)){r.delete(s),this.dropHandleIndexFor(n,s),o.backhaul.release().catch(()=>{}),e=!0;break}if(r.size===0&&this.byCaller.delete(n),e)break}if(!e)throw new je}}dropHandleIndexFor(e,n){for(let[r,s]of this.byHandle)s.apiKey===e&&s.conversationId===n&&this.byHandle.delete(r)}connectionFor(e,n){let r=null,s=!1,o=()=>(r===null&&(r=this.attachEntry(e,Xt(),n)),r),a={createResponse:(i,l)=>o().backhaul.clients.createResponse(i,l),catalogIdentity:i=>o().backhaul.clients.catalogIdentity(i),servingAppSlug:i=>{let l=o().backhaul.clients.servingAppSlug;if(l===void 0)throw new Error("the conversation backhaul wires no servingAppSlug seam \u2014 the caller-org app a request resolves to cannot be known");return l(i)},listModels:()=>o().backhaul.clients.listModels(),sessionHandle:i=>o().backhaul.clients.sessionHandle(i),dedicatedSessionHandle:i=>{let l=o().backhaul.clients.dedicatedSessionHandle;return l===void 0?o().backhaul.clients.sessionHandle(i):l(i)},releaseSessionHandle:i=>o().backhaul.clients.releaseSessionHandle?.(i),endDedicatedSession:i=>o().backhaul.clients.endDedicatedSession?.(i),touchSessionPresence:(i,l)=>o().backhaul.clients.touchSessionPresence?.(i,l),detachSessionPresence:(i,l)=>o().backhaul.clients.detachSessionPresence?.(i,l),createResponseOn:(i,l,h)=>o().backhaul.clients.createResponseOn(i,l,h),onSessionEnd:(i,l)=>o().backhaul.clients.onSessionEnd(i,l)};return a.openAudio=async(i,l)=>{let h=o().backhaul.clients.openAudio;if(h===void 0)throw new Error("the conversation backhaul wires no openAudio seam \u2014 voice is unavailable on this deployment");return h(i,l)},a.openVideo=async i=>{let l=o().backhaul.clients.openVideo;if(l===void 0)throw new Error("the conversation backhaul wires no openVideo seam \u2014 video-in is unavailable on this deployment");return l(i)},a.openVideoOut=async i=>{let l=o().backhaul.clients.openVideoOut;if(l===void 0)throw new Error("the conversation backhaul wires no openVideoOut seam \u2014 video-out is unavailable on this deployment");return l(i)},a.supportsAudio=async i=>{let l=o().backhaul.clients.supportsAudio;if(l===void 0)throw new Error("the conversation backhaul wires no supportsAudio seam \u2014 the realtime lane cannot gate audio modality on this deployment");return l(i)},a.supportsSpeech=async i=>{let l=o().backhaul.clients.supportsSpeech;if(l===void 0)throw new Error("the conversation backhaul wires no supportsSpeech seam \u2014 the speech lane cannot gate model capability on this deployment");return l(i)},a.speechVoices=async i=>{let l=o().backhaul.clients.speechVoices;if(l===void 0)throw new Error("the conversation backhaul wires no speechVoices seam \u2014 the speech lane cannot resolve the voice set /v1/models publishes on this deployment");return l(i)},a.speechSessionHandle=async i=>{let l=o().backhaul.clients.speechSessionHandle;if(l===void 0)throw new Error("the conversation backhaul wires no speechSessionHandle seam \u2014 the speech lane cannot resolve its own pooled session on this deployment");return l(i)},a.openAudioOn=async(i,l,h)=>{let f=o().backhaul.clients.openAudioOn;if(f===void 0)throw new Error("the conversation backhaul wires no openAudioOn seam \u2014 the speech and realtime lanes cannot open their pinned native session audio on this deployment");return f(i,l,h)},a.openVideoOn=async(i,l)=>{let h=o().backhaul.clients.openVideoOn;if(h===void 0)throw new Error("the conversation backhaul wires no openVideoOn seam \u2014 the realtime lane cannot open its pinned native video frame lane on this deployment");return h(i,l)},a.openTurnsOn=(i,l)=>{let h=o().backhaul.clients.openTurnsOn;if(h===void 0)throw new Error("the conversation backhaul wires no openTurnsOn seam \u2014 the realtime transcription lane cannot open the backend turn/transcript lane on this deployment");return h(i,l)},a.evictSpeechSession=async i=>{let l=o().backhaul.clients.evictSpeechSession;if(l===void 0)throw new Error("the conversation backhaul wires no evictSpeechSession seam \u2014 the speech lane cannot retire its pinned speech session after a failed turn on this deployment");return l(i)},a.supportsTranscription=async i=>{let l=o().backhaul.clients.supportsTranscription;if(l===void 0)throw new Error("the conversation backhaul wires no supportsTranscription seam \u2014 the transcription lane cannot gate model capability on this deployment");return l(i)},a.transcriptStreamFor=async i=>{let l=o().backhaul.clients.transcriptStreamFor;if(l===void 0)throw new Error("the conversation backhaul wires no transcriptStreamFor seam \u2014 the realtime transcription lane cannot verify the model's engine_args.transcript_stream on this deployment");return l(i)},a.listSpeechToTextModels=async()=>{let i=o().backhaul.clients.listSpeechToTextModels;if(i===void 0)throw new Error("the conversation backhaul wires no listSpeechToTextModels seam \u2014 the transcription lane cannot list the stt models on this deployment");return i()},{clients:a,bindResumeHandle:i=>{let l=r;if(l===null)throw new Error("bindResumeHandle before the conversation opened \u2014 no conversation to bind to");for(;this.byHandle.size>=gr;){let h=this.byHandle.keys().next();if(h.done)break;this.byHandle.delete(h.value)}this.byHandle.set(i,{apiKey:e.apiKey,conversationId:l.id})},clientsForResume:async i=>{let l=this.byHandle.get(i),h=l===void 0?void 0:this.byCaller.get(l.apiKey),f=l===void 0||h===void 0?void 0:h.get(l.conversationId);if(l===void 0||f===void 0||l.apiKey!==e.apiKey)throw new ie("the conversation behind this resume handle is gone (evicted at capacity, or the replica restarted) or the handle is not yours \u2014 reconnect without a handle to start a new conversation");return r=f,f.attachments+=1,f.backhaul.clients},release:async()=>{if(s)return;s=!0;let i=r;r=null,i!==null&&(i.attachments-=1,!(i.attachments>0)&&await i.backhaul.release().catch(()=>{}))}}}async detachAll(){let e=[];for(let r of this.byCaller.values())for(let s of r.values())e.push(s.backhaul.release());this.byCaller.clear(),this.byHandle.clear();let n=[];if(await Promise.all(e.map(async r=>{try{await r}catch(s){n.push(String(s instanceof Error?s.message:s))}})),n.length>0)throw new Error(`failed to detach ${n.length} conversation backhaul(s): ${n.join("; ")}`)}};T();var wr="/inference-ledger",br=1e4,ke=class extends Error{ledgerFailureReason;constructor(e,n="duplicate"){super(e),this.name="LedgerDuplicateError",this.ledgerFailureReason=n}},qe=class extends Error{constructor(n,r){super(r);this.ledgerAlreadyWritten=n;this.name="LedgerAlreadyWrittenError"}ledgerAlreadyWritten},H=class extends Error{ledgerFailureReason="surface";constructor(e){super(e),this.name="LedgerSurfaceError"}},Ve=class extends N{ledgerFailureReason="auth";constructor(e){super(e),this.name="LedgerAuthError"}},Ye=class extends Error{ledgerFailureReason="ledger_signature_invalid";constructor(e){super(e),this.name="LedgerSignatureError"}},vr=[["inference_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["model_id",t=>typeof t=="string"&&/[^\s]/.test(t)],["variant",t=>t===null||typeof t=="string"],["task",t=>typeof t=="string"&&/[^\s]/.test(t)],["http_status",t=>typeof t=="number"&&Number.isInteger(t)],["started_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["completed_at",t=>typeof t=="string"&&!Number.isNaN(Date.parse(t))],["prompt_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["completion_tokens",t=>t===null||typeof t=="number"&&Number.isInteger(t)],["output_units",Je],["output_minutes",Je],["cost_nano_usd",Je],["price_version",t=>t===null||typeof t=="string"]];function _r(t){for(let[e,n]of vr){if(!(e in t))return`${e} (absent)`;if(!n(t[e]))return`${e} (${JSON.stringify(t[e])})`}return null}function Sr(t){let e;try{e=JSON.parse(t)}catch{return{status:"unavailable"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"unavailable"};let n=e.existing_status;if(n==="not_in_this_org")return{status:"not_in_this_org"};if(n!=="found")return{status:"unavailable"};let r=e.existing;return r===null||typeof r!="object"||Array.isArray(r)?{status:"unavailable"}:_r(r)!==null?{status:"unavailable"}:{status:"found",row:r}}function Je(t){return t===null?!0:typeof t=="number"?Number.isFinite(t):typeof t!="string"?!1:/[^\s]/.test(t)&&Number.isFinite(Number(t))}function ze(t,e){return t===null?e===null:e===null?!1:Number(e)===t}function kr(t,e){return t===null?e===null:e===null?!1:Number(t.toFixed(9))===Number(e)}function en(t,e){if(typeof e!="string")return!1;let n=Date.parse(t),r=Date.parse(e);return Number.isFinite(n)&&Number.isFinite(r)&&n===r}function Er(t,e){let n=e;return n.inference_id===t.inference_id&&n.model_id===t.model_id&&(n.variant??null)===t.variant&&n.task===t.task&&n.http_status===t.http_status&&en(t.started_at,n.started_at)&&en(t.completed_at,n.completed_at)&&ze(t.prompt_tokens,n.prompt_tokens)&&ze(t.completion_tokens,n.completion_tokens)&&ze(t.output_units,n.output_units)&&kr(t.output_minutes,n.output_minutes)}function Rr(t){let e=r=>String(r??null),n="session_seconds"in t?t.session_seconds:null;return["urun-ledger-write-v2",t.inference_id,t.model_id,e(t.variant),t.identity_kind,t.task,e(t.prompt_tokens),e(t.completion_tokens),e(t.output_units),e(t.output_minutes),e(t.output_seconds),e(n),t.started_at,t.completed_at].join(`
|
|
@@ -205,7 +205,7 @@ interface InferenceRecord {
|
|
|
205
205
|
*/
|
|
206
206
|
|
|
207
207
|
/** The turn kinds the transcribe bridge emits (TranscriptEvent kinds). */
|
|
208
|
-
type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
|
|
208
|
+
type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
|
|
209
209
|
/**
|
|
210
210
|
* One decoded transcript-lane event — the `RealtimeBinding.turns` event
|
|
211
211
|
* shape. `text` is the wire `delta` field (a transcript PIECE — the adapter
|
|
@@ -65,7 +65,7 @@ interface InferenceRecord {
|
|
|
65
65
|
readonly catalog: TurnCatalogIdentity;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_eager_end' | 'turn_resumed';
|
|
68
|
+
type SessionTurnKind = 'delta' | 'final' | 'turn_start' | 'turn_end' | 'turn_dropped' | 'turn_eager_end' | 'turn_resumed';
|
|
69
69
|
|
|
70
70
|
interface SessionTurnLaneEvent {
|
|
71
71
|
kind: SessionTurnKind;
|