@urun-sh/openai 0.6.44 → 0.6.46
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-BA3NCMS5.js → chunk-2AFSBZLN.js} +1 -1
- package/dist/{chunk-J3KCHTSA.js → chunk-CUO2JOW4.js} +5 -5
- package/dist/{chunk-Y774TOE7.js → chunk-MJGUEL2U.js} +1 -1
- package/dist/chunk-NCKEKCTI.js +4 -0
- package/dist/{chunk-G6AFKOVS.js → chunk-PXV7QBSD.js} +1 -1
- package/dist/{chunk-HB5KNEY5.js → chunk-Q3AIBMET.js} +1 -1
- package/dist/chunk-U6TUJPC3.js +66 -0
- package/dist/{chunk-FNAZ2XBE.js → chunk-UOQP3DBT.js} +6 -6
- package/dist/{chunk-MJSK6W3W.js → chunk-WWFK27D2.js} +1 -1
- package/dist/{composite-DNNAm0PY.d.ts → composite-D0ivH65M.d.ts} +14 -0
- package/dist/{composite-DM2sT1Sp.d.cts → composite-QilJ-Faj.d.cts} +57 -0
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +11 -0
- package/dist/gemini-live.d.ts +2 -0
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +47 -47
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +42 -42
- 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/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +54 -54
- package/dist/pooler/bin.cjs +5 -5
- package/dist/pooler/bin.js +1 -1
- package/dist/proxy/cli.cjs +52 -52
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.cjs +32 -32
- package/dist/proxy/index.d.cts +34 -3
- package/dist/proxy/index.d.ts +10 -3
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-DMRZZTYI.js +0 -4
- package/dist/chunk-VQSCBUKT.js +0 -66
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as m}from"./chunk-
|
|
1
|
+
import{h as m}from"./chunk-CUO2JOW4.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.46";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,6 +1,6 @@
|
|
|
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 $e(n,e){let t=typeof n=="number"?n:typeof n=="string"&&n.trim()!==""?Number(n):NaN;if(!Number.isFinite(t)||t<0)throw new _(`${e}: price_usd is not a non-negative number (${JSON.stringify(n)})`);return t}function 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 Te(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:$e(i.price_usd,r),effective_at:Z(i.effective_at,r,"effective_at"),expires_at:Te(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 O(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===e);if(o)return o.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===null);return r?r.pricing:null}var E={prices:[],refusals:[]};async function rt(n){let e=n.fetchImpl??fetch,t=`${j},${U}`,o=await e(`${n.catalogUrl}/model_prices?select=${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 Oe(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 Ee(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 Ae(n){if(!n)return null;let e=n.split("@")[0],t=e.indexOf("/"),o=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<o.length;r+=1){let i=o[r];if(Object.hasOwn(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 Ie=["context_length","max_model_len"];function Me(n){let e=Ie.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 A(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return A(o);let r=K(n,e);return r.length>0?A(r):null}function A(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e: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 $=class extends Error{name="ModelCreatedError"};function T(n){if(n.length===0)return 0;let e=`${n[0].model_id}:${n[0].variant}`,t=n.map(u=>u.created_at??void 0);if(t.some(u=>u===void 0))throw new $(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let o=t[0];if(!t.every(u=>u===o))throw new $(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(t)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(r===null)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let i=Number(r[1]),s=Number(r[2]),d=Number(r[3]),a=Date.UTC(i,s-1,d),l=new Date(a);if(l.getUTCFullYear()!==i||l.getUTCMonth()!==s-1||l.getUTCDate()!==d)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 not a real calendar date`);return a/1e3}function b(n){let e={id:n.id,object:n.object,created:n.created,owned_by:n.owned_by,...n.context_length!==void 0?{context_length:n.context_length}:{},...n.pricing!==void 0?{pricing:n.pricing}:{},...n.voices!==void 0?{voices:n.voices}:{},...n.capabilities!==void 0?{capabilities:n.capabilities}:{}};return"image_modes"in n?{...e,image_modes:n.image_modes}:e}function 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=T(i),a=O(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?A(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=A(e);if(!r)return null;let{row:i,matches:s}=r;if(!i.task||Ce[i.task]!==!0)return null;let d=N(s),a=O(i.model_id,i.variant,t),l=Ae(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:T(s),quantization:Oe(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&a!==null,is_free:!1,input_modalities:[{type:"text",...d!==null?{supported_inputs:{max_context_length:{value:d,unit:"token"}}}:{},...a?{pricing: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:Ee(n?.regions,r),compliance:n?.compliance??null},d=[],a=new Set;for(let l of i){let u=`${l.model_id}:${l.variant}`;if(a.has(u))continue;a.add(u);let c=je(l,e.filter(g=>g.model_id===l.model_id&&g.variant===l.variant),t,s);c&&d.push(c)}return{data:d}}w();var 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{},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 St(n){let e=n.fetchImpl??fetch,t=`${n.apiUrl.replace(/\/+$/,"")}/apps`,o=await e(t,{headers:{Authorization:`Bearer ${n.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${t} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${t})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${t} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}function 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 E(n,e,t){if(t.refusals.some(i=>i.model_id===n&&i.variant===e))return null;let o=t.prices.find(i=>i.model_id===n&&i.variant===e);if(o)return o.pricing;if(t.refusals.some(i=>i.model_id===n&&i.variant===null))return null;let r=t.prices.find(i=>i.model_id===n&&i.variant===null);return r?r.pricing:null}var I={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 Ee(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 Ie(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 Oe(n){if(!n)return null;let e=n.split("@")[0],t=e.indexOf("/"),o=(t===-1?e:e.slice(t+1)).toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>0);for(let r=0;r<o.length;r+=1){let i=o[r];if(Object.hasOwn(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 Le(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return O(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return O(o);let r=K(n,e);return r.length>0?O(r):null}function O(n){let e=n[0];return n.every(o=>o.model_id===e.model_id&&o.variant===e.variant)?{row:n.length===1?e:Fe(n),matches:n}:null}function Fe(n){let e=n[0],t=o=>n.every(r=>(r[o]??void 0)===(e[o]??void 0))?e[o]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),updated_at:t("updated_at")}}var 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 L(n,e,t){let o=Le(n,e);if(!o)return b({id:n,object:"model",created:0,owned_by:"urun"});let{row:r,matches:i}=o,s=N(i),d=$(i),a=E(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?O(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=O(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=E(i.model_id,i.variant,t),l=Oe(i.hf_repo),u={temperature:{type:"range",min:0,max:2},top_p:{type:"range",min:0,max:1},stop:{type:"array",max_items:4}};return d!==null&&(u.max_tokens={type:"integer",min:1,max:d,unit:"token"}),{schema_version:"2.4",id:`${i.model_id}:${i.variant}`,name:`${i.model_id}:${i.variant}`,created:$(s),quantization:Ee(i.variant),...l!==null?{tokenizer:l}:{},description:i.description??"",hugging_face_id:i.hf_repo?i.hf_repo.split("@")[0]??i.hf_repo:"",is_ready:n.ready===!0&&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:Ie(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)}
|
|
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
|
-
`),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
|
|
4
|
-
`),
|
|
5
|
-
`);return o}outputFreeKeys(e){let t=new Set;if(!e)return t;for(let o of e.endpoints)o.output_free===!0&&t.add(J(o.model_id,o.variant));return t}warn(e){(this.opts.warn??(o=>console.warn(o.trimEnd())))(e)}servable(e){return e.filter(t=>t.serves==="openai"&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=this.opts.defaultApp,t=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())r.startsWith(we)||r.startsWith(me)||t.add(r);let o=[...t].filter(r=>r!==e).sort();return e===null?o:[e,...o]}async noDefaultApp(e){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new P(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${o}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${o}`)}async sharedLane(e){if(!this.opts.shared)return null;let t=await this.sharedBlock();if(!t)return null;let o=D(t,e);if(o)return o;let r=e.lastIndexOf(":"),i=r>0?e.slice(0,r):e,s=r>0?e.slice(r+1):void 0,d=h(i),a=t.endpoints.filter(c=>h(c.model_id)===d&&(s===void 0||c.variant===s)),l=new Set(a.map(c=>c.model_id)),u=[...l][0];return u===void 0||l.size!==1?null:D(t,u,s)}async resolveTarget(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):{appSlug:o};let r=h(t);if(r===o)return{appSlug:o};let i=await this.sharedLane(t);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:i.shared_org_id,gpuSpec:i.endpoint.gpu_spec??void 0,appId:i.endpoint.app_id??void 0};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let s=await this.deployedApps(),d=this.servable(s);if(d.includes(r))return{appSlug:r};let a=d.filter(u=>u.startsWith(`${r}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=s.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(l)throw new P(`model "${t}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let d=(await this.opts.listCatalog()).find(a=>t===a.model_id||t===`${a.model_id}:${a.variant}`||r===h(a.model_id)||r===h(`${a.model_id}-${a.variant}`));if(d)throw new P(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${d.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):{appSlug:o}}async catalogIdentityFor(e){let t=G(await this.resolveTarget(e));return t.kind==="catalog"?{model_id:t.model_id,variant:t.variant}:null}async poolTuningFor(e){return He(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return q(await this.resolveTarget(e))}async sessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,q(t))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return G(await this.resolveTarget(e))}async speechSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,me+q(t))}async dedicatedSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,qe+Ke())}async evictHandle(e){let t=ge(e);if(!t)return;let o=this.pool.get(t.app);if(!o)return;let r=await o.then(i=>i,()=>null);r!==null&&await this.evict(t.app,r)}async acquire(e,t){let o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(e,t)),this.pool.set(t,o),o.then(r=>this.snapshotMintId(r),()=>{}),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o,identity:G(e)}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(e);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(e){let{app:t,entry:o}=await this.sessionFor(e);return{app:t,handle:pe(t,this.keyOf(o))}}async speechHandleFor(e){let{app:t,entry:o}=await this.speechSessionFor(e);return{app:t,handle:pe(t,this.keyOf(o))}}async sessionForHandle(e){let t=ge(e);if(!t)throw new M(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,i=this.pool.get(o),s=i?await i.then(d=>d,()=>null):null;if(s===null)throw new M(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(s)!==r&&this.mintedIds.get(s)!==r)throw new M(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:s}}async evict(e,t){let o=this.pool.get(e);!o||await o.then(i=>i,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[o,r]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=o.rows,s=o.ok?r:
|
|
6
|
-
`);let a=(t?S(t):[]).map(l=>{let u=i.filter(Y=>Y.model_id===l.model_id&&Y.variant===l.variant),c=N(u),g
|
|
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 F=6e4,ye=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,t,o){let r=e.current;return r&&Date.now()-r.at<o?r.value:r?(r.refreshing||(r.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{r.refreshing=void 0}})()),r.value):(e.current={at:Date.now(),value:await t()},e.current.value)}seed(e,t){this.snapshotMintId(t),this.pool.set(e,Promise.resolve(t))}snapshotMintId(e){try{let t=this.keyOf(e),o=e;this.mintedIds.has(o)||this.mintedIds.set(o,t)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??F):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??F):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??F):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??F;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let t=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:t},t}async pricesForListing(e){let t;try{t=await this.priceRows()}catch(r){if(r instanceof _)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
|
|
4
|
+
`),I}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}
|
|
5
|
+
`);return o}outputFreeKeys(e){let t=new Set;if(!e)return t;for(let o of e.endpoints)o.output_free===!0&&t.add(J(o.model_id,o.variant));return t}warn(e){(this.opts.warn??(o=>console.warn(o.trimEnd())))(e)}servable(e){return e.filter(t=>t.serves==="openai"&&t.deployment_status==="active").map(t=>t.app_slug)}async availableIds(){let e=this.opts.defaultApp,t=new Set(e===null?[]:[e]);if(this.opts.listApps)for(let r of this.servable(await this.deployedApps()))t.add(r);for(let r of this.pool.keys())r.startsWith(we)||r.startsWith(me)||t.add(r);let o=[...t].filter(r=>r!==e).sort();return e===null?o:[e,...o]}async noDefaultApp(e){let t=await this.availableIds(),o=t.length>0?t.join(", "):"(none deployed)";throw new P(e===""?`no "model" was given and this endpoint has no default model \u2014 name one of your org's deployed apps that declare serves="openai"; available models: ${o}`:`model "${e}" does not name a deployed app in your org that declares serves="openai", and this endpoint has no default model to fall back to; available models: ${o}`)}async sharedLane(e){if(!this.opts.shared)return null;let t=await this.sharedBlock();if(!t)return null;let o=D(t,e);if(o)return o;let r=e.lastIndexOf(":"),i=r>0?e.slice(0,r):e,s=r>0?e.slice(r+1):void 0,d=h(i),a=t.endpoints.filter(c=>h(c.model_id)===d&&(s===void 0||c.variant===s)),l=new Set(a.map(c=>c.model_id)),u=[...l][0];return u===void 0||l.size!==1?null:D(t,u,s)}async resolveTarget(e){let t=(e??"").trim(),o=this.opts.defaultApp;if(!t||t==="urun")return o===null?this.noDefaultApp(t):{appSlug:o};let r=h(t);if(r===o)return{appSlug:o};let i=await this.sharedLane(t);if(i)return{appSlug:i.endpoint.app_slug,fnName:i.endpoint.function,sharedApp:!0,modelId:i.endpoint.model_id,variant:i.endpoint.variant,sharedOrgId:i.shared_org_id,gpuSpec:i.endpoint.gpu_spec??void 0,appId:i.endpoint.app_id??void 0};if(this.pool.has(r))return{appSlug:r};if(this.opts.listApps){let s=await this.deployedApps(),d=this.servable(s);if(d.includes(r))return{appSlug:r};let a=d.filter(u=>u.startsWith(`${r}-`));if(a.length===1)return{appSlug:a[0]};if(a.length>1)throw new P(`model "${t}" is ambiguous across deployed apps ${a.join(", ")} \u2014 name the exact app slug (or catalog id:variant)`);let l=s.find(u=>u.app_slug===r||u.app_slug.startsWith(`${r}-`));if(l)throw new P(`model "${t}" maps to app "${l.app_slug}", which has no function declaring serves="openai" \u2014 add serves="openai" to its @app.function or deploy it with \`urun serve ${t}\`; available models: ${(await this.availableIds()).join(", ")}`)}if(this.opts.listCatalog){let d=(await this.opts.listCatalog()).find(a=>t===a.model_id||t===`${a.model_id}:${a.variant}`||r===h(a.model_id)||r===h(`${a.model_id}-${a.variant}`));if(d)throw new P(`model "${t}" is in the uRun catalog but not deployed \u2014 deploy it with \`urun serve ${d.model_id}\`; available models: ${(await this.availableIds()).join(", ")}`)}return o===null?this.noDefaultApp(t):{appSlug:o}}async catalogIdentityFor(e){let t=G(await this.resolveTarget(e));return t.kind==="catalog"?{model_id:t.model_id,variant:t.variant}:null}async poolTuningFor(e){return He(await this.catalogRows(),e)}async servingAppSlugFor(e){return(await this.resolveTarget(e)).appSlug}async resolveApp(e){return q(await this.resolveTarget(e))}async sessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,q(t))}async resolveTargetFor(e){return this.resolveTarget(e)}async realtimeBillingIdentityFor(e){return G(await this.resolveTarget(e))}async speechSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,me+q(t))}async dedicatedSessionFor(e){let t=await this.resolveTarget(e);return this.acquire(t,qe+Ke())}async evictHandle(e){let t=ge(e);if(!t)return;let o=this.pool.get(t.app);if(!o)return;let r=await o.then(i=>i,()=>null);r!==null&&await this.evict(t.app,r)}async acquire(e,t){let o=this.pool.get(t);return o||(o=Promise.resolve(this.opts.openSession(e,t)),this.pool.set(t,o),o.then(r=>this.snapshotMintId(r),()=>{}),o.catch(()=>this.pool.delete(t))),{app:t,entry:await o,identity:G(e)}}keyOf(e){let t=this.opts.sessionKey;if(!t)throw new Error("ModelRouter: sessionKey is not configured \u2014 the session-identity seam (handleFor/sessionForHandle) is unavailable on this router");let o=t(e);if(typeof o!="string"||o.length===0)throw new Error("ModelRouter: sessionKey returned an empty identity for a pooled session");return o}async handleFor(e){let{app:t,entry:o}=await this.sessionFor(e);return{app:t,handle:pe(t,this.keyOf(o))}}async speechHandleFor(e){let{app:t,entry:o}=await this.speechSessionFor(e);return{app:t,handle:pe(t,this.keyOf(o))}}async sessionForHandle(e){let t=ge(e);if(!t)throw new M(`malformed session handle ${JSON.stringify(e)} \u2014 not issued by this proxy`);let{app:o,key:r}=t,i=this.pool.get(o),s=i?await i.then(d=>d,()=>null):null;if(s===null)throw new M(`the session behind this handle (app "${o}") is gone \u2014 closed, evicted after its pod died, or the proxy restarted; it cannot be reattached. Reconnect without a handle to start a new session.`);if(this.keyOf(s)!==r&&this.mintedIds.get(s)!==r)throw new M(`the session behind this handle (app "${o}") was replaced \u2014 the original backhaul died and a new session serves this app now; the handle's session cannot be reattached. Reconnect without a handle to start a new session.`);return{app:o,entry:s}}async evict(e,t){let o=this.pool.get(e);!o||await o.then(i=>i,()=>null)!==t||this.pool.get(e)!==o||(this.pool.delete(e),await this.opts.closeSession(t).catch(()=>{}))}async modelList(){let e=this.opts.sharedOnlyListing?[]:await this.availableIds(),t=await this.sharedBlock(),[o,r]=await Promise.all([this.catalogRows().then(l=>({ok:!0,rows:l}),()=>({ok:!1,rows:[]})),this.pricesForListing(this.outputFreeKeys(t))]),i=o.rows,s=o.ok?r:I;o.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
|
|
6
|
+
`);let a=(t?S(t):[]).map(l=>{let u=i.filter(Y=>Y.model_id===l.model_id&&Y.variant===l.variant),c=N(u),g=$(u),f=B(u),v=E(l.model_id,l.variant,s),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>L(l,i,s)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[t,o]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return le(e,t,o,r=>this.warn(r))}async supportsImages(e,t){let o=await this.resolveTarget(e),r=await this.catalogRows();if(o.sharedApp){let i=H(String(e),o.modelId,o.variant,r,this.opts.listCatalog!==null);return he(`${o.modelId}:${o.variant}`,i).includes(t)}return fe(W(o.appSlug,r)).includes(t)}async supportsAudio(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))!==null:R(A(t,o))!==null}async supportsSpeech(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="tts":R(A(t,o))==="tts"}async supportsTranscription(e){let t=await this.resolveTarget(e),o=await this.catalogRows();return t.sharedApp?R(o.filter(r=>r.model_id===t.modelId&&r.variant===t.variant))==="stt":R(A(t,o))==="stt"}async transcriptStreamFor(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):A(t,o);return Ye(r)}async speechVoices(e){let t=await this.resolveTarget(e),o=await this.catalogRows(),r=t.sharedApp?o.filter(i=>i.model_id===t.modelId&&i.variant===t.variant):A(t,o);return z(r)}async imageModelList(){let e=await this.catalogRows(),t=I,o=[];for(let i of await this.availableIds()){let s=fe(W(i,e));s.length!==0&&o.push(b({...L(i,e,t),image_modes:s}))}let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null),d=he(`${i.model_id}:${i.variant}`,s);if(d.length===0)continue;let a=b({id:`${i.model_id}:${i.variant}`,object:"model",created:$(s),owned_by:"urun",image_modes:d});o.push(a)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=I,o=[];for(let i of await this.availableIds())R(_e(i,e))==="stt"&&o.push(L(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(s)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:$(s),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,Qe as b,Xe as c,rt as d,dt as e,T as f,pt as g,bt as h,P as i,M as j,St as k,Tt as l,pe as m,ge as n,$t as o,He as p,me as q,qe as r,q as s,G as t,ye as u};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as D}from"./chunk-
|
|
1
|
+
import{c as D}from"./chunk-2AFSBZLN.js";import{c as C}from"./chunk-YSFSRI3D.js";C();import{createClientToken as U}from"@urun-sh/core";import{Queue as H}from"bullmq";import{randomUUID as I}from"crypto";var M=3e4;var V=1e3,G=12e4;function v(n){let s;try{s=JSON.parse(n)}catch{return null}if(typeof s!="object"||s===null||!("proxy_url"in s))return null;let t=s;return typeof t.proxy_url!="string"||t.proxy_url===""?null:{proxy_url:t.proxy_url,occupant_id:typeof t.occupant_id=="string"?t.occupant_id:"",capacity:typeof t.capacity=="number"?t.capacity:0,heartbeat_ms:typeof t.heartbeat_ms=="number"?t.heartbeat_ms:0,...typeof t.region=="string"&&t.region!==""?{region:t.region}:{}}}var P=class extends Error{};async function O(n,s){let t;try{await Promise.race([n,new Promise(c=>{t=setTimeout(c,Math.max(0,s))})])}finally{clearTimeout(t)}}function X(n){let s=n.now??Date.now,t=new Map,c=new Map,h=new Map,u=new Map,_=new Map,y=new Map,b=new Map,f=new Set,w=e=>{let a=t.get(e);return a||(a=n.queueFor?.(e)??S(e),t.set(e,a)),a},S=e=>{let a=n.redis,m=new H(e,{prefix:"bull:dispatch",connection:a});return{reassertWaiting:async p=>{let l=(await m.getJobs(["waiting"])).filter(r=>r.data?.session_kind==="lane").sort((r,d)=>r.timestamp-d.timestamp);if(l.length===0)return{found:0};for(let r of l)try{await r.updateData({...r.data,demand_reaffirmed_at_ms:p})}catch{}for(let r of l.slice(1))try{await r.remove()}catch{}return{found:l.length}},close:()=>m.close()}},k=async e=>{let a=await n.redis.hgetall(`lanes:${e}`),m=[],p=new Map;for(let[r,d]of Object.entries(a)){let o=v(d);o&&o.proxy_url===n.docHostUrl&&(m.push(r),p.set(r,o.region))}if(m.length===0)return[];let g=await n.redis.mget(...m.map(r=>`lane_hosts:${r}`)),l=[];return m.forEach((r,d)=>{let o=g[d];o&&l.push({laneId:r,host:o,region:p.get(r)})}),l},T=async(e,a,m,p,g)=>{let l=m,r=p,d=g;if(typeof l!="string"||l===""||typeof r!="string"||r===""){let A=n.catalogIdentity?await n.catalogIdentity(a).catch(()=>null):null;if(A)l=A.app,r=A.fn,d=A.sharedApp??d;else{let $=h.get(e)??0;if(s()-$<M)return;throw h.set(e,s()),new P("lane demand refused: the pick carried no app/fn identity and no catalog row names the pick's model \u2014 a new lane can only be admitted through session-api with the app and function (roll out the proxy's identity wire, or publish the model's catalog row)")}}let o=c.get(e)??0,L=s();if(L-o<M)return;if(c.set(e,L),(await w(e).reassertWaiting(s()).catch(A=>{throw c.delete(e),A})).found>0){_.set(a??"",(_.get(a??"")??0)+1),n.onEvent?.({kind:"lane_demand_reaffirmed",pool:e,model:a});return}let x=`lane-${I().replaceAll("-","")}`,E=await n.admission.createLaneSession({pool:e,app:l,fn:r,...d?{sharedApp:!0}:{},laneId:x,laneHostUrl:n.docHostUrl});if(E.sessionId!==x)throw new Error(`session-api lane admission returned session_id "${E.sessionId}" for requested logical_id "${x}" \u2014 refusing to fork the lane identity`);u.set(a??"",(u.get(a??"")??0)+1),b.delete(e),n.onEvent?.({kind:"lane_demand_enqueued",pool:e,model:a})};return{async pick({pool:e,app:a,fn:m,sharedApp:p,model:g,holdMs:l=0}){if(f.add(e),n.targets!==void 0&&g!==void 0&&!n.targets.some(i=>i.model===g)){let i=`no pooler target for ${g} \u2014 refusing to mint a lane demand`;throw y.set("untargeted",(y.get("untargeted")??0)+1),b.set(e,i),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:i}),new D(e,g)}let r=async()=>{try{await T(e,g,a,m,p)}catch(i){let R=i instanceof Error?i.message:String(i),x=i instanceof P?"identity":"admission";y.set(x,(y.get(x)??0)+1),b.set(e,R),n.onEvent?.({kind:"lane_demand_failed",pool:e,model:g,reason:R})}},d=async()=>{try{return await k(e)}catch{return[]}},o=await d();if(o.length>0){let i=n.laneMinFor?.(e)??0;return i>o.length&&(async()=>{for(let R=o.length;R<i;R++)await r()})(),o}let L=s()+l;for(await O(r(),l);s()<L;){if(await new Promise(i=>setTimeout(i,V)),o=await d(),o.length>0)return o;await O(r(),L-s())}return[]},async status(){let e=[...f].sort();return Promise.all(e.map(async a=>{let m=[];try{let p=await n.redis.hgetall(`lanes:${a}`),g=Object.keys(p),l=g.length===0?[]:await n.redis.mget(...g.map(d=>`lane_hosts:${d}`)),r=s();m=g.map((d,o)=>{let L=p[d],i=L===void 0?null:v(L);return{laneId:d,occupantId:i?.occupant_id??"",capacity:i?.capacity??0,heartbeatAgeMs:i===null?null:r-i.heartbeat_ms,advertisedHere:i?.proxy_url===n.docHostUrl,hosted:!!l[o]}})}catch{}return{pool:a,lanes:m,lastDemandAt:c.get(a)??null}}))},demandCounters(){return[...new Set([...u.keys(),..._.keys()])].sort().map(a=>({model:a,enqueued:u.get(a)??0,reaffirmed:_.get(a)??0}))},demandRefusals(){return[...y.entries()].sort(([e],[a])=>e.localeCompare(a)).map(([e,a])=>({reason:e,count:a}))},demandFailure(e){return b.get(e)??null},async close(){await Promise.all([...t.values()].map(e=>e.close().catch(()=>{}))),t.clear()}}}var q=4e3,j=5e3;function Q(n){return(s,t)=>n(s,{...t,signal:AbortSignal.timeout(q)})}function Y(n){return{createLaneSession:async({pool:s,app:t,fn:c,sharedApp:h,laneId:u,laneHostUrl:_})=>{let y=await U(n.apiKey,{baseUrl:n.baseUrl,expiresIn:300,allowedFunctions:[`${t}/${c}`],bindPrincipal:!0,...h?{sharedApp:!0}:{},fetch:Q(n.fetch??globalThis.fetch)}),b=n.fetch??globalThis.fetch,f;try{f=await b(`${n.baseUrl}/api/sessions/create`,{method:"POST",signal:AbortSignal.timeout(j),headers:{"content-type":"application/json",authorization:`Bearer ${y.token}`,"x-tenant-id":y.orgId},body:JSON.stringify({app:t,function:c,...h?{shared_app:!0}:{},logical_id:u,idempotency_key:u,concurrency_key:u,lane_host_url:_})})}catch(k){throw new Error(`session-api lane admission for ${u} (app ${t}/${c}) failed: ${k instanceof Error?k.message:String(k)}`)}let w={};try{w=await f.json()}catch{}let S=w.session_id;if(f.status!==200||w.status!=="allocated"||typeof S!="string"){let k=typeof w.message=="string"?w.message:`HTTP ${f.status}`;throw new Error(`session-api lane admission refused for ${u} (app ${t}/${c}): ${k}`)}return{sessionId:S}}}}C();var J="urun:catalog:v1";function ne(n){let s=n.refreshMs??5e3,t=n.now??Date.now,c=null,h=0,u=null,_=async()=>{let b=await n.redis.hgetall(J),f=[];for(let w of Object.values(b))try{f.push(JSON.parse(w))}catch{process.stderr.write(`[lane-catalog] dropping malformed catalog row (bad JSON)
|
|
2
2
|
`)}return c=f,h=t(),f},y=()=>c===null||t()-h>=s;return{rows(){return y()?(u||(u=_().finally(()=>{u=null})),u):Promise.resolve(c)},close(){c=null,u=null}}}export{G as a,X as b,Y as c,J as d,ne as e};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as ne}from"./chunk-CAR4AEQJ.js";import{e as ue,f as B,g as pe,h as fe}from"./chunk-U6TUJPC3.js";import{c as Z,f as j,g as ee,p as oe}from"./chunk-64VO62LW.js";import{a as me,b as W}from"./chunk-WWFK27D2.js";import{c as le}from"./chunk-2AFSBZLN.js";import{a as V}from"./chunk-Q3AIBMET.js";import{b as Y,d as $}from"./chunk-PXV7QBSD.js";import{b as te,c as se,d as re,g as ie,j as R,m as H,n as _,o as ae,r as N,s as L,t as ce,u as de}from"./chunk-CUO2JOW4.js";import{c as v}from"./chunk-YSFSRI3D.js";v();import{App as q,createClientToken as Ee,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS as He,DEFAULT_WHEN_LIVE_TIMEOUT_MS as be,isWakingPhase as Be,SessionFailedError as K}from"@urun-sh/core";v();import{SessionFailedError as Ie}from"@urun-sh/core";var G=2;function _e(e){let o=e?.type;return o==="response.created"||o==="response.in_progress"}function Le(e){let o=e?.type;return o==="response.completed"||o==="error"}function ge(e){return async function(s,i){let a=await e.sessionFor(s.model);return(async function*(){for(let l=1;l<=G;l++){let{app:g,entry:y,identity:h}=l===1?a:await e.sessionFor(s.model);i?.({sessionId:e.sessionIdOf?.(y)??null,identity:h});let d=!1,p=!1;try{let m=await e.createStream(y,s);for await(let f of m){if(Le(f)&&(d=!0),_e(f)){if(l>1)continue}else p=!0;yield f}}catch(m){if(m instanceof Ie&&(m.kind==="never-live"||m.kind==="create-failed")){try{e.onAdmissionVerdict?.(g,y,m)}catch{}throw m}if(l<G&&!p){await e.evict(g,y);continue}throw m}if(d)return;if(l<G&&!p){await e.evict(g,y);continue}return}})()}}import{randomUUID as ve}from"crypto";v();import{request as Te}from"http";var Fe="/pooler/v1/inference",k=class extends Error{constructor(s,i,a,c){super(a);this.status=s;this.code=i;this.retryAfterSeconds=c;this.name="PoolerTransportError"}status;code;retryAfterSeconds},Re=e=>{if(typeof e.instructions=="string"&&e.instructions!=="")return e.instructions;let o=e.messages?.find(s=>s.role==="system"||s.role==="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content)},Ne=e=>{let o=e.messages?.find(s=>s.role!=="system"&&s.role!=="developer");if(o!==void 0)return typeof o.content=="string"?o.content:JSON.stringify(o.content);if(typeof e.input=="string")return e.input;if(Array.isArray(e.input)){let s=e.input.find(i=>{if(i===null||typeof i!="object"||!("role"in i))return!0;let a=i.role;return a!=="system"&&a!=="developer"});if(s===void 0)return;if(typeof s=="string")return s;if(s!==null&&typeof s=="object"&&"content"in s){let i=s.content;return typeof i=="string"?i:JSON.stringify(i)}return JSON.stringify(s)}},we=e=>new Promise((o,s)=>{let i=[];e.on("data",a=>i.push(a)),e.on("end",()=>o(Buffer.concat(i).toString("utf8"))),e.on("error",s)}),Me=async e=>{let o="pooler_error",s=`the pooler refused the request (HTTP ${e.status})`;try{let i=JSON.parse(await we(e.body));if(i!==null&&typeof i=="object"&&"error"in i){let a=i.error;a!==null&&typeof a=="object"&&"code"in a&&typeof a.code=="string"&&(o=a.code),a!==null&&typeof a=="object"&&"message"in a&&typeof a.message=="string"&&(s=a.message)}}catch{}return new k(e.status,o,s,e.retryAfterSeconds)};async function De(e,o,s,i,a){let c=new URL(`${e.baseUrl.replace(/\/+$/,"")}${Fe}`),l=JSON.stringify({region:e.region,model:i,request_id:s,streaming:a,payload:o,affinity:{systemPrompt:Re(o),firstMessage:Ne(o)}});return new Promise((g,y)=>{let h=Te({hostname:c.hostname,port:c.port===""?void 0:Number(c.port),path:`${c.pathname}${c.search}`,method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json",accept:a?"text/event-stream":"application/json","content-length":String(Buffer.byteLength(l))}},d=>{let p=Number(d.headers["retry-after"]??"");g({status:d.statusCode??0,retryAfterSeconds:Number.isFinite(p)?p:void 0,body:d})});h.on("error",d=>y(new k(502,"pooler_unreachable",`the pooler channel failed: ${d.message}`))),h.end(l)})}var ye=e=>{if(!e.startsWith("data: "))return null;let o=e.slice(6).trim();if(o===""||o==="[DONE]")return null;let s;try{s=JSON.parse(o)}catch{return null}if(s===null||typeof s!="object")return null;let i=s;if(i.t===void 0&&i.error!==null&&typeof i.error=="object"){let a=i.error.code;return{t:"error",code:typeof a=="string"?a:null,body:i}}return i};async function*xe(e){let o="";for await(let i of e.body)for(o+=String(i);;){let a=o.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);if(a===-1)break;let c=o.slice(0,a);o=o.slice(a+2);let l=ye(c);l!==null&&(yield l)}let s=ye(o);s!==null&&(yield s)}async function on(e,o,s,i){let a=Y(o,s,i),c=a.model??"";if(c==="")throw new k(400,"missing_model","the pooler submit requires a model");let l=await De(e,a,s,c,o.stream===!0);if(l.status>=400)throw await Me(l);let g=o.stream===!0?$(s,xe(l)):await Ce(l,s);return(async function*(){yield{type:"response.created",response:{id:`resp_${s}`,status:"in_progress"}},yield*g})()}async function Ce(e,o){let s=await we(e.body),i=null;try{let c=JSON.parse(s);c!==null&&typeof c=="object"&&(i=c)}catch{i=null}if(i===null)throw new k(502,"pooler_bad_body","the pooler answered a non-object body");let a=i;return $(o,(async function*(){yield a})())}v();import{encodeStreamEnvelope as he}from"@urun-sh/core";var Ue="audio";function Se(e){let o=e.streamEndpoint(Ue);return{sessionId:e.id,appendInputAudio(s,i){let a=Buffer.from(s,"base64");if(a.byteLength!==0){if(i===void 0){o.send(he(new Uint8Array(a)));return}o.send(he({pcm16:s,capture_wall_ms:i}))}},onOutputAudio(){return()=>{}}}}v();import{encodeStreamEnvelope as $e}from"@urun-sh/core";var je="rt-video-in";function Pe(e){let o=e.streamEndpoint(je);return{sendInputFrame:async s=>{o.send($e(s))}}}var We=0,Ge=4,qe=4;function Tn(e,o){let s=(l,g)=>{let y=(e[l]??"").trim();if(!y)return g;let h=Number.parseInt(y,10);if(!Number.isInteger(h)||h<1)throw new Error(`${l} must be a positive integer (got ${JSON.stringify(e[l])})`);return h},i=(e.URUN_DECISION_POOL_MIN??"").trim();if(i==="0")return null;let a=i?Number.parseInt(i,10):We;if(!Number.isInteger(a)||a<0)throw new Error(`URUN_DECISION_POOL_MIN must be a non-negative integer (got ${JSON.stringify(e.URUN_DECISION_POOL_MIN)})`);let c=s("URUN_DECISION_POOL_MAX",Math.max(a,Ge));return{min:a,max:c,idleGraceMs:3e4,inFlightCap:s("URUN_DECISION_POOL_INFLIGHT_CAP",qe),replicaId:(e.URUN_REPLICA_ID??"").trim()||o||"proxy"}}function Fn(e){let o=(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S??"").trim();if(!o)return B;let s=Number.parseInt(o,10);if(!Number.isInteger(s)||s<=0)throw new Error(`URUN_DECISION_STREAM_IDLE_TIMEOUT_S must be a positive integer (got ${JSON.stringify(e.URUN_DECISION_STREAM_IDLE_TIMEOUT_S)})`);return s*1e3}function J(e,o,s,i){let a=e[s];if(typeof a!="function")throw new Error(`app "${o}" has no function "${s}" (set URUN_FUNCTION)`);let c=i?a(void 0,i):a();if(typeof c.end!="function")throw new Error(`app "${o}" function "${s}" returned a session without end()`);return c}function Ae(e,o,s,i){let{baseUrl:a,orgId:c,auth:l}=e,g=o.fnName??e.fnName,y=e.sessionStartOptions?.(s),h=i||y||o.sharedApp?{...o.sharedApp?{sharedApp:!0}:{},...y,...i}:void 0,d=w=>({session:w,responses:new V(w),gone:me(w,s)});if(l.lane==="jwt"){let w=q(o.appSlug,{baseUrl:a,orgId:c,jwt:l.jwt});return d(J(w,o.appSlug,g,h))}if(l.lane==="machine"||l.lane==="user"){let w=l.lane==="machine"?l.machineToken:l.userToken,{gatewayUrl:I}=l,T=(typeof e.subject=="function"?e.subject():e.subject)??ve(),F=q(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(w,{baseUrl:I,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:T,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(J(F,o.appSlug,g,h))}let{apiKey:p,gatewayUrl:m}=l,f=(typeof e.subject=="function"?e.subject():e.subject)??ve(),S=q(o.appSlug,{baseUrl:a,orgId:c,getAccessToken:async()=>(await Ee(p,{baseUrl:m,expiresIn:300,allowedFunctions:[`${o.appSlug}/${g}`],subject:f,...o.sharedApp?{sharedApp:!0}:{}})).token});return d(J(S,o.appSlug,g,h))}function ke(e){let o=e.session.id;if(typeof o!="string"||o.length===0)throw new Error("pooled session exposes no stable session id \u2014 the session-identity seam requires @urun-sh/core Session (session.id)");return o}function X(e){if(e.kind==="never-live")return!0;if(e.kind!=="create-failed")return!1;let o=e.status.error?.httpStatus,s=e.status.error?.code;return o===410||o===409&&(s==="cancelled"||s==="expired")?!0:s==="client_ended"}var Je=new Set(["error","paused"]);function Rn(e){let{auth:o,catalog:s}=e,i=null,a=(l,g)=>{let y=Ae(e,l,g);return e.onSessionOpen&&typeof y.session.id=="string"&&y.session.id!==""&&e.onSessionOpen(g,y.session.id),y.gone.onGone(()=>{i?.evict(g,y)}),y},c=new de({sharedOnlyListing:e.sharedOnlyListing===!0,defaultApp:e.defaultApp,fnName:e.fnName,openSession:a,closeSession:async l=>{if(l.gone.dispose(),l.audioDispose?.(),e.release==="detach"){if(typeof l.session.detach!="function")throw new Error('pooled session exposes no native detach() \u2014 the release:"detach" lane requires @urun-sh/core Session.detach');l.session.detach();return}await l.session.end()},listApps:o.lane==="api-key"?()=>ae({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,listCatalog:e.catalogRows??(s?()=>ne(s):null),listPrices:s?()=>re(s):null,shared:e.catalogRows?async()=>{let l=await e.catalogRows();return te(l)}:o.lane==="api-key"?()=>se({apiUrl:e.apiUrl,apiKey:o.apiKey}):null,sessionKey:ke});return i=c,e.defaultApp!==null&&c.seed(e.defaultApp,a({appSlug:e.defaultApp},L({appSlug:e.defaultApp}))),c}function Nn(e,o){let s=e.decisionPool;if(!s)throw new Error("wireDecisionPool called without BackhaulConfig.decisionPool");let i=s.replicaId??"proxy",a=new Map,c=new Map,l=new Map,g=d=>{process.stderr.write(`[decision-pool] ${d}
|
|
4
|
+
`)},y=(d,p)=>{let m=a.get(p);if(m)return m;let f=new ue({min:s.min,max:s.max,idleGraceMs:s.idleGraceMs,inFlightCap:s.inFlightCap,replicaId:i,openSlot:async S=>{let w=Ae(e,d,p,{concurrencyKey:S.concurrencyKey});return w.gone.onGone(I=>I.bindingLost?f.evict(w):f.markSessionDead(w)),await C(w.session),g(`slot attached pool=${p} slot=${S.concurrencyKey} session=${w.session.id??"(no id)"}`),w},closeSlot:async S=>{S.gone.dispose(),S.audioDispose?.(),await S.session.end()},onDetach:(S,w)=>g(`slot detached pool=${p} slot=${S.concurrencyKey} reason=${w}`),terminalOpenFailure:S=>S instanceof K&&X(S)});return c.set(p,{target:d,env:s}),a.set(p,f),f},h=async(d,p)=>{let m=c.get(p);if(m)try{let f=await o.poolTuningFor(d);y(d,p).retune({min:f?.min??m.env.min,max:f?.max??m.env.max,inFlightCap:f?.in_flight_cap??m.env.inFlightCap,idleGraceMs:f?.idle_grace_s!==void 0?f.idle_grace_s*1e3:m.env.idleGraceMs,warmWaitMs:f?.warm_wait_s!==void 0?f.warm_wait_s*1e3:void 0})}catch(f){g(`pool tuning refresh failed pool=${p} reason=${f instanceof Error?f.message:String(f)}`)}};return{async boot(){if(e.defaultApp===null)return;let d={appSlug:e.defaultApp};await y(d,L(d)).boot()},async sessionFor(d){let p=await o.resolveTargetFor(d),m=L(p),f=y(p,m);await h(p,m);let S=await f.acquire({timeoutMs:f.requestWaitMs}),w=l.get(S.entry)??[];return w.push(S),l.set(S.entry,w),{app:m,entry:S.entry,identity:ce(p)}},async warmFor(d){let p=await o.resolveTargetFor(d);await y(p,L(p)).boot()},end(d){let p=l.get(d)?.shift();p&&(l.get(d)?.length===0&&l.delete(d),p.release())},evict(d){for(let p of a.values())p.evict(d)},markSessionDead(d){for(let p of a.values())p.markSessionDead(d)},reap(){for(let[d,{target:p}]of c)h(p,d).then(()=>{let m=a.get(d);m&&m.reap()})},async pingReady(d){for(let p of a.values())if(await p.pingReady(d))return!0;return!1},stats(){return[...a.entries()].map(([d,p])=>({poolKey:d,...p.stats()}))},async drain(d){await Promise.all([...a.values()].map(p=>p.drain({timeoutMs:d})))},async close(){await Promise.all([...a.values()].map(d=>d.close()))}}}function Ke(e){return Be(e?.name)?e?.runtime?.wake?.expectedWakePath==="portable-golden-restore"?be:He:be}async function C(e,o){let s=e.whenLive;if(typeof s!="function")throw new Error("pooled session exposes no native whenLive() \u2014 the audio lane must wait for the session's own admission (cold wake: queued \u2192 demand \u2192 promote) before wiring media; a session without the core Session.whenLive surface cannot be served audio");await s.call(e,{timeout:Ke(e.phase),signal:o})}async function Xe(e){if(typeof e.cancel=="function")try{await e.cancel();return}catch{}if(typeof e.detach!="function")throw new Error("pooled session exposes neither cancel() nor detach() \u2014 the client-gone abandon path requires the @urun-sh/core Session native lifecycle surface");e.detach()}async function Oe(e){let o=e.phase?.name;if(o==="live"||o==="paused"){if(typeof e.detach!="function")throw new Error("the dedicated dial session reads live but exposes no native detach() \u2014 the client-gone release refuses to park a serving lane");e.detach();return}if(typeof e.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the client-gone release requires the @urun-sh/core Session terminal surface");await e.end()}function x(e){return e.reason instanceof Error?e.reason:new Error("the client socket closed")}function Mn(e,o=ee,s,i,a=B,c){let l=new WeakMap,g=new WeakMap,y=new WeakMap,h=new WeakMap,d=new WeakMap,p=n=>{let t=n.session.id;return typeof t=="string"&&t.length>0?t:null},m="lane",f=n=>{let t=_(n);if(!c||!t||t.app!==m)return null;let r=c.entryFor(t.key);if(!r)throw new R(`the lane behind this handle (${t.key}) is gone \u2014 its runtime released it or the host lost it; it cannot be reattached. Reconnect without a handle to pick a lane again.`);return{laneId:t.key,entry:r}},S=async n=>f(n)?.entry??(await e.sessionForHandle(n)).entry,w=n=>{let t=l.get(n);if(!t){let r={waiting:0,gone:new AbortController};d.set(n,r),t=(async()=>{if(await C(n.session,r.gone.signal),r.gone.signal.aborted)throw x(r.gone.signal);d.get(n)===r&&d.delete(n);let u=await Z(n.session,await o());return Object.assign(u,{sessionId:n.session.id})})(),l.set(n,t),t.then(u=>{l.get(n)===t&&(n.audioDispose=()=>u.dispose())},()=>{}),t.catch(()=>{l.get(n)===t&&l.delete(n)}),t.then(()=>{d.get(n)===r&&d.delete(n)},()=>{d.get(n)===r&&d.delete(n)})}return t},I=n=>{let t=h.get(n);return t||(t=(async()=>{let r=await w(n);return{appendInputAudio:(u,E)=>r.appendInputAudio(u,E),onOutputAudio:u=>r.onOutputAudio(u),sessionId:p(n)}})(),h.set(n,t),t.catch(()=>{h.get(n)===t&&h.delete(n)})),t},T=async(n,t,r,u=!1)=>{let E=()=>u?Oe(n.session):Xe(n.session);if(r?.aborted){let O=d.get(n);throw(l.get(n)===void 0||O!==void 0&&O.waiting===0)&&await E().catch(()=>{}),x(r)}let b=t(n),P=d.get(n);return P!==void 0&&P.waiting++,r===void 0?b:new Promise((O,A)=>{let z=()=>{P!==void 0&&--P.waiting===0&&d.get(n)===P&&(P.gone.abort(),d.delete(n),l.delete(n),h.delete(n),E().catch(()=>{})),A(x(r))};r.addEventListener("abort",z,{once:!0});let Q=()=>r.removeEventListener("abort",z);b.then(U=>{Q(),O(U)},U=>{Q(),A(U)})})},F=async(n,t,r)=>{try{return await r}catch(u){throw(u instanceof R||u instanceof K&&X(u))&&(e.evict(n,t),u instanceof K&&s?.(n,u.kind==="never-live"?"never-live":"create-failed")),u}};return{createResponse:ge({sessionFor:c?async n=>{let t=await e.resolveTargetFor(n);if(t.sharedApp)try{let r=await c.sessionFor(n,t);return{app:r.app,entry:r.entry,identity:r.identity}}catch(r){if(r instanceof le)return i?i.sessionFor(n):e.sessionFor(n);if(r instanceof k)return console.error(`[pooler-fallback] pooler channel failed for ${n} (${r.name} ${r.code}: ${r.message}) \u2014 serving via the per-request path`),i?i.sessionFor(n):e.sessionFor(n);throw r}return i?i.sessionFor(n):e.sessionFor(n)}:i?n=>i.sessionFor(n):n=>e.sessionFor(n),sessionIdOf:n=>p(n),evict:(n,t)=>{c&&c.owns(t)?c.evict(t):i?i.evict(t):e.evict(n,t)},onAdmissionVerdict:(n,t,r)=>{X(r)&&(c&&c.owns(t)?c.evict(t):i?i.markSessionDead(t):e.evict(n,t),s?.(n,r.kind==="never-live"?"never-live":"create-failed"))},createStream:async(n,t)=>{try{await C(n.session);let r=pe(W(await n.responses.responses.create(t),n.gone),a);if(!i&&!c)return r;let u=n;return(async function*(){try{yield*r}catch(b){throw fe(b)&&(c&&c.owns(u)?c.evict(u):i&&(b instanceof R&&!b.bindingLost?i.markSessionDead(u):i.evict(u))),b}finally{c&&c.owns(u)?c.release(u):i?.end(u)}})()}catch(r){throw c&&c.owns(n)?c.release(n):i&&i.end(n),r}}}),listModels:()=>e.modelList(),openRouterModels:()=>e.openRouterModels(),supportsImages:(n,t)=>e.supportsImages(n,t),listImageModels:()=>e.imageModelList(),catalogIdentity:n=>e.catalogIdentityFor(n),servingAppSlug:async n=>await e.servingAppSlugFor(n),supportsAudio:n=>e.supportsAudio(n),supportsSpeech:n=>e.supportsSpeech(n),speechVoices:n=>e.speechVoices(n),supportsTranscription:n=>e.supportsTranscription(n),transcriptStreamFor:n=>e.transcriptStreamFor(n),listSpeechToTextModels:()=>e.speechToTextModelList(),openAudio:async(n,t)=>{let{app:r,entry:u}=await e.sessionFor(n);return await F(r,u,T(u,w,t))},openAudioOn:async(n,t,r,u)=>{let E=f(n);if(E){let A=E.entry.session;return Se(A)}let{app:b,entry:P}=await e.sessionForHandle(n);if(u&&P.session.phase?.name!=="live"){let A=P.session.phase?.name;u({status:A==="queued"||A==="waiting_for_capacity"?A:"pending",reason:`the dial's session is ${A??"not yet admitted"} \u2014 the connection waits for admission`})}let O=_(n)?.app.startsWith(N)??!1;return await F(b,P,T(P,I,t,O))},openTurnsOn:async function*(n,t){if(t?.aborted)throw x(t);let r=await S(n);yield*ie(r.session,t)},openVideoOn:async n=>{let t=f(n);if(t)return Pe(t.entry.session);let{entry:r}=await e.sessionForHandle(n),u=g.get(r);return u||(u=j(r.session),g.set(r,u)),u},openVideo:async n=>{let{entry:t}=await e.sessionFor(n),r=g.get(t);return r||(r=j(t.session),g.set(t,r)),r},openVideoOut:async n=>{let{entry:t}=await e.sessionFor(n),r=y.get(t);return r||(r=oe(t.session),y.set(t,r)),r},sessionHandle:async n=>{if(c){let t=await e.resolveTargetFor(n);if(t.sharedApp){let r=await c.sessionFor(n,t),u=p(r.entry);if(u===null)throw new Error("lane pick returned an entry with no lane id \u2014 the lane session must carry its laneId as `id`");return H(m,u)}}return(await e.handleFor(n)).handle},dedicatedSessionHandle:async n=>{if(!(await e.resolveTargetFor(n)).sharedApp)return(await e.handleFor(n)).handle;let{app:r,entry:u}=await e.dedicatedSessionFor(n);return H(r,ke(u))},releaseSessionHandle:n=>{let t=_(n);if(!t)return;if(t.app.startsWith(N)){(async()=>{let u=null;try{u=(await e.sessionForHandle(n)).entry}catch{return}await Oe(u.session).catch(()=>{}),await e.evict(t.app,u)})();return}if(!c||t.app!==m)return;let r=c.entryFor(t.key);r&&c.release(r)},endDedicatedSession:async n=>{let t=_(n);if(!t||!t.app.startsWith(N))return;let r=null;try{r=(await e.sessionForHandle(n)).entry}catch{return}if(typeof r.session.end!="function")throw new Error("the dedicated dial session exposes no end() \u2014 the app-close verb requires the @urun-sh/core Session terminal surface");let u=await r.session.end();return await e.evict(t.app,r),u},speechSessionHandle:async n=>(await e.speechHandleFor(n)).handle,evictSpeechSession:async n=>{let{app:t,entry:r}=await e.sessionForHandle(n);await e.evict(t,r)},createResponseOn:async(n,t,r)=>{let u=await S(n);await C(u.session);let E=r!==void 0&&f(n)?new V({...u.session,consumerId:r},{sessionTag:r}):u.responses;return W(await E.responses.create(t),u.gone)},onSessionEnd:async(n,t)=>{let r=f(n);if(r)return r.entry.gone.onGone(P=>t({timeLeftMs:null,reason:P.message}));let{entry:u}=await e.sessionForHandle(n),E=u.session;if(typeof E.onPhase!="function")throw new Error("pooled session exposes no onPhase \u2014 session-end (goAway) wiring requires @urun-sh/core Session");let b=!1;return E.onPhase(P=>{if(b||!Je.has(P.name))return;b=!0;let O=E.endsAt??null;t({timeLeftMs:O?Math.max(0,O.getTime()-Date.now()):null,reason:P.reason??`session ${P.name}`})})}}}export{k as a,on as b,Tn as c,Fn as d,Rn as e,Nn as f,Mn as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();import{gcRequest as w}from"@urun-sh/core/internal";i();var v="llm-resp";async function*h(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let
|
|
1
|
+
import{a as m}from"./chunk-7KRHHEKZ.js";import{c as i}from"./chunk-YSFSRI3D.js";i();function _(e,t,o,n){let s=e.response??{},r={request_id:o,consumer_id:n,stream:!0,kind:"chat",messages:t};return typeof s.instructions=="string"&&(r.instructions=s.instructions),Array.isArray(s.modalities)&&(r.modalities=s.modalities),typeof s.temperature=="number"&&(r.temperature=s.temperature),typeof s.max_output_tokens=="number"&&(r.max_output_tokens=s.max_output_tokens),s.tools!==void 0&&(r.tools=s.tools),r}function f(e,t,o){let n={request_id:t,consumer_id:o,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(n.model=e.model),e.tools!==void 0&&(n.tools=e.tools),e.tool_choice!==void 0&&(n.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(n.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(n.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(n.stop=e.stop),typeof e.reasoning_effort=="string"&&(n.reasoning_effort=e.reasoning_effort),typeof e.instructions=="string"&&(n.instructions=e.instructions),e.chat_template_kwargs!==void 0&&(n.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(n.response_format=e.response_format),typeof e.voice=="string"&&(n.voice=e.voice),typeof e.language=="string"&&(n.language=e.language),n}i();function y(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,o=t.body??{},n=o.error,s=n?.message??o.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:n?.type??"urun_error",code:t.code??n?.code??null,message:s}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}i();import{gcRequest as w}from"@urun-sh/core/internal";i();var v="llm-resp";async function*h(e,t){let o=`resp_${e}`,n=new Map;for await(let s of t){let r=s;if(r.t==="delta"){if(typeof r.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:r.delta}),typeof r.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:r.reasoning}),Array.isArray(r.tool_calls))for(let a of r.tool_calls){let p=typeof a.index=="number"?a.index:0,u=n.get(p)??{};a.id&&(u.id=a.id),a.function?.name&&(u.name=a.function.name),n.set(p,u),yield{type:"response.function_call_arguments.delta",item_id:`fc_${e}_${p}`,tool_index:p,call_id:u.id,name:u.name,delta:a.function?.arguments??""}}}else if(r.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...r.body}};return}else if(r.t==="error"){yield y(r);return}}}async function*g(e,t){let o=`${v}:${t}`;yield{type:"response.created",response:{id:`resp_${t}`,status:"in_progress"}};try{yield*h(t,e.stream(o).messages())}finally{try{w(e.doc("llm"),t)}catch{}}}i();import{gcRequest as E}from"@urun-sh/core/internal";var k=class{constructor(t,o=15e3,n){this.session=t;this.docSyncTimeoutMs=o;this.sessionTag=n===void 0?t.sessionId??globalThis.crypto.randomUUID():n}session;docSyncTimeoutMs;sessionTag;get consumerId(){return this.session.consumerId}write(t){this.sessionTag!==null&&(t.session_tag=this.sessionTag),this.session.doc("llm").set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,o){return this.writeGated(o,()=>{let n=f(t,o,this.consumerId);return this.write(n),g(this.session,o)})}sendResponseCreate(t,o,n){return this.writeGated(n,()=>{let s=_(t,o,n,this.consumerId);return this.write(s),g(this.session,n)})}cancelTurn(t){try{E(this.session.doc("llm"),t)}catch{}}async writeGated(t,o){try{await m(this.session.doc("llm"),this.docSyncTimeoutMs,"the request envelope write")}catch(n){throw new Error(`[urun] responses dial ${t} aborted before its envelope write: ${n instanceof Error?n.message:String(n)}`)}return o()}};export{_ as a,f as b,y as c,h as d,g as e,k as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as r}from"./chunk-
|
|
1
|
+
import{f as r}from"./chunk-PXV7QBSD.js";import{c as e}from"./chunk-YSFSRI3D.js";e();var s=0;function a(){return s+=1,`req_${Date.now().toString(36)}_${s.toString(36)}`}var o=class{transport;constructor(t,n){this.transport=new r(t,void 0,n?.sessionTag)}responses={create:async t=>{let n=a(),i=await this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*i})(),{requestId:n})}}};export{o as a};
|