@urun-sh/openai 0.6.43 → 0.6.45

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.
Files changed (61) hide show
  1. package/dist/{ResponsesClient-2EsjJUz1.d.ts → ResponsesClient-75VdSOY-.d.ts} +1 -1
  2. package/dist/{ResponsesClient-BIcQ6p6Z.d.cts → ResponsesClient-BJDe9EBw.d.cts} +1 -1
  3. package/dist/{chunk-J3KCHTSA.js → chunk-3QZYIRAL.js} +3 -3
  4. package/dist/chunk-5JTIJPFV.js +6 -0
  5. package/dist/chunk-64VO62LW.js +1 -0
  6. package/dist/chunk-7KRHHEKZ.js +1 -0
  7. package/dist/{chunk-MJSK6W3W.js → chunk-BMSZZYSZ.js} +1 -1
  8. package/dist/chunk-GCQR62TJ.js +2 -0
  9. package/dist/chunk-LNQW3VFC.js +66 -0
  10. package/dist/chunk-NUPHEB3L.js +20 -0
  11. package/dist/chunk-PXV7QBSD.js +1 -0
  12. package/dist/{chunk-FF3RWDFM.js → chunk-Q3AIBMET.js} +1 -1
  13. package/dist/{chunk-JMSVHETI.js → chunk-X5BLQXHK.js} +1 -1
  14. package/dist/chunk-XNRPTMSL.js +1 -0
  15. package/dist/chunk-ZXQXOEVN.js +4 -0
  16. package/dist/{composite-D4_XPSas.d.ts → composite-BXbbnmL2.d.ts} +10 -1
  17. package/dist/{composite-BoS9-74g.d.cts → composite-n3axzdCh.d.cts} +35 -1
  18. package/dist/gemini-live.cjs +2 -2
  19. package/dist/gemini-live.d.cts +15 -4
  20. package/dist/gemini-live.d.ts +6 -4
  21. package/dist/gemini-live.js +1 -1
  22. package/dist/hosted/bin.cjs +48 -47
  23. package/dist/hosted/bin.js +1 -1
  24. package/dist/hosted/index.cjs +45 -44
  25. package/dist/hosted/index.d.cts +4 -4
  26. package/dist/hosted/index.d.ts +4 -4
  27. package/dist/hosted/index.js +1 -1
  28. package/dist/index.cjs +1 -1
  29. package/dist/index.d.cts +4 -4
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +1 -1
  32. package/dist/pi-extension/index.cjs +2 -2
  33. package/dist/pi-extension/index.d.cts +2 -2
  34. package/dist/pi-extension/index.d.ts +2 -2
  35. package/dist/pi-extension/index.js +1 -1
  36. package/dist/pi-extension/standalone.cjs +54 -54
  37. package/dist/pooler/bin.cjs +25 -25
  38. package/dist/pooler/bin.js +24 -24
  39. package/dist/proxy/cli.cjs +52 -51
  40. package/dist/proxy/cli.js +1 -1
  41. package/dist/proxy/conformance-probe.js +1 -1
  42. package/dist/proxy/index.cjs +32 -31
  43. package/dist/proxy/index.d.cts +19 -6
  44. package/dist/proxy/index.d.ts +11 -6
  45. package/dist/proxy/index.js +1 -1
  46. package/dist/{translator-PsmsZT62.d.cts → translator-C6MpaZS-.d.cts} +1 -1
  47. package/dist/{translator-BemK1Of5.d.ts → translator-CaOqL-V8.d.ts} +1 -1
  48. package/dist/{types-CxWQ84Ew.d.cts → types-DiYzfHYN.d.cts} +2 -5
  49. package/dist/{types-CxWQ84Ew.d.ts → types-DiYzfHYN.d.ts} +1 -1
  50. package/dist/{video-out-DPLqpGbQ.d.cts → video-out-A8qMuI36.d.cts} +1 -1
  51. package/dist/{video-out-DkMqKSOi.d.ts → video-out-IoTqIbAw.d.ts} +1 -1
  52. package/package.json +1 -1
  53. package/dist/chunk-27HP3RMZ.js +0 -6
  54. package/dist/chunk-2NKCALKY.js +0 -22
  55. package/dist/chunk-2RO722HS.js +0 -2
  56. package/dist/chunk-7DUSLXPG.js +0 -1
  57. package/dist/chunk-BFIKVTQB.js +0 -1
  58. package/dist/chunk-GDH2D3S6.js +0 -1
  59. package/dist/chunk-MOX5FG2R.js +0 -1
  60. package/dist/chunk-YRBUHHI3.js +0 -2
  61. package/dist/chunk-ZCF6EV4Y.js +0 -65
@@ -1,4 +1,4 @@
1
- import { b as UrunSessionLike } from './types-CxWQ84Ew.js';
1
+ import { b as UrunSessionLike } from './types-DiYzfHYN.js';
2
2
 
3
3
  interface ResponsesStream extends AsyncIterable<unknown> {
4
4
  readonly requestId: string;
@@ -1,4 +1,4 @@
1
- import { b as UrunSessionLike } from './types-CxWQ84Ew.cjs';
1
+ import { b as UrunSessionLike } from './types-DiYzfHYN.cjs';
2
2
 
3
3
  interface ResponsesStream extends AsyncIterable<unknown> {
4
4
  readonly requestId: string;
@@ -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 $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 Le(n,e){let t=e.filter(i=>h(`${i.model_id}-${i.variant}`)===n);if(t.length>0)return A(t);let o=e.filter(i=>h(i.model_id)===n);if(o.length>0)return A(o);let r=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:Fe(n),matches:n}:null}function Fe(n){let e=n[0],t=o=>n.every(r=>(r[o]??void 0)===(e[o]??void 0))?e[o]:void 0;return{model_id:e.model_id,variant:e.variant,gpu_spec:t("gpu_spec"),engine:t("engine"),task:t("task"),description:t("description"),size_gb:t("size_gb"),hf_repo:t("hf_repo"),updated_at:t("updated_at")}}var $=class extends Error{name="ModelCreatedError"};function T(n){if(n.length===0)return 0;let e=`${n[0].model_id}:${n[0].variant}`,t=n.map(u=>u.created_at??void 0);if(t.some(u=>u===void 0))throw new $(`model "${e}" is catalog-joined but not every model_catalog row carries created_at \u2014 the catalog generator stamps every authored row (urun-infra#2951); the listing refuses to publish a created: 0 that lies about the model's appearance date`);let o=t[0];if(!t.every(u=>u===o))throw new $(`model "${e}" has model_catalog rows that disagree on created_at ("${[...new Set(t)].join('", "')}") \u2014 created is per model id and never changes; disagreement is catalog drift`);let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(r===null)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 expected an ISO calendar date (YYYY-MM-DD), the model_catalog column's own shape`);let i=Number(r[1]),s=Number(r[2]),d=Number(r[3]),a=Date.UTC(i,s-1,d),l=new Date(a);if(l.getUTCFullYear()!==i||l.getUTCMonth()!==s-1||l.getUTCDate()!==d)throw new $(`model "${e}" carries a malformed created_at ("${o}") \u2014 not a real calendar date`);return a/1e3}function b(n){let e={id:n.id,object:n.object,created:n.created,owned_by:n.owned_by,...n.context_length!==void 0?{context_length:n.context_length}:{},...n.pricing!==void 0?{pricing:n.pricing}:{},...n.voices!==void 0?{voices:n.voices}:{},...n.capabilities!==void 0?{capabilities:n.capabilities}:{}};return"image_modes"in n?{...e,image_modes:n.image_modes}:e}function L(n,e,t){let o=Le(n,e);if(!o)return b({id:n,object:"model",created:0,owned_by:"urun"});let{row:r,matches:i}=o,s=N(i),d=T(i),a=O(r.model_id,r.variant,t),l=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{bindingLost;constructor(e,t){super(e),this.bindingLost=t?.bindingLost??!1}},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)}
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 I(n,e){return _e(n.appSlug,e)}function Ye(n){let e=n.map(o=>o.engine_args?.transcript_stream).filter(o=>o!=null);if(e.length===0)return"stt";let t=e[0];if(typeof t!="string"||t.length===0||!e.every(o=>o===t))throw new p(`the model's model_catalog rows cannot vow one engine_args.transcript_stream (found ${JSON.stringify(e)}) \u2014 the field must be a non-empty string agreeing across placements; the realtime transcription lane refuses to guess the stream the engine writes`);return t}var L=6e4,ye=class{constructor(e){this.opts=e}opts;pool=new Map;mintedIds=new WeakMap;apps={current:null};rows={current:null};shared={current:null};async swr(e,t,o){let r=e.current;return r&&Date.now()-r.at<o?r.value:r?(r.refreshing||(r.refreshing=(async()=>{try{e.current={at:Date.now(),value:await t()}}catch{}finally{r.refreshing=void 0}})()),r.value):(e.current={at:Date.now(),value:await t()},e.current.value)}seed(e,t){this.snapshotMintId(t),this.pool.set(e,Promise.resolve(t))}snapshotMintId(e){try{let t=this.keyOf(e),o=e;this.mintedIds.has(o)||this.mintedIds.set(o,t)}catch{}}async deployedApps(){return this.opts.listApps?this.swr(this.apps,()=>this.opts.listApps(),this.opts.appsTtlMs??L):[]}async sharedBlock(){return this.opts.shared?this.swr(this.shared,()=>this.opts.shared(),this.opts.appsTtlMs??L):null}async catalogRows(){return this.opts.listCatalog?this.swr(this.rows,()=>this.opts.listCatalog(),this.opts.appsTtlMs??L):[]}pricesCache=null;async priceRows(){if(!this.opts.listPrices)return[];let e=this.opts.appsTtlMs??L;if(this.pricesCache&&Date.now()-this.pricesCache.at<e)return this.pricesCache.rows;let t=await this.opts.listPrices();return this.pricesCache={at:Date.now(),rows:t},t}async pricesForListing(e){let t;try{t=await this.priceRows()}catch(r){if(r instanceof _)throw r;return this.warn(`urun /v1/models: the per-token price surface could not be read (${String(r instanceof Error?r.message:r)}) \u2014 every model is listed UNPRICED for now; Hugging Face will show no price until the read succeeds
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 I(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
4
  `),E}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
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:E;o.ok||this.warn(`urun /v1/models: the model catalog could not be read \u2014 entries fall back to the bare OpenAI fields AND no model is priced on either lane (pricing follows catalog identity, so a half-priced listing would flicker on Hugging Face)
6
- `);let a=(t?S(t):[]).map(l=>{let u=i.filter(Y=>Y.model_id===l.model_id&&Y.variant===l.variant),c=N(u),g=T(u),f=B(u),v=O(l.model_id,l.variant,s),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>F(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(I(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(I(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(I(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):I(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):I(t,o);return z(r)}async imageModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds()){let s=fe(W(i,e));s.length!==0&&o.push(b({...F(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:T(s),owned_by:"urun",image_modes:d});o.push(a)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds())R(_e(i,e))==="stt"&&o.push(F(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(s)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(s),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,Qe as b,Xe as c,rt as d,dt as e,$ as f,pt as g,bt as h,P as i,M as j,pe as k,ge as l,St as m,He as n,me as o,qe as p,q,G as r,ye as s};
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=T(u),f=B(u),v=O(l.model_id,l.variant,s),m=z(u);return b({id:`${l.model_id}:${l.variant}`,object:"model",created:g,owned_by:"urun",...c!==null?{context_length:c}:{},...v!==null?{pricing:v}:{},...m.published.length>0?{voices:[...m.published]}:{},...f!==null?{capabilities:{reasoning:f}}:{}})});return{object:"list",data:this.opts.sharedOnlyListing?a:[...e.map(l=>L(l,i,s)),...a]}}async openRouterModels(){let e=await this.sharedBlock(),[t,o]=await Promise.all([this.catalogRows(),this.pricesForListing(this.outputFreeKeys(e))]);return 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(I(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(I(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(I(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):I(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):I(t,o);return z(r)}async imageModelList(){let e=await this.catalogRows(),t=E,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:T(s),owned_by:"urun",image_modes:d});o.push(a)}return{object:"list",data:o}}async speechToTextModelList(){let e=await this.catalogRows(),t=E,o=[];for(let i of await this.availableIds())R(_e(i,e))==="stt"&&o.push(L(i,e,t));let r=await this.sharedBlock();if(r)for(let i of S(r)){let s=H(`${i.model_id}:${i.variant}`,i.model_id,i.variant,e,this.opts.listCatalog!==null);if(R(s)!=="stt")continue;let d=b({id:`${i.model_id}:${i.variant}`,object:"model",created:T(s),owned_by:"urun"});o.push(d)}return{object:"list",data:o}}async closeAll(){let e=[...this.pool.values()],t=[];if(await Promise.all(e.map(async o=>{try{await this.opts.closeSession(await o)}catch(r){t.push(String(r instanceof Error?r.message:r))}})),t.length>0)throw new Error(`failed to close ${t.length} pooled session(s): ${t.join("; ")}`)}};export{p as a,Qe as b,Xe as c,rt as d,dt as e,$ as f,pt as g,bt as h,P as i,M as j,pe as k,ge as l,St as m,He as n,me as o,qe as p,q,G as r,ye as s};
@@ -0,0 +1,6 @@
1
+ import{h as m}from"./chunk-3QZYIRAL.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.45";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
+ `)};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
+ `)}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
+ `)}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}
5
+ `)}catch(o){try{e.appendSync(e.logPath,`${new Date().toISOString()} urun compat: the crash line could not reach stderr (${String(o?.code??o)}) \u2014 the terminal is gone
6
+ `)}catch{}}e.killChild(),e.exit(1)};return e.proc.on("uncaughtException",t),e.proc.on("unhandledRejection",t),()=>{e.proc.off("uncaughtException",t),e.proc.off("unhandledRejection",t)}}function de(e,t){let n="pass --port 0 for an OS-assigned ephemeral port";return t?`port ${e} is held by another urun-openai proxy serving app ${t.app} (org ${t.org}, fn ${t.fn}, version ${t.proxy_version}) \u2014 reuse it by pointing your agent at http://127.0.0.1:${e}, or ${n}`:`port ${e} is already in use and does not answer the urun-openai /stats identity probe \u2014 ${n}`}c();var w=class extends Error{status=500;constructor(t){super(t),this.name="LaneTargetError"}},b=class extends Error{pool;constructor(t){super("no capacity available for this model right now, retry shortly"),this.name="LaneCapacityError",this.pool=t}};var U=class extends Error{pool;model;constructor(t,n){super(`no pooler target for ${n??"this model"} \u2014 refusing to mint a lane demand`),this.name="LaneNotTargetedError",this.pool=t,this.model=n}};export{w as a,b,U as c,M as d,O as e,F as f,H as g,V as h,X as i,z as j,Q as k,Z as l,ee as m,te as n,$ as o,f as p,ne as q,L as r,re as s,oe as t,ie as u,se as v,ae as w,ue as x,de as y};
@@ -0,0 +1 @@
1
+ import{c as m}from"./chunk-YSFSRI3D.js";m();var M=24e3,v="audio",w=class{constructor(e,n){this.backend=e;this.opts=n}backend;opts;source=null;sink=null;outHandlers=new Set;dataEmit=null;dataEmitChain=Promise.resolve();dataEmitFailures=0;setDataEmit(e){this.dataEmit=e}async startOutbound(){return this.source=this.backend.createSource(),this.source.track}appendInputAudio(e,n){if(!this.source)throw new Error("startOutbound() not called");let r=Buffer.from(e,"base64"),i=Math.floor(r.byteLength/2),a=new Int16Array(i);for(let s=0;s<i;s++)a[s]=r.readInt16LE(s*2);this.source.onData(a),this.dataEmit&&(this.dataEmitChain=this.dataEmitChain.then(()=>this.dataEmit(r)).catch(s=>{this.dataEmitFailures+=1,(this.dataEmitFailures===1||this.dataEmitFailures%50===0)&&console.warn(`[audio-ingest] \xA75 DATA audio emit FAILED (${this.dataEmitFailures}x): `+(s instanceof Error?s.message:String(s)))}))}async startInbound(e){if(e==null)throw new Error('startInbound: no downstream audio track \u2014 the runtime audio producer has not been consumed yet (session.stream("audio").track is null)');this.sink=this.backend.createSink(e),this.sink.onframe=n=>{let r=Buffer.from(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength).toString("base64");for(let i of this.outHandlers)i(r)}}dispose(){this.source=null,this.sink=null,this.dataEmit=null,this.backend.dispose?.()}onOutputAudio(e){return this.outHandlers.add(e),()=>this.outHandlers.delete(e)}};async function N(t,e,n=1e4){try{return await I(t,e,n)}catch(r){try{e.dispose?.()}catch{}throw r}}async function I(t,e,n){let r=new w(e,{sampleRate:24e3}),i=await r.startOutbound(),a=t.stream(v);await a.attach(i),typeof a.emit=="function"&&r.setDataEmit(u=>a.emit(u));let s=await L(t,n);return await r.startInbound(s),r}function L(t,e){let n=t.stream(v);return n.track!=null?Promise.resolve(n.track):new Promise((r,i)=>{let a,s=setTimeout(()=>{a?.(),i(new Error(`enableSessionAudio: no downstream audio track within ${e}ms (runtime produced no voice OUT / SFU audio consumer never attached)`))},e),u=o=>{o!=null&&(clearTimeout(s),a?.(),r(o))};a=n.on?.("track",u),n.track!=null&&u(n.track)})}var b="rt-video-in",k=256e3;function q(t){let e=t.stream(b),n=e.emit;if(typeof n!="function")throw new Error(`enableSessionVideo: session.stream('${b}') has no emit() \u2014 the named-DATA stream produce seam (@urun-sh/core SessionStream.emit, contract \xA75) is required for the video frame lane`);return{sendInputFrame:async r=>{if(r.byteLength===0)throw new Error("enableSessionVideo: refusing to send an empty video frame");if(r.byteLength>k)throw new Error(`enableSessionVideo: frame is ${r.byteLength} bytes \u2014 over the ${k}-byte data-channel budget (the SFU's 262144-byte SCTP ceiling drops oversize messages SILENTLY; send smaller/lower-quality frames)`);await n.call(e,r)}}}var U=24e3,f=480,_=111,x=50,h=null;async function B(){if(h)return;let t=await import("opusscript");h=t.default??t}function P(){if(!h)throw new Error("[opus-guard] opusscript module not loaded");return new h(U,1,2048)}var g=class{constructor(e=P){this.build=e;this.inner=this.build()}build;inner=null;consecutiveFailures=0;_wedged=!1;rebuild(){let e=this.build();return this.inner=e,e}get wedged(){return this._wedged||this.consecutiveFailures>=x}encode(e,n){this.inner||this.rebuild();let r=this.inner;try{let i=r.encode(e,n);return this.consecutiveFailures=0,this._wedged=!1,i}catch(i){this.consecutiveFailures+=1,this.inner=null;try{r.delete?.()}catch{}if(this.wedged)throw this._wedged=!0,new Error(`[opus-guard] encode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${i instanceof Error?i.message:String(i)}`);return null}}decode(e){this.inner||this.rebuild();let n=this.inner;try{let r=n.decode(e);return this.consecutiveFailures=0,this._wedged=!1,r}catch(r){this.consecutiveFailures+=1,this.inner=null;try{n.delete?.()}catch{}throw this.wedged?(this._wedged=!0,new Error(`[opus-guard] decode failed ${this.consecutiveFailures}x consecutively \u2014 the codec is wedged, failing loud: ${r instanceof Error?r.message:String(r)}`)):r}}dispose(){let e=this.inner;this.inner=null;try{e?.delete?.()}catch{}}};async function J(){let t=await import("werift");await B();let e=new g;return{createSource:()=>{let n=new t.MediaStreamTrack({kind:"audio"}),r=Math.random()*4294967295>>>0,i=Math.random()*65535&65535,a=Math.random()*4294967295>>>0,s=new Int16Array(0);return{track:n,onData:u=>{let o=new Int16Array(s.length+u.length);o.set(s,0),o.set(u,s.length);let d=0;for(;o.length-d>=f;){let c=o.subarray(d,d+f);d+=f;let l=Buffer.from(c.buffer,c.byteOffset,c.byteLength),y=e.encode(l,f);if(y===null){s=o.slice(d);break}i=i+1&65535,a=a+f>>>0;let A=new t.RtpHeader({version:2,payloadType:_,sequenceNumber:i,timestamp:a,ssrc:r,marker:!1}),R=new t.RtpPacket(A,y);n.writeRtp(R)}s=o.slice(d)}}},createSink:n=>{let r={onframe:null};return n.onReceiveRtp.subscribe(a=>{if(a.payload.length>3828){console.error(`[opus-guard] decode skipped: packet ${a.payload.length} B > 3828 B max`);return}let s;try{s=e.decode(a.payload)}catch(o){if(e.wedged)throw o;return}let u=new Int16Array(s.length/2);for(let o=0;o<u.length;o++)u[o]=s.readInt16LE(o*2);r.onframe?.({samples:u})}),r},dispose:()=>e.dispose()}}async function Y(){let t=await import("@roamhq/wrtc");return{createSource:()=>{let e=new t.nonstandard.RTCAudioSource;return{track:e.createTrack(),onData:r=>e.onData({samples:r,sampleRate:24e3})}},createSink:e=>{let n={onframe:null},r=new t.nonstandard.RTCAudioSink(e);return r.ondata=i=>{n.onframe?.(i)},n}}}m();import{WtControlDecoder as D,consumeWtDataStreams as F,encodeWtControlFrame as W,STREAM_END as $}from"@urun-sh/core";var p="rt-video-out",C="urun.videoOut.v1",E="h264";function O(t,e){if(!Number.isInteger(t.seq)||t.seq<0)throw new Error(`${e}: header seq must be a non-negative integer (got ${t.seq})`);if(!Number.isInteger(t.ptsUs))throw new Error(`${e}: header ptsUs must be an integer microsecond timestamp (got ${t.ptsUs})`);if(typeof t.codec!="string"||t.codec.length===0)throw new Error(`${e}: header codec must be a non-empty string`);if(typeof t.key!="boolean")throw new Error(`${e}: header key must be a boolean`)}function z(t,e){if(O(t,"encodeVideoOutRecord"),e.byteLength===0)throw new Error("encodeVideoOutRecord: refusing to encode an empty access unit");let n=new TextEncoder().encode(JSON.stringify({v:1,seq:t.seq,ptsUs:t.ptsUs,codec:t.codec,key:t.key}));if(n.byteLength>65535)throw new Error(`encodeVideoOutRecord: header JSON is ${n.byteLength} bytes \u2014 over the u16 length prefix`);let r=new Uint8Array(2+n.byteLength+e.byteLength);return r[0]=n.byteLength&255,r[1]=n.byteLength>>8,r.set(n,2),r.set(e,2+n.byteLength),r}function S(t){if(t.byteLength<2)throw new Error(`decodeVideoOutRecord: truncated record (${t.byteLength} byte(s), no header length)`);let e=t[0]|t[1]<<8;if(t.byteLength<2+e)throw new Error(`decodeVideoOutRecord: truncated record (header says ${e} bytes, ${t.byteLength-2} present)`);let n;try{n=JSON.parse(new TextDecoder().decode(t.subarray(2,2+e)))}catch(s){throw new Error(`decodeVideoOutRecord: header is not valid JSON (${String(s)})`)}let r=n;if(r===null||typeof r!="object"||r.v!==1)throw new Error(`decodeVideoOutRecord: header is not spec v1 (v=${JSON.stringify(r?.v)}) \u2014 a newer producer must be met with a newer consumer, never silently misread`);let i=r;O(i,"decodeVideoOutRecord");let a=t.subarray(2+e);if(a.byteLength===0)throw new Error("decodeVideoOutRecord: empty access unit \u2014 a record with no AU bytes is a producer bug");return{header:i,au:a.slice()}}async function K(t){let e=t.wtDataEndpoint;if(typeof e!="function")throw new Error("negotiateSessionVideoOutQuic: the core session exposes no wtDataEndpoint() \u2014 the \xA75-over-QUIC dial seam (urun-infra#1608 TransportOfferResponse.webtransport, offered with wtData: true) is required for the video OUT lane; there is no WS fallback");let n=await e.call(t),r=n.sessionId??t.sessionId;if(typeof r!="string"||r.length===0)throw new Error("negotiateSessionVideoOutQuic: no session id \u2014 the WT hello requires one and neither the negotiated endpoint nor the core session carries it");return{transport:"webtransport",url:n.url,certHashes:n.certHashes,token:n.token,sessionId:r,stream:p,codec:E,framing:C}}var X="urun.videoOut.v2-ws";function Z(t){let e=t.stream(p);if(typeof e.messages!="function")throw new Error(`openSessionVideoOutLane: session.stream('${p}') has no messages() \u2014 the named-DATA stream consume seam (@urun-sh/core SessionStream.messages, contract \xA75) is required for the video OUT lane`);let n=new Set,r=new Set,i=new Set,a=o=>{for(let d of r)d(o)},s=!1,u=async()=>{for await(let o of e.messages()){if(!(o instanceof Uint8Array)){a(new Error(`openSessionVideoOutLane: "${p}" delivered a non-BINARY \xA75 payload (${typeof o}) \u2014 spec v1 records ride BINARY envelopes only`));continue}let d;try{d=S(o)}catch(c){a(c instanceof Error?c:new Error(String(c)));continue}for(let c of n)c(d)}for(let o of i)o()};return{codec:E,onOutputFrame:o=>(n.add(o),s||(s=!0,u().catch(d=>a(d instanceof Error?d:new Error(String(d))))),()=>n.delete(o)),onLaneError:o=>(r.add(o),()=>r.delete(o)),onEnd:o=>(i.add(o),()=>i.delete(o))}}function H(t){if(t.length%2!==0||/[^0-9a-fA-F]/.test(t))throw new Error(`consumeVideoOut: certHashes entry is not hex sha-256 (${JSON.stringify(t)})`);let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}async function ee(t,e,n){let r=n??(typeof globalThis.WebTransport=="function"?(d,c)=>new globalThis.WebTransport(d,c):void 0);if(!r)throw new Error("consumeVideoOut: no WebTransport implementation \u2014 this platform has no globalThis.WebTransport; inject a connect factory (the third argument)");let i=r(t.url,{serverCertificateHashes:t.certHashes.map(d=>({algorithm:"sha-256",value:H(d)}))});await i.ready;let a=await i.createBidirectionalStream();await a.writable.getWriter().write(W({t:"hello",token:t.token,sessionId:t.sessionId}));let s=a.readable.getReader(),u=new D,o=!1;for(;!o;){let{value:d,done:c}=await s.read();if(c)throw new Error("consumeVideoOut: gateway closed the control stream before hello-ack");if(d)for(let l of u.push(d)){if(l.t==="hello-ack"){o=!0;break}throw new Error(`consumeVideoOut: gateway rejected hello (got ${JSON.stringify(l.t)} before hello-ack)`)}}await F(i.incomingUnidirectionalStreams,{onData:(d,c)=>{if(d===t.stream){if(c===$){e.onEnd?.();return}if(!(c instanceof Uint8Array)){e.onLaneError(new Error(`consumeVideoOut: "${t.stream}" delivered a non-BINARY \xA75 payload (${typeof c}) \u2014 spec v1 records ride BINARY envelopes only`));return}try{e.onFrame(S(c))}catch(l){e.onLaneError(l instanceof Error?l:new Error(String(l)))}}},onLaneError:d=>e.onLaneError(d)})}export{M as a,w as b,N as c,b as d,k as e,q as f,J as g,Y as h,p as i,C as j,E as k,z as l,S as m,K as n,X as o,Z as p,ee as q};
@@ -0,0 +1 @@
1
+ import{c as r}from"./chunk-YSFSRI3D.js";r();async function d(e,t,o){if(e.synced===!0||typeof e.onSynced!="function")return;let n;await new Promise((i,s)=>{let u=e.onSynced(()=>{clearTimeout(n),i()});n=setTimeout(()=>{u(),s(new Error(`[urun] llm doc plane never synced within ${t}ms \u2014 ${o} is withheld rather than raced into a possibly-lost pre-sync write (resumed-attach first-write-lost, prod-usw2 2026-09-23)`))},t)})}export{d as a};
@@ -1 +1 @@
1
- import{j as d}from"./chunk-J3KCHTSA.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
1
+ import{j as d}from"./chunk-3QZYIRAL.js";import{c as h}from"./chunk-YSFSRI3D.js";h();var p=3,v="llm",y=new Set(["paused","error"]);function w(i,t,l){let o=i.doc(v),a=typeof o.onConnectionState=="function",c=typeof i.onPhase=="function";if(!a&&!c)throw new Error(`session for app "${t}" exposes neither a doc connection-state surface nor onPhase \u2014 session-gone detection requires @urun-sh/core Session (SessionDocument.onConnectionState / Session.onPhase); pooling a session with no native lifecycle signal would silently swallow requests dispatched after the platform closes it`);let n=null,r=!1,s=new Set,u=[],f=e=>{if(!n){n=e;for(let S of[...s])S(e);s.clear()}};return a&&u.push(o.onConnectionState(e=>{r&&(e.consecutiveFailures<p||f(new d(`the pooled session for app "${t}" is gone: its doc backhaul failed ${e.consecutiveFailures} consecutive times (last close ${e.lastCloseCode===null?"by provider liveness reap":`code ${e.lastCloseCode}`}${e.lastCloseReason?`, reason ${JSON.stringify(e.lastCloseReason)}`:""}) \u2014 the platform closed the session (idle timeout or a serve-side crash). The entry is evicted; retry to get a fresh session.`)))})),l?.armOnFirstSync===!0&&typeof o.onSynced=="function"?u.push(o.onSynced(()=>{r=!0})):c&&u.push(i.onPhase(e=>{if(e.name==="live"){r=!0;return}r&&y.has(e.name)&&f(new d(`the pooled session for app "${t}" lost its compute binding (phase "${e.name}"). The entry is evicted; retry to get a fresh session. The named session itself is not over \u2014 it stays attachable by name.`,{bindingLost:!0}))})),{gone:()=>n,onGone(e){return n?(e(n),()=>{}):(s.add(e),()=>s.delete(e))},dispose(){s.clear();for(let e of u.splice(0))e()}}}async function*E(i,t){let l=t.gone();if(l)throw l;let o=i[Symbol.asyncIterator](),a,c=new Promise((n,r)=>{a=t.onGone(s=>r(s))});c.catch(()=>{});try{for(;;){let n=await Promise.race([o.next(),c]);if(n.done)return;yield n.value}}finally{a?.(),o.return?.(void 0)}}export{w as a,E as b};
@@ -0,0 +1,2 @@
1
+ import{c as D}from"./chunk-5JTIJPFV.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
+ `)}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};